I have some like this:
/package
__init__.py
file1.py
file2.py
and inside __init__.py I define some_variable=True
When I try to import some_variable inside my files
from . import some_variable
I get ImportError: cannot import name some_variable.
I get the same error if I do
from folder.package import some_variable
Why am I not able to import this variable?
The really confusing/frustrating part is that PyCharm's autocomplete recognises that the variable exists.
Related
I have the following project structure:
- workflow/
file1.ipynb
file2.ipynb
...
- utils/
__init__.py
function_one.py
function_two.py
...
I am working on file1.ipynb, so far I have found a way to import the variables defined in init.py through the following code:
utils = importlib.machinery.SourceFileLoader('utils', '/home/utils/__init__.py').load_module()
Let's assume my __init__.py contains the following:
from .function_one import *
I can then use the variables defined inside the __init__.py file.
However, every time I want to call any of these variables I need to use the following syntax:
utils.function_one ...
I want to be able to write function_one without the utils at the beginning.
How can I import directly the variables defined inside the __init__.py ?
I don't know why you don't import your module with the normal import mechanism: from ..utils import * or depending on where your python interpreter was started just from utils import * but if you insist on using utils = importlib.machinery.SourceFileLoader('utils', '/home/utils/__init__.py').load_module() you can hack all values into your globals like this:
tmp = globals()
for attr_name in dir(utils):
if not attr_name.startswith("_"): # don't import private and dunder attributes
tmp[attr_name] = getattr(utils, attr_name)
del tmp
function_one(...) # should work now
Try this:
from ..utils import *
I have the following project structure:
unit_tests/
__init__.py # 1
bar/
__init__.py # 2
test.py
foo/
__init__.py # 3
module2.py
module1.py
__init__.py 1 and 2 are empty while 3 contains the following:
from .module1 import print1
from .module2 import print2
The reason I defined them is that this will allow bar/test.py to import print1 or print2 by just calling
from unit_tests.foo import print1
instead of
from unit_tests.foo.module1 import print1
So far so good. However, when I try to import print2 within module1:
from . import print2
I get the error: ImportError: cannot import name print2
Only from .module2 import print2 works.
My question: Since I am in module1.py, which is in folder foo, why can't I use from . import print2 to import print2? I find it strange because I am able to import print1 and print2 in bar/test.py without referencing module1 or module2.
You have to see that imports are executed just like any other statements. For example, python will not try to import packages in a specific order.
So when importing foo, you first execute:
from .module1 import print1 which import module1.py.
Then doing from . import print2 in module1.py is incorrect since from .module2 import print2 has not been executed yet in foo/__init__.py. This is why exchanging the two lines of foo/__init__.py fixes the problem.
So either either you have to switch the two lines foo/__init__.py either you have to import print2 as you did: from .module2 import print2 to fix your problem.
I have the following Python package with 2 moludes:
-pack1
|-__init__
|-mod1.py
|-mod2.py
-import_test.py
with the code:
# in mod1.py
a = 1
and
# in mod2.py
from mod1 import a
b = 2
and the __init__ code:
# in __init__.py
__all__ = ['mod1', 'mod2']
Next, I am trying to import the package:
# in import_test.py
from pack1 import *
But I get an error:
ModuleNotFoundError: No module named 'mod1'
If I remove the dependency "from mod1 import a" in mod2.py, the import goes correctly. But that dependency makes the import incorrect with that exception "ModuleNotFoundError".
???
The issue here is that from mod2 perspective the first level in which it will search for a module is in the path from which you are importing it (here I am assuming that pack1 is not in your PYTHONPATH and that you are importing it from the same directory where pack1 is contained).
This means that if pack1 is in the directory /dir/to/pack1 and you do:
from mod1 import a
Python will look for mod1 in the same directory as pack1, i.e., /dir/to/pack1.
To solve your issue it is enough to do either:
from pack1.mod1 import a
or in Python 3.5+
from .mod1 import a
As a side note, unless this is a must for you, I do not recommend designing your package to be used as from pack import *, even if __all__ exists to give you better control of your public API.
I am making a bot in python 3 and wish it to be easily expanded so I have a central file and then one for each command. I wish to know if there is a way to import a sub-directory full of modules without importing each separately. For example:
example
├── commands
│ ├── bar.py
│ └── foo.py
└── main.py
And the code in main.pywould be something like:
import /commands/*
Thanks :D
Solution:
Import each separately with:
from commands import foo, bar
from commands import * Does not work.
If you're using python3, the importlib module can be used to dynamically import modules. On python2.x, there is the __import__ function but I'm not very familiar with the semantics. As a quick example,
I have 2 files in the current directory
# a.py
name = "a"
and
# b.py
name = "b"
In the same directory, I have this
import glob
import importlib
for f in glob.iglob("*.py"):
if f.endswith("load.py"):
continue
mod_name = f.split(".")[0]
print ("importing {}".format(mod_name))
mod = importlib.import_module(mod_name, "")
print ("Imported {}. Name is {}".format(mod, mod.name))
This will print
importing b Imported <module 'b' from '/tmp/x/b.py'>.
Name is b
importing a Imported <module 'a' from '/tmp/x/a.py'>.
Name is a
Import each separately with:
from commands import bar and
from commands import foo
from commands import * Does not work.
I have created my own module with filename mymodule.py. The file contains:
def testmod():
print "test module success"
I have placed this file within /Library/Python/2.7/site-packages/mymodule/mymodule.py
I have also added a __init__.py file, these have compiled to generate
__init__.pyc and mymodule.pyc
Then in the python console I import it
import mymodule
which works fine
when I try to use mymodule.testmod() I get the following error:
AttributeError: 'module' object has no attribute 'testmod'
So yeah it seems like it has no functions?
You have a package mymodule, containing a module mymodule. The function is part of the module, not the package.
Import the module:
import mymodule.mymodule
and reference the function on that:
mymodule.mymodule.testmod()
You can use from ... import and import ... as to influence what gets imported exactly:
from mymodule import mymodule
mymodule.testmod()
or
from mymodule import mymodule as nestedmodule
nestedmodule.testmod
or
from mymodule.mymodule import testmod
testmod()
etc.