简体   繁体   中英

Error when importing python module from folders

I have a following directory structure:

source
       source_1.py
       __init__.py

source1.py has class Source defined

source1.py

class Source(object):
    pass

I am able to import using this

>>> from source.source1 import Source
>>> Source
<class 'source.source1.Source'>

However when trying to import using the below method it fails.

>>> from source import *
>>> source1.Source
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'source1' is not defined

Please let me know how can we use the 2nd import ?

For importing from a package (unlike importing from a module) you need to specify what * means. To do that, in __init__.py add a line like this:

__all__ = ["source1"]

See the Python documentation for Importing * From a Package .

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