0

How do I access *args variable name(s) in __init__ method?

E.g.

class Parent:
    def __init__(self, *args):
        # How to access *args variable names here?
        # In this example: foo, bar
        pass

class Child(Parent):
    def __init__(self, foo, bar):
        super().__init__(foo, bar)
4
  • 4
    That's not even a meaningful concept. *args, like any other list, contains nothing but values. There's no guarantee that those values even came from variables, anyway - they could just as easily have been literals, or expressions. Commented Nov 28, 2021 at 2:22
  • This is possible in a different context. For example, a functools-wrapped wrapper can access wrapped *args variable names like so: func.__code__.co_varnames Commented Nov 28, 2021 at 2:24
  • *args and *kargs: geeksforgeeks.org/args-kwargs-python. args is for values only, kargs is for key => value. Commented Nov 28, 2021 at 2:27
  • 2
    You can't. Variables don't get passed to functions, objects do. In general, you should never have to care what the names of variables referring to your objects are. That is usually a sign of a broken design Commented Nov 28, 2021 at 2:47

1 Answer 1

1

Inspired by OP's comment, maybe you could do something like

class Parent:
    def __init__(self, *args):
        self.child_varnames = type(self).__init__.__code__.co_varnames[1:]

class Child(Parent):
    def __init__(self, foo, bar):
        super().__init__(foo, bar)

In my tests, I get

>>> c = Child(1, 2)
>>> c.child_varnames
('foo', 'bar')
Sign up to request clarification or add additional context in comments.

1 Comment

Yep - this did the trick. Looking to build an API wrapper where a user may pass a kwarg as an arg. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.