简体   繁体   中英

python importing from subfolders

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?

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...

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.

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
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM