Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A python module for global parameters - is this good practice?

Tags:

python

I'm a mechanical engineering student, and I'm building a physical simulation using PyODE.

instead of running everything from one file, I wanted to organize stuff in modules so I had:

  • main.py
  • callback.py
  • helper.py

I ran into problems when I realized that helper.py needed to reference variables from main, but main was the one importing helper!

so my solution was to create a 4th file, which houses variables and imports only external modules (such as time and random).

so I now have:

  • main.py
  • callback.py
  • helper.py
  • parameters.py

and all scripts have: import parameters and use: parameters.foo or parameters.bar.

Is this an acceptable practice or is this a sure fire way to make python programmers puke? :)

Please let me know if this makes sense, or if there is a more sensible way of doing it!

Thanks, -Leav

like image 324
Leav Avatar asked Aug 29 '26 11:08

Leav


2 Answers

Separate 'global' files for constants, configurations, and includes needed everywhere are fine. But when they contain actual mutable variables then they're not such a good idea. Consider having the files communicate with function return values and arguments instead. This promotes encapsulation and will keep your code from becoming a tangled mess.

Clear communication between files makes them easier to understand and makes what's going on more obvious. When you're using variables and nobody knows where they came from, things can get pretty annoying. :)

like image 58
Gordon Gustafson Avatar answered Aug 31 '26 01:08

Gordon Gustafson


Uhm, i think it does not make sence if this happens: "realized that helper.py needed to reference variables from main", your helper functions should be independent from your "main code", otherwise i think its ugly and more like a design failure.

like image 21
InsertNickHere Avatar answered Aug 31 '26 03:08

InsertNickHere



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!