简体   繁体   中英

python relative import from same directory doesn't work as expected

I have the following directory structure:

pkg/
    sub1.py
    sub2.py

from withing sub1.py I can successfully import sub2 with: import pkg.sub2 or with a relative import as from. import sub2 from. import sub2 but I thought the following relative import: import.sub2 should work as well but it does not. I get a SyntaxError: invalid syntax Why doesn't this work?

import doesnot take the . this is invalid syntax.

in relative imports always use the from keyword! Always! if you want to use the import by its own then this will be an abs import . just use:

import sub2

generaly speaking, relative imports are risky and try to minimise the usage of this kind of imports.

in your case if you want to import the sub2.py module in relative way: the correct way in python is:

from. import sub2 from. import sub2 as you first typed.

giving one more example for the usage of relative imports. you didnt ask but i found it right to attach this example:

pkg/
    sub1.py
    sub2.py
    pkg2/
         foo.py

supose i am in foo.py and i want to import from sub1.py the class clsTemp then the right way to import this class in relative manner:

from ..sub1 import clsTemp

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