Creating scipy.stats random variable subclass does not result in expected object type

Viewed 266

I am trying to extend scipy.stats.rv_discrete to provide some simple distributions for the user. For example, in the simplest case they might want a distribution with a constant output. Here's my code for that:

from scipy.stats._distn_infrastructure import rv_sample

class const(rv_sample):  # a distribution with probability 1 for a single val
    def __init__(self, val, *args, **kwds):
        super(const, self).__init__(values=(val, 1), *args, **kwds)

However, this is not resulting in an object of the same type as the built-in random variable distributions, and this is messing up some operations I want to perform on distributions generically. Compare this to the poisson distribution:

from scipy.stats import poisson
import inspect

print('\nThese should both contain rv_discrete:')
print('1: ', inspect.getmro(poisson.__class__))
print('2: ', inspect.getmro(const.__class__))

print('\nThese should both be rv_frozen:')
print('1: ', inspect.getmro(poisson(5).__class__))
print('2: ', inspect.getmro(const(5).__class__))

Output:

These should both contain rv_discrete:
1:  (<class 'scipy.stats._discrete_distns.poisson_gen'>, <class 'scipy.stats._distn_infrastructure.rv_discrete'>, <class 'scipy.stats._distn_infrastructure.rv_generic'>, <class 'object'>)
2:  (<class 'type'>, <class 'object'>)

These should both be rv_frozen:
1:  (<class 'scipy.stats._distn_infrastructure.rv_frozen'>, <class 'object'>)
2:  (<class '__main__.const'>, <class 'scipy.stats._distn_infrastructure.rv_sample'>, <class 'scipy.stats._distn_infrastructure.rv_discrete'>, <class 'scipy.stats._distn_infrastructure.rv_generic'>, <class 'object'>)

Any tips on what I'm doing wrong here? I'm relatively inexperienced when it comes to subclassing so it may be something simple. Thank you!

0 Answers
Related