Creating a global variable (from a string) from inside a class

Context: I'm making a Ren'py game. The value of Character (). Yes, I know that this is a stupid idea outside this context.

I need to create a variable from an input string inside a class that exists outside the scope of the class:

class Test: def __init__(self): self.dict = {} # used elsewhere to give the inputs for the function below. def create_global_var(self, variable, value): # the equivalent of exec("global {0}; {0} = {1}".format(str(variable), str(value))) # other functions in the class that require this. Test().create_global_var("abc", "123") # hence abc = 123 

I tried vars()[] , globals()[variable] = value , etc., and they just don't work (they don't even define anything) Edit:. That was my problem.

I know that the following will work the same way, but I want the variables to be in the correct area:

 setattr(self.__class__, variable, value) # d.abc = 123, now. but incorrect scope. 

How can I create a variable in global scope inside a class using a string as a variable name without using attributes or exec in python?

And yes, I will check the performance.

+2
source share
2 answers

First of all: what we call the global area in Python is actually a โ€œmodularโ€ area (on the other hand, it reduces the โ€œevilโ€ from using global vars).

Then, to dynamically create a global var, although I still can't figure out why this is better than using a module level dictionary, just do:

 globals()[variable] = value 

This creates a variable in the current module. If you need to create a modular variable in the module from which the method was called, you can look into the global dictionary from the callerโ€™s frame using:

 from inspect import currentframe currentframe(1).f_globals[variable] = name 

Now this seems completely useless, since you can create a variable with a dynamic name, but you cannot access it dynamically (unless you use the global dictionary again)

Even in your test case, you create the variable "abc" by passing the string method, but then you need to access it using the hard code "abc" - the language itself is designed to prevent this (from here is the Javascript difference, where the array indices and object attributes are interchangeably, while in Python you have distinc matching objects)

My suggestion is that you use an explicit module level dictionary and create all your dynamic variables as key / value pairs:

 names = {} class Test(object): def __init__(self): self.dict = {} # used elsewhere to give the inputs for the function below. def create_global_var(self, variable, value): names[variable] = value 

(on the side of the note, in Pyhton 2 your classes always inherit from the "object")

+5
source

You can use setattr(__builtins__, 'abc', '123') for this.

Keep in mind that this is most likely a design issue, and you must rethink the design.

+2
source

Source: https://habr.com/ru/post/916951/