sss
sss

Reputation: 3

Iterating through different classes of another script in Python

I have a script with different classes. Now I need to import that script and iterate through all the classes in Python. I don't know with what library that could be possible?

For exaple there is foo.py with different classes:

#foo.py
class a():
   print("a")

class b():
   print("b")

class c():
   print("c")

Also there is another script myscript.py that I want to import foo.py and loop over all the classes (Pseudocode) :

#myscript.py
import foo
for c in foo.classes:
    #do something...

I'm wondering if there is a library that I can do that.

Upvotes: 0

Views: 127

Answers (1)

rdas
rdas

Reputation: 21285

You could use dir() & getattr() to get what you want:

import foo

for symbol in dir(foo):
    # ignore dunder-members
    if symbol.startswith('_'):
        continue
    print(symbol)
    # here's your class 
    cl = getattr(foo, symbol)
    # here's how you can make an object
    obj = cl()
    print(obj)

Output:

a
<foo.a object at 0x10e1339a0>
b
<foo.b object at 0x10e133c70>
c
<foo.c object at 0x10e1339a0>

However, this is not really maintainable code - I'd suggest refactoring to ensure this is not required.

Upvotes: 1

Related Questions