Set a runtime variable from a string and a python object

Asked

Viewed 43 times

-1

I want to add a variable to my code or in memory at runtime, I’m looking for something like this since yesterday and can’t get the desired result.

Let’s say I have an object: (<bound method Menu.adSabor of <__main__.Menu object at 0x00000219635E6040>>), and I want reference to it at execution time. for example: (def referencia(self, 'nome_da_variavel_em_string', <bound method Menu.adSabor of <__main__.Menu object at 0x00000219635E6040>>, the nome_da_variavel_em_string will be the new reference of the object, where I can call it with self.nome_da_variavel_em_string)

1 answer

0


If I understand correctly, you want enter a variable using a string that contains the variable name.

If the variable is global, you can use the function globals, which returns a dictionary containing all global variables, and access its variable of interest using its name as key:

X = "Olá"
retorno = globals()["X"]
print(retorno)  # printa "Olá"

Equivalently, you can use the function locals if the variable is a local variable (eg defined within the body of a function):

def f():
    Y = 5
    return locals()["Y"]

print(f())  # printa 5

Still, if your variable is defined in some other module, or if it is a method/attribute of an object, you can use the function getattr, by passing your module/object and the name of the desired attribute inside it:

import meu_modulo

print(getattr(meu_modulo, "Z"))  # printa o valor de meu_modulo.Z
class A:
    valor = 10

instancia = A()
print(getattr(instancia, "valor"))  # printa 10

Having said all that, I recommend you reflect whether it would not make more sense in your code to use a dictionary or some other data structure to keep references to your objects of interest. Directly access the dictionary globals seems a bit obfuscated - if you need references to your objects, create some structure that maintains them. Explicit is better than implicit ;-)

Edit:

If you want create/modify a method or attribute of an object, can use the function setattr:

class A:
    valor = 10

    def metodo(self):
        return self.valor

setattr(A, "novo_metodo", A.metodo)

instancia = A()
print(instancia.novo_metodo())  # printa 10

Note that A.novo_metodo is only a copy of A.metodo - both exist within the class body. If you want to delete the old method, you need to use del A.metodo.

If you want to add or modify a global/local variable by name, you will need to modify the dictionary returned byglobals/locals, respectively. However, I do not recommend this approach, either by obfuscating the code further, or by potentially modifying some value that Python relies on. Again, it makes more sense to define a proper dictionary for this.

  • this is a nice way, but has how I reference? I can call a certain function with self.nome_da_função , but I want to change this name to another using a string

  • @Heitortasso edited the answer and added one more example, see if it helps you.

  • helped a lot, thank you for the attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.