Search code examples
pythonargumentssubclassseaborndefault-value

How to access keyword argument default values of inherited class


I'm trying to make some modifications to the seaborn.JointGrid class. My plan was to make a child class and inherit most methods from the JointGrid class, like so:

import seaborn

class CustomJointGrid(seaborn.JointGrid):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

If I do this, I do not have access to the variables size, ratio, space etc., which are part of the __init__ method of JointGrid:

def __init__(self, x, y, data=None, size=6, ratio=5, space=.2,
dropna=True, xlim=None, ylim=None) 

I noticed that these variables are not initialized in JointGrid class with the usual self.size = size in the __init__ method. Perhaps this is why I can not access them from my child class?

How can I access these variables size, ratio, space etc?


Solution

  • You can use inspect.getfullargspec to do this:

    >>> import seaborn, inspect
    >>> spec = inspect.getfullargspec(seaborn.JointGrid.__init__)
    >>> defaults = spec.kwonlydefaults or {}
    >>> defaults.update(zip(spec.args[-len(spec.defaults):], spec.defaults))
    >>> defaults
    {'data': None, 'size': 6, 'ratio': 5, 'space': 0.2, 'dropna': True, 'xlim': None, 'ylim': None}
    

    Note that your code would only need to do this once, since the signature of the imported class won't change.