Skip to content Skip to sidebar Skip to footer

Creating A Global Variable (from A String) From Within A Class

Context: I'm making a Ren'py game. The value is Character(). Yes, I know this is a dumb idea outside of this context. I need to create a variable from an input string inside of a

Solution 1:

First things first: what we call "global" scope in Python is actually "module" scope (on the good side, it diminishes the "evils" of using global vars).

Then, for creating a global var dynamically, although I still can't see why that would be 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 module variable on the module from which the method was called, you can peek the globals dictionary from the caller frame using:

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

Now, the this seems specially useless since you may create a variable with a dynamic name, but you can't access it dynamically (unless using the globals dictionary again)

Even in your test example, you create the "abc" variable passing the method a string, but then you have to access it by using a hardcoded "abc" - the language itself is designed to discourage this (hence the difference to Javascript, where array indexes and object attributes are the interchangeable, while in Python you have distinc Mapping objects)

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

names = {}
classTest(object):def__init__(self):
        self.dict = {} # used elsewhere to give the inputs for the function below.defcreate_global_var(self, variable, value):
         names[variable] = value

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

Solution 2:

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

Do mind you that this is most likely a design problem and you should rethink the design.

Post a Comment for "Creating A Global Variable (from A String) From Within A Class"