I have a project that tries to create a new module dynamically and then in a subsequent exec statement tries to import that module.
import imp
s="""
class MyClass(object):
def __init__(self):
pass
def foo(self):
pass
"""
mod = imp.new_module("testmodule.testA")
exec s in mod.__dict__
exec "import testmodule.testA"
But this throws this exception:
Traceback (most recent call last):
File "test.py", line 14, in <module>
exec "import testmodule.testA"
File "<string>", line 1, in <module>
ImportError: No module named testmodule.testA
I've tried several things: adding it to sys.modules, creating a scope dict containing the name and the module as well. But no dice. I can see testmodule.testA when I do a print locals() in my exec statement, but I can't import it. What am I missing here?
Thank you.
You'll need to add your module to the sys.modules structure for import to find it:
import sys
sys.modules['testmodule.testA'] = mod
You already have the module object however and there is not much point in importing it again. mod is a reference to what Python would otherwise 'import' already.
The following would work without an import call:
mod.MyClass
If you need the module in an exec call, add it to the namespace there:
exec 'instance = MyClass()' in {'MyClass': mod.MyClass}
Related
I have been learning working with classes in python after learning OOPs in c++.
I am working on a project, where I have a class defined in one file, and an important function to be used in the class in the seperate file.
I have to call the class in the first file, but I am getting the ImportError.
Great, if you could help.
try1.py
from try2 import prnt
class a:
def __init__(self):
print("started")
def func1(self):
print("func1")
prnt()
try2.py
from try1 import a
b = a()
b.func1()
def prnt():
b.func()
As for eg, in the above example, when I am running try1.py, I am getting an ImportError: cannot import name 'prnt'.
You absolutely need to redesign your project. Even if you did manage to get away with the cyclic imports (ie by moving the import to inside the function - but don't do it) you will still get a NameError: name 'b' is not defined since b is not define in prnt.
Unless prnt can't be defined in class a (why?), consider defining prnt in a third, "utils" file and import it in both try1.py and try2.py and pass an object to it so it can access all of its attributes.
Just run your code, read the error, and deduct something from it.
When you run it, here is the error message :
Traceback (most recent call last):
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
File "C:\Users\Kilian\Desktop\Code\Garbage\temp2.py", line 1, in <module>
from tmp import a
File "C:\Users\Kilian\Desktop\Code\Garbage\tmp.py", line 7, in <module>
from temp2 import prnt
ImportError: cannot import name prnt
Your script is trying to import something it already has tried to import earlier on. Python is probably deducing that it can't import it. :)
I failed to import a module from sub directory in python. Below is my project structure.
./main.py
./sub
./sub/__init__.py
./sub/aname.py
when I run python main.py, I got this error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
import sub.aname
File "/Users/dev/python/demo/sub/__init__.py", line 1, in <module>
from aname import print_func
ModuleNotFoundError: No module named 'aname'
I don't know it failed to load the module aname. Below is the source code:
main.py:
#!/usr/bin/python
import sub.aname
print_func('zz')
sub/__init__.py:
from aname import print_func
sub/aname.py:
def print_func( par ):
print ("Hello : ", par)
return
I am using python 3.6.0 on MacOS
There are several mistakes in your Python scripts.
Relative import
First, to do relative import, you must use a leading dots (see Guido's Decision about Relative Imports syntax).
In sub/__init__.py, replace:
from aname import print_func
with:
from .aname import print_func
Importing a function
To import a function from a given module you can use the from ... import ... statement.
In main.py, replace:
import sub.aname
with:
from sub import print_func
from sub import aname
aname.print_func('zz')
Probably the most elegant solution is to use relative imports in your submodule sub:
sub.__init__.py
from .aname import print_func
But you also need to import the print_func in main.py otherwise you'll get a NameError when you try to execute print_func:
main.py
from sub import print_func # or: from sub.aname import print_func
print_func('zz')
Today I wrote an "alias import function" for myself, because I need to write a script to do variable value checks for different python files.
# filename: zen_basic.py
import importlib
def from_module_import_alias(module_name, var_name, alias):
""" equal to from module import a as b """
agent = importlib.import_module(module_name)
globals()[alias] = vars(agent)[var_name]
The weird thing is, if I start a Python interactive shell, I can't import things by using this function. But by using its content outside of the function, it works.
>>> from zen_basic import *
>>> module_name = 'autor'
>>> var_name = 'food'
>>> alias = 'fd'
>>> from_module_import_alias(moduele_name, var_name, alias)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'moduele_name' is not defined
>>> from_module_import_alias(module_name, var_name, alias)
>>> fd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fd' is not defined
>>> agent = importlib.import_module(module_name)
>>> globals()[alias] = vars(agent)[var_name]
>>> fd
'cake'
>>>
I did 3 more experiments after:
Do python -i test.py
import zen_basic in interactive shell
call from_module_import_alias function, failed.
Do python -i zen_basic.py
call from_module_import_alias function, success.
add code which import zen_basic and call the from_module_import_alias function to test.py
Do python -i test.py, success
What's the reason that directly using from_module_import_alias function in a Python interactive shell failed?
You are updating the wrong globals. You are updating the globals of your zen_basic module, not the __main__ module (the namespace for your script or the interactive interpreter). The globals() function always returns the globals of the module in which the code was defined, not the module that called your function.
You'd have to retrieve the globals of the calling frame. Note that it rarely is advisable to modify the globals of the calling frame, but if you must then you can retrieve the calling frame by using the sys._getframe() function:
import sys
def from_module_import_alias(module_name, var_name, alias):
""" equal to from module import a as b """
agent = importlib.import_module(module_name)
calling_globals = sys._getframe(1).f_globals
calling_globals[alias] = vars(agent)[var_name]
In your experiments, python -i zen_basic.py runs zen_basic as the main script entry, and thus globals() references the __main__ module.
I have a script that does the following:
import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
Later on, I call a class of the this module with the same name:
config = storage_configuration_reader()
If I import it like the above I get the following NameError NameError: global name 'storage_configuration_reader' is not defined but if I use the following code:
import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
import storage_configuration_reader
config = storage_configuration_reader()
Then I get this error TypeError: 'module' object is not callable
Changing the name of the imp.load_source doesn't help to import the object:
import imp
imp.load_source("storage_configuration","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
<module 'storage_configuration' from '/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.pyc'>
import storage_configuration
config = storage_configuration_reader()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'storage_configuration_reader' is not defined
Which is the best way (AKA working way) to import an object like this?
Info: The storage_configuration_reader definition:
class storage_configuration_reader(object):
"""
Class configuration_reader: this object read the config file and return the
different configuration values
"""
...
imp.load_source loads the module using the given path and name it using the new name, it's not like from your_module_at_path import your_class_by_name, it's just like import your_module_at_path as new_name (not exactly the same).
Besides, you need to assign the name to a variable to use it:
wtf=imp.load_source("new_module_name", your_path)
#wtf is the name you could use directly:
config = wtf.storage_configuration_reader()
the name new_module_name is stored as a key in dictionary sys.modules, you can use it like this:
sys.modules['new_module_name'].storage_configuration_reader()
A simpler way to import a module from some other directory is adding the module's path to sys.path:
import sys
sys.path.append("/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao")
import storage_configuration_reader
config = storage_configuration_reader.storage_configuration_reader()
I'm new to python and now learning how to to import a module or a function, but I got these posted errors. The python code is saved under the name: hello_module.py
python code:
def hello_func():
print ("Hello, World!")
hello_func()
import hello_module
hello_module.hello_func()
error message:
Traceback (most recent call last):
File "C:/Python33/hello_module.py", line 9, in <module>
import hello_module
File "C:/Python33\hello_module.py", line 10, in <module>
hello_module.hello_func()
AttributeError: 'module' object has no attribute 'hello_func'
You cannot and should not import your own module. You defined hello_func in the current namespace, just use that directly.
You can put the function in a separate file, then import that:
File foo.py:
def def hello_func():
print ("Hello, World!")
File bar.py:
import foo
foo.hello_func()
and run bar.py as a script.
If you try to import your own module, it'll import itself again, and when you do that you import an incomplete module. It won't have it's attributes set yet, so hello_module.hello_func doesn't yet exist, and that breaks.