Search code examples
pythonimportarchitecture

Python: Is it a good practice to rely on import to execute code?


In Python, is it a good practice to rely on import to execute code, like in the example below?

The code in mod.py is supposed to load some config, and needs to be executed once only. It can use more complex logic, but its purpose is to establish values of some parameters, later used as configuration by main.py.

# --- mod.py ---
param1 = 'abc'
param2 = 'def'
# ...


# --- main.py ---
import mod

p1 = mod.param1
p2 = mod.param2
# (then calls functions from other components, which use p1, p2, ... as arguments)

Solution

  • Defining things in an additional module is perfectly fine - variables, classes, functions etc.

    When the module is imported, as long as you don't use from ... import * your namespace does not get cluttered and you can extract a standalone and/or repeated fragments to have cleaner code.

    It's pretty much an intended use for modules.

    What is not so good, is having code with side-effects that gets executed on import. This here gives a nice example why it's not a good idea: Say “no” to import side‐effects in Python