How can I pass my locals and access the variables directly from another function?

前端 未结 5 828
没有蜡笔的小新
没有蜡笔的小新 2020-12-10 07:17

Let\'s say I have this :


def a(dict):
  locals().update(dict)
  print size

def b():
  size = 20
  f(locals())

What do I have to do to acc

5条回答
  •  难免孤独
    2020-12-10 08:06

    print size
    

    cannot work, because "size" is not known when the code is compiled. Your code will work if you change it like this:

    def a(dict):
        locals().update(dict)
        print locals()["size"]
    
    def b():
        size = 20
        a(locals())
    

    But as the comment to your question already suggests: This is very strange code. I'm very sure that there are better solutions, if you explain what you really want to do.

提交回复
热议问题