Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 896
wojciech Avatar asked Sep 04 '26 16:09

wojciech


2 Answers

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

like image 109
matszwecja Avatar answered Sep 06 '26 07:09

matszwecja


code in mod.py is supposed to load some config, and needs to be executed once only.

Using import statement leads to

  1. find a module, loading and initializing it if necessary
  2. define a name or names in the local namespace for the scope where the import statement occurs.

therefore even numerous usage of import mod will lead to execution of code in it just once, consider following toy example, let mod.py content be

print("I am mod.py")

and main.py content be

import mod
import mod
import mod

then output of python main.py will be

I am mod.py
like image 35
Daweo Avatar answered Sep 06 '26 05:09

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!