Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

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

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 access the size variable directly from the a function? I know of :


size = dict["size"]

but I think there should be a more direct way. I tried using locals().update(dict) but it didn't work. Is there a betteer way ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code:

def lv1(d):
  locals().update(d)
  print zap

the compiler "knows" that barename zap is NOT local (not assigned in function lv1) and so it compiles code to access it as a global instead -- whatever d contains won't matter.

If you prefer slow and bloated code, you can defeat the optimization by using an exec inside the function -- when the compiler sees the keyword exec, it KNOWS you're trying to make your code as slow, bloated and buggy as possible, and so it cooperates by not optimizing in any way, just about.

So, the following code works as you desire:

def lv1(d):
  exec ""
  locals().update(d)
  print zap

lv1({'zap': 23})

it emits 23 as you want.

I hope it's clear from the above "deadpan humor" that the technique is not recommended, but I'd better spell it out very explicitly: for the dubious syntactic pleasure of writing print zap in lieu of print locals()['zap'], you ARE paying a hefty price in terms of performance. Still, like all sorts of dangerous tools that can be useful in rare use cases for really experienced guru-level programmers who really truly know what they're doing and why, exec is there, available for you to use (or mis-use) at your whim: Python does NOT stand in your way!-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...