I'd like to have modules/packages structure like following:
/__init__.py
/mymodule.py
/mymodule/
/mymodule/__init__.py
/mymodule/submodule.py
And then use modules like:
import mymodule
import mymodule.submodule
But it seems like file "mymodule.py" conflicts with "mymodule" directory.
What's the correct naming convention here?
Package and Module Names Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
Organize your modules into packages. Each package must contain a special __init__.py file. Your project should generally consist of one top-level package, usually containing sub-packages. That top-level package usually shares the name of your project, and exists as a directory in the root of your project's repository.
In Python, Modules are simply files with the “. py” extension containing Python code that can be imported inside another Python Program. In simple terms, we can consider a module to be the same as a code library or a file that contains a set of functions that you want to include in your application.
If you want to make a package, you have to understand how Python translates filenames to module names.
The file mymodule.py
will be available as the mymodule
, assuming the interpreter finds it in a directory in the Python search path. If you're on a case-insensitive filesystem, it might also be importable with different capitalization (but you should avoid using such system-dependent behavior).
A package is a directory with an __init__.py
file in it. There's been some movement recently to allow packages without those files, but I'm going to ignore that less-common case for this answer. A package becomes a module inside Python, with its code coming from the __init__.py
file. So the file mypackage/__init__.py
can be imported as mypackage
.
There's no meaning to an __init__.py
file directly in the Python search path (well, I suppose you could import it an an __init__
module, but this is probably a bad idea).
So, for your situation, here's the appropriate filesystem layout:
toplevel/
mymodule/
__init__.py # put code here for mymodule
submodule.py # put code here for mymodule.submodule
Only the toplevel
folder should be in the Python search path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With