Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Scripts directory an anti-pattern in Python? If so, what's the right way to import?

I've always created scripts directories in every project I've built because they're useful for putting infrequently used executable scripts. In Python, I'll always put an __init__.py in my scripts directory so I can run scripts as packages (i.e. python -m scripts.some_scripts) and load modules from sister directories. Based off this as well as googling, I'm starting to get the feeling that this is an anti-pattern.

That said, given a structure like:

project_dir/
    some_modules_dir/
        foo.py
        bar.py
        ...
    scripts/
        some_script.py
        other_script.py
        ...

What's the right way to run scripts and what's the right way to have them import from their sister directory some_modules_dir? Which dirs should contain __init__.py and which shouldn't? I want to follow PEP8 as much as possible, and want to simplify running scripts as much as possible. If having a scripts directory at all is inherently inadvisable, what do you guys do instead?

like image 718
Eli Avatar asked Nov 03 '14 22:11

Eli


People also ask

What is __ import __ in Python?

__import__() Parameters name - the name of the module you want to import. globals and locals - determines how to interpret name. fromlist - objects or submodules that should be imported by name. level - specifies whether to use absolute or relative imports.

What are the three types of import statement in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)

How do I run a Python script from a different directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.


1 Answers

The link in the question only says about running scripts that reside in a package directory which is a potential problem because... well... packages are not scripts and scripts are not packages. They serve different purposes and are invoked in different ways, so if you mix them together, there'll be a mess at some point.

Since Python itself has had a Scripts directory for ages and no one complains, it's in no way an anti-pattern.

See How do I separate my executable files from my library files? on how we dealt with executable scripts at my last occupation. It never caused any problems that I'm aware of.

like image 102
ivan_pozdeev Avatar answered Sep 28 '22 06:09

ivan_pozdeev