Senior Pomidor
Senior Pomidor

Reputation: 318

Dynamically import classes

Now i have script like this:

class threadEnum():
    pass

class first(threadEnum):
    pass

class second(threadEnum):
    pass

class third(threadEnum):
    pass

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

which classes is very long and takes a lot of lines. I need to move each class to separate file and then import all classes into main script. So i create folder engines and put inside three files with classes first.py, second.py and third.py also file __init__.py

I think must be something like that:

import importlib

class threadEnum():
    pass

chosenEnums = []
chosenEnums = ['first', 'second', 'third']

# Load classes from engines folder
for enumm in chosenEnums:
    module = 'engines'
    # create a global object containging our module
    mymethod = getattr(importlib.import_module('engines'), enumm)

enums = [enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose) for enum in chosenEnums]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

But i get error:

AttributeError: 'module' object has no attribute 'first'

What is wrong? Python 2.7.6

Upvotes: 0

Views: 264

Answers (2)

yinnonsanders
yinnonsanders

Reputation: 1871

When you import a folder as a module, the files within it are not immediately loaded as attributes.

>>> import importlib
>>> print(dir(importlib.import_module('engines'))

['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

To load them, you must use an import statement. In this case you could use __import__("{0}.{1}".format(module,enumm)).

Upvotes: 2

Matthew Proudman
Matthew Proudman

Reputation: 1

by using a simple if statement and haveing a set variable name to be the object and use the dir() to detect the objects within the named object (class).

Upvotes: -1

Related Questions