Mike
Mike

Reputation: 75

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=('',))

Upvotes: 1

Views: 1946

Answers (3)

gebbissimo
gebbissimo

Reputation: 2659

Old question, but there are ways to do this, e.g. by inspecting frames like LightningCLI does https://github.com/Lightning-AI/pytorch-lightning/blob/be608fa355b835b9b0727df2f5476f0a1d90bc59/src/lightning/pytorch/utilities/parsing.py#L176

However, the ways above are definitely simpler and more robust.

Upvotes: 0

ivan_pozdeev
ivan_pozdeev

Reputation: 36046

__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.

Upvotes: 2

cap
cap

Reputation: 377

You can store them as attributes.

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

then just print them:

anobj = AnObject(kw='a keyword arg')
print anobj.kw
print anobj.args
print anobj.kwargs

if you want to see them all, you could take a look into its __dict__ attribute.

Upvotes: 1

Related Questions