Home > Blockchain >  How to dynamically reference imported file names in Python?
How to dynamically reference imported file names in Python?

Time:10-12

Say I have:

file1 
file2
file3

Each of file1, file2, file3 have a dictionary called foo.

I have a different file named example_file that wants to read from file1, file2, file3.

from file1 import foo
from file2 import foo
from file3 import foo

# do something with file1.foo
# do something with file2.foo
# do something with file3.foo

Is there a way to do this through a loop?

for dynamic_name in something: 
   dynamic_name.foo # do something with foo
   # dynamic_name resolves to file1, file2, file3 through the loop

Essentially, I want to use the file names from the imports to reference items in the files themselves.

Is this possible?

CodePudding user response:

The built-in __import__ function will allow you to import a module who's name is in a variable.

To see how this works, consider this example.

# This...
import file1

# ...is the same as this...
file1 = __import__('file1')

# ...and this
name = 'file1'
file1 = __import__(name)

What if you want to import a name from the module (from ... import ...)? Pass the names you want to import to the fromlist argument.

# This ...
from file1 import foo

# ... is the same as
file1 = __import__('file1', fromlist=['foo'])
foo = file1.foo

CodePudding user response:

Be careful with

from file1 import foo
from file2 import foo
from file3 import foo

because the name foo will be reassigned every time and by the end it will only point to whatever file3.foo is.

Anything of the syntax something.ofthis is the object something with the attribute ofthis. Regardless of whether something is some class or a module. You can achieve the same by doing getattr(something, 'ofthis'). You can also use dir(something) to see what available attributes your object has.

import file1, file2, file3

for f in (file1, file2, file3):
   foo = getattr(f, 'foo')
  • Related