I'm Python newbie, and I have a problem with an error message
'ImportError: cannot import name callfunc'
I made two python files, '~/a.py' and '~/pkg/b.py'. (Additionally my IDE automatically created '~/__init__.py' and '~/pkg/__init__.py')
in a.py, a function
def callfunc():
print "Called"
is defined, and there are two statements in pkg/b.py:
from a import callfunc
callfunc()
However when executing python pkg/b.py, an error raises :
ImportError: cannot import name callfunc
I tried export PYTHONPATH=... , but it isn't effective also
How can I solve this problem?
write this in b.py before any of the imports from your own modules:-
import sys
sys.path.append(<the directory where a.py is defined>)
what the value of PYTHONPATH?
The parameter can be $HOME in your example.
Related
I am trying to import a function from another python file in a different directory but only have the function name in string form. I have tried using import lib as follows:
sys.path.insert(1, file_path) # Works fine
import file # Works fine
run_function = importlib.import_module("file.function"+str(loop)) # Error occurs here
But when I try this I get the error message: ModuleNotFoundError: No module named 'file.function1'; 'file' is not a package
I have also tried doing:
from file import *
eval("function{loop}()")
But with this method I recieve the error message: SyntaxError: import * only allowed at module level
I am not sure exactly how to fix the issue or whether there would be a better way of doing this. I am open to suggestions. Thanks!
You can import anywhere in the file (obviously importing within a function would limit the module scope to the function itself).
def func(x):
for i in range(x):
eval(f"from lib import function{i}")
# All functions available in this scope
For extra safety, I recommend this be put into a try/catch.
You don't import functions. You have successfully imported the module, which includes the function, so all you have to do is get it
sys.path.insert(1, file_path) # Works fine
import file # Works fine
result = getattr(file, "function1")(loop)
In python 2 I can create a module like this:
parent
->module
->__init__.py (init calls 'from file import ClassName')
file.py
->class ClassName(obj)
And this works. In python 3 I can do the same thing from the command interpreter and it works (edit: This worked because I was in the same directory running the interpreter). However if I create __ init __.py and do the same thing like this:
"""__init__.py"""
from file import ClassName
"""file.py"""
class ClassName(object): ...etc etc
I get ImportError: cannot import name 'ClassName', it doesn't see 'file' at all. It will do this as soon as I import the module even though I can import everything by referencing it directly (which I don't want to do as it's completely inconsistent with the rest of our codebase). What gives?
In python 3 all imports are absolute unless a relative path is given to perform the import from. You will either need to use an absolute or relative import.
Absolute import:
from parent.file import ClassName
Relative import:
from . file import ClassName
# look for the module file in same directory as the current module
Try import it this way:
from .file import ClassName
See here more info on "Guido's decision" on imports in python 3 and complete example on how to import in python 3.
I got an error,ModuleNotFoundError: No module named 'test2'.I made test1.py and test2.py.I wanna call test2.py's module in test1.py.So I wrote codes import test2 as test in test1.py but the error happens.I rewrote from test2 import test but same error happens.What is wrong in my code?How should I fix this?I am using IDE so I think I can install module automatically, but in this time it cannot be done.
Your syntax is wrong....
from test2 import test
means from the test2 module import a function or variable named test...
The actual syntax is import test2...In that case make sure that the two python files are in the same directory.....
I am newbie to Python 3 and currently learning how to create Python modules. I have created below package structure.
maindir
test.py
package
__init__.py
subpackage
__init__.py
module.py
This is my module.py file
name="John"
age=21
and this is my test.py file
import package.subpackage.module
print(module.name)
When I run test.py I am getting this error NameError: name 'module' is not defined
However, when I change the import statement to import package.subpackage.module as mymod and print the name with print(mymod.name) then its working as expected. Its printing name John.
I didn't understand why its working with second case and not with first.
Perhaps what you were attempting was this:
from package.subpackage import module
Then you can reference module as a name afterwards.
If you do:
import package.subpackage.module
Then your module will be called exactly package.subpackage.module.
With little bit of reading I understood this behaviour now. Please correct me If I am wrong.
With this import package.subpackage.module style of import statement you have to access the objects with their fully qualified names. For example, in this case
print(package.subpackage.module.name)
With aliasing I can shorten the long name with import package.subpackage.module as mymod and print directly with print(mymod.name)
In short print(package.subpackage.module.name) == print(mymod.name)
I am trying out the answer in this.
The __init__.py file in a folder named MyLibs contains:
LogFile = r'D:\temp'
In utils.py in the same folder MyLibs, I tried various ways to access the LogFile variable:
from __init__ import *
print LogFile #Gives: NameError: name 'LogFile' is not defined`:
and:
import __init__
print MyLibs.LogFile #Gives: NameError: name 'MyLibs' is not defined
I got the errors while executing from MyLibs.utils import *
What is the fix I must do? I prefer a method where I can reference LogFile directly without having to add namespace prefixes.
My mistake.
The updated __init__.py was somehow not executed. I started a new Python session and it worked.
Sorry for the false alarm.
Not sure how to do this with 2.7's implicit relative imports, but you could try this:
from __future__ import absolute_import
from . import LogFile
If you're running the Python module directly, you need to run it with python -m MyLibs.utils rather than python MyLibs/utils.py.