0

I want to use strings as variable names inside a init method of a function, however it does not seem to work so far. I tried the following:

class SomeClass:

    def __init__(self, car_brand="BMW", **kwargs):
    
    
        car_brand = 'Mercedes'
    
        # change car_brand variable with exec
        exec("identifier " + "= 'Audi'")
    
        # change car_brand variabel with local
        str = "car_brand"
        locals()[str] = 'Audi'
    
        self.car_brand = car_brand
    
sc = SomeClass(car_brand="BMW")
sc.car_brand

My output is "Mercedes" so apparently it is possible to simply overwrite the input argument however it is not possible to overwrite the variable with "Audi" using the string "car_brand" as variable name.

pippo1980
  • 2,181
  • 3
  • 14
  • 30
  • This has been done to death. Just use a dictionary. – Chris Sep 21 '22 at 15:02
  • 1
    You shouldn't call a variable `str`, that's a built-in name. Also, what is `car_bran` in the line `self.car_brand = car_bran`? Also, `exec("identifier " + "= 'Audi'")` relevant at all to this post? – Random Davis Sep 21 '22 at 15:03
  • What I want to use it for is instantiating the class either with the argument car_brand="Audi" or with a kwargs dictionary kwargs={"car_brand":"Audi"}. Maybe there is a much better way to achieve this in general? – python444444 Sep 21 '22 at 15:18
  • Check if the key `"car_brand"` was provided in the dictionary? – Ignatius Reilly Sep 21 '22 at 15:32
  • `self.car_brand = kwargs["car_brand"] if "car_brand" in kwargs else "Audi"` ?? – 001 Sep 21 '22 at 15:37
  • https://stackoverflow.com/questions/70515070/how-to-update-dictionary-values-present-within-local-symbol-table – pippo1980 Sep 21 '22 at 16:13
  • yes thats exactly what I do but I am trying to put it in a for-loop to automatically use all dict keys as variable names for the respective dict value – python444444 Sep 22 '22 at 05:13
  • locals(), on the other hand, returns a dictionary that is a current copy of the local namespace, not a reference to it. So you can’t modify objects in the actual local namespace using the return value from locals(). – pippo1980 Sep 22 '22 at 07:27

1 Answers1

0

There are multiple ways to accomplish this.

# modifying the globals
globals()[name] = value
from operator import setitem
setitem(globals(), name, value)
# custom dicionary, like globals
custom_dict[name] = value

Perhaps you want to modify only the current instance's attributes?

setattr(self, name, value)
musava_ribica
  • 476
  • 1
  • 5
  • 18