Reputation: 1888
This is my first time making a python package, and I am thoroughly confused about __init__.py
, __main__.py
, and their relation to making a package.
Here is my project structure:
package_name/
setup.py
README.md
LICENSE
package_name/
__init__.py
__main__.py
A.py
B.py
Class A in A.py
depends on a class B in B.py
.
Should I have both __init__.py
and __main__.py
?
What should be in the files?
What I have tried:
in A.py
:
from B import B
and from .B import B
The first allows me to run normally locally, but when I try to upload it to pypi and install it, I get ModuleNotFoundError: No module named 'B'
The second allows me to import it after installing it from pypi, but I can't run it normal locally.
My goal is to import Class A from the package with the following
from package_name import A
and be able to run my package locally.
Edit: I am using Python 3.
Upvotes: 0
Views: 468
Reputation: 36
Files named init.py are used to mark directories on disk as a Python package directories, you can let this empty most of the time.
But let's say you have for example this file structure with the following code inside them:
Structure
package_name/ ├── setup.py ├── package_name │ ├── __init__.py │ └── main.py └── package_name.py
setup.py
#!/usr/bin/env python3
import sys
from setuptools import setup
setup(
name = "package_name",
version = "0.1",
packages=["package_name"],
package_data = {},
author="xxx",
author_email = "[email protected]",
description = "The familiar example program in Python",
license = "BSD",
keywords= "example documentation tutorial",
)
package_name.py
#!/usr/bin/env python
import sys
import package_name.main
if __name__ == '__main__':
sys.exit(package_name.main.main())
main.py
#!/usr/bin/env python3
import sys
def main(argv=None):
if argv is None:
argv = sys.argv
print("Hello, world")
return 0
Go in the terminal to the package_name folder and type: "python3 package_name.py" to execute the code.
Output
Hello, world
The package.py goes to the main.py and execute the code that is in the main.py. If you want to import in your example try using for example "from package_name.A.py import [function name]
" in the the python files you wish to access the functions. It should work.
Upvotes: 1