python - How to create global variables dynamically from base class defined in a separate file? - Stack Overflow

My real scenario needs to create global variables dynamically from within a function defined in a libra

My real scenario needs to create global variables dynamically from within a function defined in a library so it can be reused for many projects. The function can be either a method in a base class or a global function.

For the sake of simplicity, consider the following a trivial example. I know the global variables are in file or module scope.

# mylib.py
class Parent:
    def __init__(self, var_name):
        self.__var_name__ = var_name
    def create_global_variable(self, var_value):
        globals()[self.__var_name__] = var_value
    def clear_global_variables(self):
        globals().clear()
# test.py
from mylib import Parent
class Child(Parent): pass
child = Child('temperature')
child.create_global_variable(100)
print(temperature) # NameError: name 'temperature' is not defined
child.clear_global_variables()

Is there any trick to bypass the restriction?

Edit

job() will be reused in many projects.

def job(input, predicate, buffer_name):
    globals()[buffer_name] = predicate(input)
    return input


exp = fr"""
Squaring {job(2,lambda x: x*x, 'square')} equals to {square} 
"""

print(exp)

Constraint: all buffering variables must be defined in f-string.

My real scenario needs to create global variables dynamically from within a function defined in a library so it can be reused for many projects. The function can be either a method in a base class or a global function.

For the sake of simplicity, consider the following a trivial example. I know the global variables are in file or module scope.

# mylib.py
class Parent:
    def __init__(self, var_name):
        self.__var_name__ = var_name
    def create_global_variable(self, var_value):
        globals()[self.__var_name__] = var_value
    def clear_global_variables(self):
        globals().clear()
# test.py
from mylib import Parent
class Child(Parent): pass
child = Child('temperature')
child.create_global_variable(100)
print(temperature) # NameError: name 'temperature' is not defined
child.clear_global_variables()

Is there any trick to bypass the restriction?

Edit

job() will be reused in many projects.

def job(input, predicate, buffer_name):
    globals()[buffer_name] = predicate(input)
    return input


exp = fr"""
Squaring {job(2,lambda x: x*x, 'square')} equals to {square} 
"""

print(exp)

Constraint: all buffering variables must be defined in f-string.

Share Improve this question edited Mar 21 at 20:27 D G asked Mar 21 at 19:55 D GD G 8298 silver badges15 bronze badges 12
  • 2 pass globals() to Child(globals(), 'temperature') but this seems like a bad idea. Perhaps if you explained your motivate a bit there might be a better alternative approach than using globals. – JonSG Commented Mar 21 at 20:10
  • 2 @JonSG my point is that there shouldn't be a class Parent or some def mess_with_globals in some module. The client code should just deal with globals() directly, if that's what it wants to do. but if there really was a good reason to do this, the only approach would be for the client to pass in their own globals as you suggested (aside from stack introspection hacks) – juanpa.arrivillaga Commented Mar 21 at 20:16
  • 1 @juanpa.arrivillaga I agree 100% – JonSG Commented Mar 21 at 20:17
  • 2 This has a real hacky code-smell to it. It seems like you're asking us to help you solve the wrong thing; xyproblem.info Why do you think you need this? Please provide a minimal reproducible example of the actual problem you're trying to solve with globals. – MatBailie Commented Mar 21 at 20:27
  • 1 Re: Constraint: all buffering variables must be defined in f-string. ; WHY? – MatBailie Commented Mar 21 at 20:29
 |  Show 7 more comments

1 Answer 1

Reset to default 1

If you really wanted to do this, I would suggest reading How do I create variable variables? and if you still wanted to proceed I woud think about something like this that will allow you to pass in the context you want to manipulate.

mylib.py:

class Parent:
    def __init__(self, context, var_name):
        self.__context__ = context
        self.__var_name__ = var_name
    def create_global_variable(self, var_value):
        self.__context__[self.__var_name__] = var_value
    def clear_global_variables(self):
        if self.__var_name__ in self.__context__:
            del self.__context__[self.__var_name__]

test.py:

from mylib import Parent

class Child(Parent):
    def __init__(self, var_name):
        super().__init__(globals(), var_name)

child = Child("temperature")

child.create_global_variable(100)
print(temperature)

child.clear_global_variables()
print(globals().get("temperature"))

child.clear_global_variables()

That should give you:

100
None

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744335659a4569102.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信