pythonpython-2.7

Get arguments that an object's __init__ was called with


Is there a way to get an object's init argument values in python 2.7? I'm able to get the defaults through getargspec but i would like to access passed in values

import inspect

class AnObject(object):
    def __init__(self, kw='', *args, **kwargs):
        print 'Hello'

anobj = AnObject(kw='a keyword arg')
print inspect.getargspec(anobj.__init__)

Returns

Hello
ArgSpec(args=['self', 'kw'], varargs='args', keywords='kwargs', defaults=('',))

Solution

  • __init__ is treated no differently than any other function. So, like with any other function, its arguments are discarded once it returns -- unless you save them somewhere before that.

    The standard approach is to save what you need later in attributes of the instance:

    class Foo:
        def __init__(self, a, b, *args, **kwargs):
            self.a = a
            self.b = b
            <etc>
    

    "Dataclasses" introduced in 3.7 streamline this process but require data annotations:

    import dataclasses
    
    @dataclasses.dataclass
    class Foo:
        a: int
        b: str
    

    is equivalent to:

    class Foo:
        def __init__(self, a:int, b:str):
            self.a = a
            self.b = b
    

    Though see Python decorator to automatically define __init__ variables why this streamlining is not very useful in practice.