Post

Python Package


Python Package

1
2
3
4
5
main.py
mypackage/
    __init__.py
    mymodule.py
    myothermodule.py

…a mymodule.py like this…

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python3

# Exported function
def as_int(a):
    return int(a)

# Test function for module
def _test():
    assert as_int('1') == 1

if __name__ == '__main__':
    _test()

1 example

  • main.py: good
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3

from mypackage.myothermodule import add

def main():
    print(add('1', '1'))

if __name__ == '__main__':
    main()

  • myothermodule.py: fail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python3

from .mymodule import as_int

# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()
  • The way you’re supposed to run it is…
  • python3 -m mypackage.myothermodule

solution:

  • assuming the name mymodule is globally unique
    • would be to avoid using relative imports, and just use…
    • from mymodule import as_int
  • if it’s not unique, or your package structure is more complex,
    • include the directory containing your package directory in PYTHONPATH, and do it like this…
    • from mypackage.mymodule import as_int

.

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.