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.

2
  • You don't want to hear this, but your solution doesn't work and the correct solution is to avoid globals. Commented Jun 2, 2018 at 8: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. Commented Jun 2, 2018 at 9:21

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

I think this answer is better than mine, because this, which readers should be aware of.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.