Python – Should Scripts Be Included Inside a Python Package?

packagespython

In my Python application, I can distinguish between entry points (scripts) and what I think of as library code.

My instinct is to put the library code inside a package, and the scripts elsewhere importing from the package.

It is possible using setup.py to reference methods inside a package to use as entry-points, thereby having all Python code inside packages.

Which is preferable?

Note: this link discusses both options but doesn't really offer an opinion.

Edit: to give a more concrete example, I am reviewing some code which contains one package. There are forty modules inside it:

  • __init__.py
  • 11 'scripts'
  • 10 'library modules' used by those scripts
  • 18 test modules

This doesn't feel like it is using the capability of packages very well, but I can't put my finger on what exactly is wrong.

I appreciate that having tests in the same package was not in my original question.

Best Answer

Yes, this is possible and quite common for packages that serve as both command-line tools and imported libraries.

In setup.py, add a module's function as an entry point:

setuptools.setup(
    ...
    entry_points={'console_scripts': [
        'foo = my_package.some_module:main_func',
    ]},
    ...
)

To create a script named foo that calls the my_func function inside of my_package.some_module. Read more at https://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation.

It is also a convention it to add:

#!/usr/bin/env python

...

if __name__ == '__main__':
    my_func()

to the modules that can be called as "scripts" where my_func is the function you'd like to call externally.


Here is an example of setup.py:

https://github.com/jacebrowning/gdm/blob/fa998167f5f6de64bc8bdfd8b9433870d79ef814/setup.py#L28-L31

and a callable module:

https://github.com/jacebrowning/gdm/blob/fa998167f5f6de64bc8bdfd8b9433870d79ef814/gdm/cli.py#L161-L162

Related Topic