Python module hierarchy naming convention

I would like to have a module / package structure as shown below:

/__init__.py
/mymodule.py
/mymodule/
/mymodule/__init__.py
/mymodule/submodule.py

And then use modules like:

import mymodule
import mymodule.submodule

But it looks like the file " mymodule.py " is conflicting with the mymodule directory .

What is the correct naming convention here?

Thank.

+5
source share
2 answers

If you want to create a package, you need to understand how Python translates file names into module names.

mymodule.py mymodule, , Python. , ( ).

- __init__.py. - , , . Python, __init__.py. , mypackage/__init__.py mypackage.

__init__.py Python (, , __init__, , , ).

, , :

toplevel/
    mymodule/
        __init__.py     # put code here for mymodule
        submodule.py    # put code here for mymodule.submodule

Python toplevel.

+11

package. , :

/some-parent-directory # This needs to be on sys.path
    /mymodule  # This is not really a module - it a package
        __init__.py  # import mymodule
        # init is loaded when you `import mymodule` or anything below it
        some.py  # import mymodule.some
        implementation.py  # import mymodule.implementation
        files.py  # import mymodule.files
        /submodule
            __init__.py  # import mymodule.submodule
            # init is loaded when you `import mymodule.submodule` or anything below it
            submodule_impl.py  # import mymodule.submodule.submodule_impl
            goes.py  # import mymodule.submodule.goes
            here.py  # import mymodule.submodule.here

sys.path, import mymodule from mymodule.submodule import something.

, - (, from mymodule import SomeItem from mymodule.submodule import AnotherItem), __init__.py .

, , , CustomClass, submodule_impl.py, submodule. submodule/__init__.py :

from .submodule_impl import CustomClass

CustomClass submodule (i. e. from mymodule.submodule import CustomClass)

+4

All Articles