简体   繁体   中英

How to properly build package to use a function without module name when importing the module?

I have been experimenting with packaging, testing it on test.pypi.

My structure is as follows:

package_name/
|--- LICENSE
|--- pyproject.toml
|--- README.md
|--- tests/
|--- dist/
|--- src/
     |--- package_name.egg-info/
     |--- package_name/ #this package is the same name as the whole package     
          |--- __init__.py   #from .my_module import my_function()
          |--- my_module.py  #containing my_function()

I successfully upload it to test.pypi. I successfully pip install it on another machine (using anaconda with python 3.9.12)

Then I face the following problem::

import package_name

print(my_module.my_function()) #works
from package_name import my_module

print(my_module.my_function()) #works
from package_name import my_module

print(my_function())
> "NameError: 'my_function' is not defined". 

I suspect it has something to do with the init file (?). I tried some different things but none seemed to work so far.

When using "from package_name import my_module" I expected "my_function()" to be callable without the module's name.

I did try different methods, but none worked so far. Also found a lot of topics here on stackoverflow, but none seemed to work so far. I just want to understand why I can't call a sole function from a sole module without also using the module's name.

I prefer absolute imports: from src.package_name.my_module import my_function

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