You want the built in __import__ function

new_module = __import__(modulename)
Answer from mgilson on Stack Overflow
🌐
Medium
medium.com › @gl7526 › importing-variables-from-another-file-5afcdaa6c8df
Importing Variables From Another File | by George | Medium
November 17, 2020 - The simplest way to do so is to have a regular Python file that you want to import variables from, and the file you want to import the variable to, in the same directory.
🌐
O'Reilly
oreilly.com › library › view › python-cookbook › 0596001673 › ch15s04.html
Importing from a Module Whose Name Is Determined at Runtime - Python Cookbook [Book]
July 19, 2002 - def importName(modulename, name): """ Import a named object from a module in the context of this function.
Authors: Alex MartelliDavid Ascher
Published: 2002
Pages: 608
Top answer
1 of 2
8

Here's how to use importlib (there is no need for the second parameter):

var = importlib.import_module("var")

# Now, you can use the content of the module:
var.my_class()

There is no direct programmable equivalent for from var import my_class.

2 of 2
-2

Note: As @DYZ points out in the comments, this way of solving this is not recommended in favor of importlib. Leaving it here for the sake of another working solution, but the Python docs advise "Direct use of import() is also discouraged in favor of importlib.import_module()."

Do you mean that you want to import a module whose name is defined by a variable? If so, you can use the __import__ method. For example:

>>> import os
>>> os.getcwd()
'/Users/christophershroba'
>>>
>>> name_to_import = "os"
>>> variable_module = __import__(name_to_import)
>>> variable_module.getcwd()
'/Users/christophershroba'

If you also want to call a variable method of that variable module you could use the __getattribute__ method on the module to get the function, and then call it with () as normal. The line below marked "See note" is not necessary, I just include it to show that the __getattribute__ method is returning a function.

>>> name_to_import = "os"
>>> method_to_call = "getcwd"
>>> variable_module = __import__(name_to_import)
>>> variable_module.__getattribute__(method_to_call) # See note
<built-in function getcwd>
>>> variable_module.__getattribute__(method_to_call)()
'/Users/christophershroba'

More documentation available for Python 3 here or Python2 here.

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-import-variables-from-another-file-in-python
How to import variables from another file in Python? - GeeksforGeeks
April 3, 2025 - By importing a file, you gain access to its variables and functions. This can be done by simply using import filename or from filename import variable_name to access the required variables or functions in your current program.
🌐
Sololearn
sololearn.com › en › Discuss › 2044263 › how-to-import-module-if-the-modulename-is-stored-in-a-variable
How to import module if the module-name is stored in a variable? | Sololearn: Learn to code for FREE!
In python 3, you can simply import module with exec: exec('import module_name') But for some reason that I still don't know (I know now), import doesn't work inside functions, but you can make it work with this: exec('import module_name', globals()) ...
🌐
CodeBurst
codeburst.io › importing-variables-from-other-files-in-python-96a200f410da
Importing variables from other files in Python | by aneesh joshi | codeburst
June 30, 2017 - from A import aprint('Imported value of a is %s' % str(a))print('value of __name__ in B is %s' % __name__) ... └> python B.py the value of __name__ in A is A Imported value of a is 0 value of __name__ in B is __main__
Find elsewhere
🌐
Openastronomy
openastronomy.org › rcsc18 › chapters › 04-further-python › 03-imports-and-namespaces
Imports and namespaces - Research Computing Summer School
Really what we should do in the example above is use more descriptive variable names, but even then it would still be possible for a large code base to use a variable name more than once in different places, so namespaces help reduce the chance of name conflicts. One of the most common uses of namespaces is in the context of module imports.
🌐
Python Morsels
pythonmorsels.com › 4-ways-import-module-python
4 ways to import a module in Python - Python Morsels
August 3, 2026 - In Python you can import specific variables from a module, you can import the whole module, and you can also rename variables while importing. When should you use each of these import styles?
🌐
Dive into Python
diveintopython.org › home › learn python programming › variables in python › how to import variables from files
Examples of Import Variables and Exporting Strings to Files in Python
May 3, 2024 - To import a variable in Python, you need to use the import statement. Suppose you have a Python file named file1.py which contains a variable named my_variable.
🌐
Fabienmaussion
fabienmaussion.info › scientific_programming › week_03 › 01-Import-Scopes.html
Modules, import mechanism, namespaces, scope(s) — Scientific Programming
By importing the math module (available in python’s standard library), we have access to a new variable called math. The variable math has the type module, and provides new functions and variables (such as math.pi). What are all these functions and variables? Let’s use the built-in dir() function to find out: ... ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor',
Top answer
1 of 2
34

It is set to the absolute name of the module as imported. If you imported it as foo.bar, then __name__ is set to 'foo.bar'.

The name is determined in the import.c module, but because that module handles various different types of imports (including zip imports, bytecode-only imports and extension modules) there are several code paths to trace through.

Normally, import statements are translated to a call to __import__, which is by default implemented as a call to PyImport_ImportModuleLevelObject. See the __import__() documentation to get a feel for what the arguments mean. Within PyImport_ImportModuleLevelObject relative names are resolved, so you can chase down the name variables there if you want to.

The rest of the module handles the actual imports, with PyImport_AddModuleObject creating the actual namespace object and setting the name key, but you can trace that name value back to PyImport_ImportModuleLevelObject. By creating a module object, it's __name__ value is set in the moduleobject.c object constructor.

2 of 2
3

The __name__ variable is an attribute of the module that would be accessible by the name.

import os
assert os.__name__ == 'os'

Example self created module that scetches the import mechanism:

>>> import types
>>> m = types.ModuleType("name of module") # create new module with name
>>> exec "source_of_module = __name__" in m.__dict__ # execute source in module
>>> m.source_of_module
'name of module'

Lines from types module:

import sys
ModuleType = type(sys)
🌐
PyPI
pypi.org › project › varname
varname · PyPI
from varname import argname def func(a, b=1): print(argname('a')) x = y = z = 2 func(x) # prints: x def func2(a, b=1): print(argname('a', 'b')) func2(y, b=x) # prints: ('y', 'x') # allow expressions def func3(a, b=1): print(argname('a', 'b', vars_only=False)) func3(x+y, y+x) # prints: ('x+y', 'y+x') # positional and keyword arguments def func4(*args, **kwargs): print(argname('args[1]', 'kwargs[c]')) func4(y, x, c=z) # prints: ('x', 'z') # As of 0.9.0 (see: https://pwwang.github.io/python-varname/CHANGELOG/#v090) # Can also fetch the source of the argument for # __getattr__/__getitem__/__setatt
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › __import__.html
__import__ — Python Reference (The Right Way) 0.1 documentation
Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime. When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name.