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

后端 未结 4 1049
醉酒成梦
醉酒成梦 2021-02-19 01:31

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

4条回答
  •  后悔当初
    2021-02-19 01:50

    Personally, having a __init__.py in one's scripts dir feels a bit off, but I can also see why it's useful here (and in IDEs).

    That said, if they're already being run as a Python module, then maybe they're not true scripts, whatever that even means (related: do you have a shebang on these files?). Hard to say without context, but perhaps they are closer to tools modules, forming part of your overall Python codebase.

    In which case, with the addition of an __init__.py at project level (project_dir in your example), you can then use normal importing in your would-be scripts:

    from some_modules_dir import foo
    

    meaning that your original python -m scripts.some_script makes absolute (sorry) sense...

提交回复
热议问题