Sharing common code between multiple scripts?

Ben Finney ben+python at benfinney.id.au
Wed Oct 30 00:31:50 EDT 2013


Victor Hooi <victorhooi at gmail.com> writes:

> NB - I'm the original poster here - https://groups.google.com/d/topic/[…]

That is not the correct URL to a discussion on this forum. The official
archives are at <URL:https://mail.python.org/pipermail/python-list/>, so
that's the correct place to look for a canonical URL to your message.

> I'd like to pull them out, and move them to a common module for all
> the scripts to import.

Great! This is modular programming, and is good practice.

> Originally, I thought I'd create a package, and have it all work:
>
> my_package
>     __init__.py
>     common/
>         my_functions.py

You should make ‘common/’ a package directory, by creating
‘common/__init__.py’.

>     script1/
>         __init__.py
>         config.yaml
>         script1.py
>     script2/
>         __init__.py
>         config.yaml
>         script2.py
>
> However, there apparently isn't an easy way to have script1.py and
> script2.py import from common/my_functions.py.

Once ‘common/’ is a package directory, you can::

    from ..common import my_functions

> So my new question is - what is the idiomatic way to structure this in
> Python, and easily share common functions between the scripts?

Put your modules into one or more packages.

Make sure each subdirectory of modules is a package.

Use explicit relative imports within your application.

Use absolute imports for shared libraries (ones shared between different
applications).

-- 
 \          “Any sufficiently advanced bug is indistinguishable from a |
  `\                                          feature.” —Rich Kulawiec |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list