Scope and Variable Binding in Python
1. Python only has two notions of scope -- global and local. This means that if a variable is declared in a function, it is bound to the function. Otherwise it is bound to the global state.
You can inspect everything that is bound globally by calling globals(), and everything that is bound locally by calling locals()
2. In the following post I will investigate variable binding and scope in python via an interactive python session. That is, by example. If you want to follow along, check out the documentation for dir() and dis.
Local modifications stay local
# define a global variable aIn [1]: a = 5# modify a locallyIn [2]: def foo():...: a = 3...:In [3]: foo()# did global a change?In [4]: aOut[4]: 5# nope.
Global variables can be accessed but not modified
In [10]: a = 5In [11]: def foo():....: print a....:In [12]: foo()5
In order to modify a function in global scope, you must declare it to be global first. The relevant difference is explained by the following byte code snippets. In the case where a is a local variable, STORE_FAST is called, whereas in the case where a is a declared global, STORE_GLOBAL is called.
Compare:
In [21]: def foo():....: a = 3....:In [22]: dis.dis(foo.func_code)2 0 LOAD_CONST 1 (3)3 STORE_FAST 0 (a)6 LOAD_CONST 0 (None)9 RETURN_VALUE
And:
In [24]: def foo():....: global a....: a = 3....:# modification is successfulIn [25]: foo()In [26]: print a3In [27]: dis.dis(foo.func_code)3 0 LOAD_CONST 1 (3)3 STORE_GLOBAL 0 (a)6 LOAD_CONST 0 (None)9 RETURN_VALUE
Expressions are always in global scope.
As a review, expressions are constructs like if/while/for/try/except. The point below is made with if statements, but would apply equally to any of the others.
# b is first defined inside a trivially true if statementIn [6]: if True:...: b = 21...:# b is still defined globallyIn [7]: bOut[7]: 21# it does matter that the if statement is evaluatedIn [10]: if False:....: b = 1337....:In [11]: b
Out[11]: 21
This contrasts with other languages like C, where variables have block scope.
#includeint main(){if(1){int a = 6;printf("%d\n", a);}printf("%d\n", a);return 0;
}
for example, generates a compile time error: ‘a’ undeclared at the second printf statement.
Nested Function Scope
# let’s see what happens hereIn [18]: def foo():....: a = 5....: def goo():....: print a....: goo()In [19]: foo()Out[19]: 5
Inner functions have access to the outer functions’ local variables. This is the basis of functional closures. Similar behavior occurs for lambdas.
In [23]: def foo():....: a = 5....: b = (lambda : a)()....: print b....:
The fact that functions and lambdas have access to external scope is useful for closures, but also opens up this common bug*:
# define a sequence of functionsIn [40]: fs = [(lambda n: i + n) for i in xrange(10)]# e.g.In [41]: fsOut[41]:[<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>,<function __main__.<lambda>>]# now apply one of the functions in the sequenceIn [43]: fs[0](3)
Out[43]: 12 # wait...wtf?
Let’s see exactly what’s happening here, just for fun:
In [49]: [dis.dis(i.func_code) for i in fs]1 0 LOAD_GLOBAL 0 (i)3 LOAD_FAST 0 (n)6 BINARY_ADD7 RETURN_VALUE1 0 LOAD_GLOBAL 0 (i)3 LOAD_FAST 0 (n)6 BINARY_ADD7 RETURN_VALUE...
<snipped>
The lambda loads i from globals, because i cannot be found within its local scope. But during the construction of the function sequence, i changes. By the time any of the functions are called, i has been incremented to 9, and so fs[0][3] doesn’t add 0 to 3 but rather 9 to 3. This is reflected in the byte code by the LOAD_GLOBAL instruction.
To avoid problems like this one, remember that python will always look for unknown function variables in global (or higher level function) scope.
Class vs Instance vs method scope
Scope behaves in the same way for functions as for classes and objects. In fact, functions are objects. If you have some experience with python, you probably already know how to define class variables and instance variables. Class variables are declared under the class declaration, and outside of any functions. Instance variables are defined attached to self, as follows:
class Foo(object):# class variablea_class_var = 'yo yo'def __init__(self):# instance variableself.an_instance_var = 'whattttt'
Brief Exercise for the reader: input the above into ipython, and compare dir(Foo)with dir(Foo())
Consider the following class
class Foo(object):# class variablex = 'yo yo'bar = Foo()
What is bar.x?
What is Foo.x?
Solution: Both are ‘yo yo’
How about this class?
class Foo(object):x = 'yo yo'def __init__(self):# print self.xself.x = 'whattttt'# print self.x
bar = Foo()
Now,
What is bar.x?
What is Foo.x?
In this case, bar.x= ‘whattttt’ and Foo.x = ‘yo yo’. If you uncomment the print statements though, you’ll notice that initially self.x = ‘yo yo’. Huh?
Conceptually, we can think of Foo as a template for all of it’s instances. The class variable x, declared as ‘yo yo’ gets copied to the instance bar on creation. self.x in the initializer is not referring to the class’s x, but rather to the instance’s x. We never tamper with the class’s x at all. If you do want to change Foo’s x, you would set self.__class__.blah.
One important thing to note is that creating foo from Foo does a shallow copy of Foo’s internals. So
class Foo2(object):hi = []def __init__(self):self.hi.append('1')bar2 = Foo2()print bar2.hibar3 = Foo2()print bar3.hiprint Foo2.hi
The class Foo2’s copy of hi was modified by its instances because on instance creation, a reference to hi was copied, but not hi itself. You may have seen this error disguised as:
In [1]: def foo(blah = []):...: blah.append(1)...: return blah...:In [2]: foo()Out[2]: [1]In [3]: foo()Out[3]: [1, 1]In [4]: foo()Out[4]: [1, 1, 1]
End
Hopefully these examples have given you some intuition about scope in python. For more detailed explanations of the examples in this post, check out the Python Language Reference. Or try out your own explorations in ipython.
*http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/ inspired by this post. Even though the title of that article seems strongly worded. It appears that Guido agrees: http://www.artima.com/weblogs/viewpost.jsp?thread=98196
20160603lindong
ReplyDeletecartier love bracelet
bottega veneta outlet
hollister
hollister clothing
ray ban outlet
michael kors handbags
michael kors outlet
levis jeans
ray ban sunglasses outlet
louis vuitton factory outlet
oakley sunglasses
adidas nmd
prada outlet
nike air max
cheap nba jerseys
coach factory outlet
michael kors outlet
air jordan uk
fitflops outlet
christian louboutin
michael kors handbags
red bottom shoes
michael kors watches
reebok shoes
under armour shoes
michael kors outlet
michael kors outlet
kate spade handbags
coach outlet
nike huarache trainers
hollister clothing
jordan pas cher
louis vuitton
ReplyDeletelouis vuitton handbags
louis vuitton outlet
christian louboutin sale
kobe bryant shoes
true religion outlet
ray ban sunglasses
michael kors outlet clearance
louis vuitton handbags
toms
louis vuitton outlet stores
cheap oakleys
michael kors handbags
louis vuitton
michael kors outlet
adidas nmd
gucci outlet
michael kors outlet
coach outlet online
louis vuitton
true religion shorts
louis vuitton outlet
air max 90
jordan 8
celine outlet
coach outlet online
nike air max 90
ray ban outlet
michael kors handbags
nike air force 1
christian louboutin outlet
louis vuitton handbags
coach outlet
replica watches for sale
adidas shoes
coach outlet store online clearances
christian louboutin
marc jacobs
christian louboutin outlet
true religion outlet
2016.7.9haungqin
louis vuitton outlet
ReplyDeletelouis vuitton
nike trainers
michael kors outlet
cincinnati bengals jerseys
cheap jordan shoes
louis vuitton
adidas shoes
adidas yeezy 350
timberland outlet
nike air max 90
pandora jewelry
michael kors canada
coach factory outlet
ugg sale
kobe 10 shoes
michael kors outlet
authentic louis vuitton handbags
kate spade handbags
ugg outlet
louis vuitton
jordan retro 3
canada goose pas cher
coach outlet
uggs outlet
ralph lauren
jordan 6
juicy couture
pittsburgh steelers jerseys
chenyingying2016815
20161108meiqing
ReplyDeletekate spade handbags
ferragamo shoes
ralph lauren outlet
cheap jordans
toms shoes outlet
christian louboutin
birkenstock shoes
gucci handbags
uggs
ralph lauren outlet
red valentinodownload
ReplyDeletenike blazer lowfew
cheap nhl jerseysFriday
ed hardy outletFriday
fitflops sale clearanceARE
michael kors handbagsyour
air max 90adding
cheap michael kors handbagsbusiness
michael kors handbags outletthe
birkenstockson
moncler outlet online
ReplyDeleteray bans
coach outlet online
polo ralph lauren outlet online
yeezy boost
coach factory outlet online
coach outlet store online
moncler jackets
cheap oakley sunglasses
coach outlet canada
2017223yuanyuan
ray ban aviators
ReplyDeletecoach outlet
ray ban sunglasses
nike store
cheap pandora jewelry
true religion uk
ray ban sunglasses outlet
coach factory online
nike air max
nfl jerseys wholesale
20174.17wengdongdong
longchamp handbags
ReplyDeletecanada goose outlet
cheap snapbacks
mac cosmetics
coach outlet
ray ban sunglasses
herve leger outlet
nike shoes
canada goose jackets
christian louboutin outlet
20171106caihuali
coach outlet
ReplyDeletelunette ray ban
pandora outlet
coach outlet online
nike shoes for men
canada goose
vibram fivefingers
canada goose jackets
mcm bag
adidas nmd
shenyuhang20180620
Pandora
ReplyDeleteYeezy boost 350 v2
Pandora Outlet
Jordan Retro 9
Air Max 270
Red Bottom Shoes For Women
Yeezy boost
Jordans 11
Jordan 9
Jordan Retro
Paul20181008
freedom apk latest whatsapp plus free download creehack apk free download
ReplyDeletenike lunarglide
ReplyDeletenike air max
hermes
paul george shoes
soccer jerseys
superdry clothing
ralph lauren polo
canada goose jackets
ray bans
the north face jackets
chenlina20181114
Jordan 9
ReplyDeletePandora Jewelry Official Site
Jordan 11
Kyrie Irving Shoes
Air Max 270
Pandora Outlet
Air Jordan
Red Bottom Shoes For Women
Pandora Charms
Latrice20190217
Pandora Outlet
ReplyDeleteJordan Retro 11
Air Jordan 4
Nike Air Max 270
Pandora Jewelry
Jordan 11
Yeezy boost 350 v2
Red Bottom Shoes For Women
Pandora Jewelry
Kyrie 3 Shoes
Ryan20190321
Menjalin hubungan tanpa komitmen dengan gaya pergaulan bebas yang kemudian terjadilah kehamilan dapat memicu melakukan cara menggugurkan hamil muda karena adanya ketidak siapan dan sebagainya . Langkah menggugurkan kandungan mereka harapkan untuk cara mencegah kehamilan yang tidak mereka inginkan . Etah itu karena keterbatasan finansial atau apalah mereka mengambil jalan praktis dengan cara menggugurkan kandungan dengan manjakani ataupun asam jawa , kunyit asam dan buah-buahan seperti nanas muda maupun nanas muda untuk solusi mengatasi masalahnya . Pernahkah anda mengalami mimpi basah , lalu apa yang bisa Anda rasakah ? . Jika pasangan wanita ada sedang mengalami menstruasi sebaiknya tidak boleh di gauli terlebih dulu , tunggu masa menstruasinya sampai tuntas . Jika sudah selesai maka silahkan saja untuk mempergauli sampai cara membuat wanita cepat klimak dan keluar cairan orgasme agar puas .
ReplyDeleteI like this post because it contains a lot of useful information to read, maybe everyone will like me. I hope this post of yours will be more appreciated by it really excellent, i enjoyed it, thanks for posting it.
ReplyDeleteio games 4 school, Jogos de Friv, 360 jogos 2019, cá koi mini
We don't yet know which 10 teams will be a part of the 2019 MLB postseason, but we do know when they'll be playing. MLB has released the full playoff schedule for this year, and it begins on Oct. 1 with the https://jerban.com/ Wild Card Game and runs through a potential Game 7 of the World Series on Oct. 30. In other words, we won't be playing November baseball this year. By way of reminder, each Wild Card Game is a one-and-done affair, the Division Series round is a best-of-five, and each League Championship Series and the World Series are best-of-seven series.
ReplyDeletebut the transfer company Removals from Jeddah to Abha packaging all furnishings to be fully maintained during the road and does not leak any dust and any dust until you reach the new house is clean and does not have any dirtشركة نقل عفش
ReplyDeleteشركة نقل عفش من الرياض الى قطر
شركة نقل اثاث من الرياض الى قطر
شركة نقل عفش بالاحساء
Wonderful post! We are linking to this particularly great article on our site. Keep posting!
ReplyDeletewww.freesitemaker.net/how-to-make-a-website/ecommerce-website-structure
This is Very very nice article. Everyone should read. Thanks for sharing. Don't miss WORLD'S BEST BikeRacingGames
ReplyDelete