Referencing and setting variables in Python dicts

后端 未结 3 851
感情败类
感情败类 2021-01-17 03:19

I want to use a python dict to store variable references and be able to assign the values pointed out by those references.

foo = \"foo\"
d = {\'foo\' : foo}
         


        
3条回答
  •  暖寄归人
    2021-01-17 03:43

    Python implements references to objects but it does not implement refs to variables. You can create a read-only binding to a local variable by using a local function:

    foo = "foo"
    def readfoo(newval):
         return foo
    d["foo"] = readfoo
    foo = "bar"
    d["foo"]() # returns "bar"
    foo = "baz"
    d["foo"]() # returns "baz"
    

    This, however, is read-only since local function can only read vars from outside scope (I believe in Python 3 there's the nonlocal keyword that changes this).

    Depending on what you really want to achieve, the simplest workaround is to use one element lists instead. This way you wrap your values in objects (the lists) which can be referenced normally:

    foo = ["foo"]
    d["foo"] = foo
    d["foo"][0] = "bar"
    foo[0] # prints "bar"
    

提交回复
热议问题