0

I would like to make a python module that can work both as standalone (so with a __main__ that has positional parameters for the options) and as regular module (so I can import the class(es) in the module for a pure code-based approach.

Is there a best practice to do so; in a way that neither the standalone nor the import action is affecting negatively the module?

I have in mind a simple module with one class, which contain different functions; and then at the bottom I have the

if __name__ == '__main__':
    # collect parameters and run a function in the class

Which is used if I want to call my module as standalone.

  • 3
    So long as you put all the standalone-only stuff inside the `__main__` block, you should be fine. – Scott Hunter Jul 31 '19 at 18:28
  • 1
    Look at the setuptools entrypoint mechanism; it's built for exactly this purpose, and does a better job than the `__name__ == '__main__'` approach (f/e, automatically generating executable wrappers on installation). For an introduction, see [Explain Python entry points](https://stackoverflow.com/questions/774824/explain-python-entry-points). – Charles Duffy Jul 31 '19 at 18:29
  • 2
    You just answered your own question... `if __name__ == '__main__':` **is** exactly the way to do that – Tomerikoo Jul 31 '19 at 18:29
  • That's how it's done lol. – Diptangsu Goswami Jul 31 '19 at 18:46
  • I disagree with the consensus in the comments, but "best practice" questions are innately considered too broad to be on-topic here, so writing up an answer would be inappropriate. See [Why is asking a question on "best practice" a bad thing?](https://meta.stackexchange.com/questions/142353) on [meta.se]. – Charles Duffy Jul 31 '19 at 20:02
  • Thanks for the replies. I am experimenting with Python making generic modules, so in the past I either made "apps" with the `__main__` in it or a pure class in the module. And just FYI, the question was not much on "what is the best way", but "what is the more correct way, in Python language". So not based on preferences, but on objective concepts due to the fact that Python as language expect certain structures and ordering, to do specific operation, like in my case. –  Aug 02 '19 at 04:28

0 Answers0