Reputation: 43
When I import a subdirectory and assign it a variable name, why am I then unable to import modules from this subdirectory via the variable name?
Eg my directory structure is:
root\
f1\
f2\
m1.py
when I do the following, everything is fine:
from f1.f2 import m1
But when I do the following, python interprets the from selection as a module and throws an error:
import f1.f2 as f
from f import m1
Error msg: ModuleNotFoundError: No module named 'f'
Why is f interpreted as a module and not the subdirectory f2 contained in f1?
Upvotes: 0
Views: 660
Reputation: 27311
The python grammar doesn't allow expressions after from
:
import f1.f2 as f
from f import m1
f
in the second line is a variable expression, and the Python grammar (https://docs.python.org/3/reference/grammar.html) thinks it has found a NAME
, which is then fed to the import machinery to find a module named f
:
Error msg: ModuleNotFoundError: No module named 'f'
You could do
import f1.f2 as f
m1 = f.m1
instead...
Upvotes: 1
Reputation: 257
Whenever you use from
or import
, Python is looking for a module with the name that you are passing. You have to first import from the actual module name and then use your variables.
Example:
>>> import random as ran
>>> from ran import * ## we cannot import from the variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'ran'
>>> ran.randint(1, 10) ## but we now can use our variable
8
>>>
Upvotes: 0
Reputation:
You need to create a init.py module in your package. Python recognizes such folders as packages.
Create an init.py file in the root folder, the f1 folder, and the f2 folder.
Upvotes: 0