pypa / packaging-problems

An issue tracker for the problems in packaging
151 stars 35 forks source link

Trouble with a packaging tutorial -- Package Exports Are Weird #598

Closed AlanLivingston closed 2 years ago

AlanLivingston commented 2 years ago

OS version

Windows 10

Python version

Python 3.10.2

Pip version

pip 22.1.2

Guide link

https://packaging.python.org/en/latest/tutorials/packaging-projects/

Problem description

At the end of the tutorial, it imports the package, and runs the exported function:

>>> from example_package import example
>>> example.add_one(2)
3

But if I just enter:

>>> import example_package
>>> example_package
<module 'example_package' from 'C:\\SrcRoot\\Source\\packaging_tutorial_root\\env\\lib\\site-
packages\\example_package\\__init__.py'>
>>> example_package.example
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'example_package' has no attribute 'example'
>>> example_package.add_one
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'example_package' has no attribute 'add_one'

What I expected was to do _import example_package_, and then invoke addone with example_package.example.add_one(2)_

Why doesn't this work?

Error message

No response

henryiii commented 2 years ago

example is not imported by __init__.py. So import example_package only imports example_package/__init__.py, and not example_package/example.py. So it's not available. You can do:

import example_package.example
example_package.example.add_one(2)

If you want. You can also import example_package.example inside example_package/__init__.py, but be warned that means anyone using the package will always import example.py (if it's optional and there are any expensive setup code, special imports, etc. you might not always want that).

AlanLivingston commented 2 years ago

Ok, thanks! That was a concept I was missing.