0

I have a module; say it's structured as:

algorithms
 ├─ __init__.py
 └─ algorithm.py

Inside my algorithm module, I have some global vars, and I would like to create a convenience initializer that sets them up. I would like to use the same names for the initializer's parameters as for the vars, but that leads to a conflict of local and global names. The cleanest way I can think of to implement this is:

lower = None
upper = None

def init_range(lower, upper):
   _lower = lower
   global lower
   lower = _lower

   _upper = upper
   global upper
   upper = _upper

If this were a class, (I think) I could do something like self.lower = lower. Is there a less verbose way to do what I'm doing for module-global vars? Something like algorithm.lower = lower?

EDIT: Turns out my solution doesn't work.

Phlippie Bosman
  • 3,983
  • 3
  • 21
  • 26
  • You don't want to hear this, but your solution doesn't work and the correct solution is to avoid globals. – Aran-Fey Jun 02 '18 at 08:52
  • You're correct, it doesn't work :( but in my case, I already use globals everywhere (this is a very minimal example), and there's no time to change that. – Phlippie Bosman Jun 02 '18 at 09:21

2 Answers2

2

If you really insist on keeping the parameter names lower and upper (why not just new_lower, new_upper or something like that?) then you could delegate the task to an inner function with alternative variable names.

def init_range(lower, upper):
    def _init_range(_lower, _upper):
        global lower
        global upper
        lower = _lower
        upper = _upper

    _init_range(lower, upper)

Demo:

>>> lower is None, upper is None
(True, True)
>>> init_range(lower=1, upper=2)
>>> lower, upper
(1, 2)
timgeb
  • 64,821
  • 18
  • 95
  • 124
2

You can use the globals function to get the dictionary representing the global scope, and update it:

def init_range(lower, upper):
   globals().update(lower=lower, upper=upper)
Aran-Fey
  • 30,995
  • 8
  • 80
  • 121
  • I think this answer is better than mine, because [this](https://stackoverflow.com/questions/5958793/is-it-safe-to-modify-the-output-of-globals), which readers should be aware of. – timgeb Jun 02 '18 at 08:58