zhong
zhong

Reputation: 185

Dynamically call all class methods as variables

Lets say I have the following files:

main.py

from foo import SomeClass

foo.py

class SomeClass:
   a = a_object
   b = b_object

I want to unpack all SomeClass class variables as variables outside the class (in main.py), So I could call them,

Its possible to do like this:

from foo import SomeClass

a = SomeClass.a
b = SomeClass.b

But I want to do this dynamically without the need of knowing each class method.

I couldn't think of a neat way to achieve this except dir() n exec() which is bad, How can I do this?

Upvotes: 0

Views: 35

Answers (1)

M Z
M Z

Reputation: 4799

You can use dir() to get the names, getattr() to get the values of those variables, then setattr() to set them globally in your own system:

import sys
from foo import SomeClass

curr_mod = sys.modules[__name__]

for var in dir(SomeClass):
    try:
        setattr(curr_mod, var, getattr(SomeClass, var))
    except:
        # some variables can only be assigned to classes
        pass

Upvotes: 2

Related Questions