Python variable scope

By Brian Fitzgerald

Python variable scoping rules are different from other languages. If you are accustomed to java, the behavior may surprise you. Scope can be file, class, or function; however, control blocks such as if-else, try-except, or while do not define scope. A variable that is defined in a control block can be used after the control block.

A simple demonstration case is the if-else block. In function test, variable a is set in the if and else blocks, and is used after the if-else structure.

scope1

Not defining a variable before entering a control block is considered idiomatic python. IDE PyCharm reports no warnings. If you try to define variable a before the if-else block, as you would in java, PyCharm greys out a and reports it as an unused variable.

scope2.png

Finally, if statement “a = 0” is changed to “pass”, then in statement “a = None”, a is no longer reported as an unused variable, and is displayed in dark grey.

scope3.png

In conclusion, python scoping is different from java’s. You should not carry java variable declaration habits into python projects.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s