Presentation is loading. Please wait.

Presentation is loading. Please wait.

Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –

Similar presentations


Presentation on theme: "Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –"— Presentation transcript:

1 Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound – Three types Local, global, and built-in They are checked by Python in that order Scope of a variable – The region of the program where the variable is accessible

2 Namespaces Local namespace – Contains variables that were created in a block of code, e.g. each function has a unique local namespace Global namespace – Stores the names of functions, classes, variables defined within the file or module on outermost level – Each module contains an identifier __name__ It holds the name of the module (“ math ”) or “ __main__ ” (we’ll see how that can be used) Built-in namespace – Contains functions such as raw_input, int, and range – The built-in namespace is included when the interpreter starts (thus we automatically have access to these functions)

3 Namespaces built_in global local import math def f(a): x = 7 print y x = 9 z = 13 f(z) range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x = 9, z = 13,.. a = 13, x = 7 ?

4 def f(a): q = 7 z = 13 f(z) global namespace local namespace z aqaq 13 7 f

5 built_in global local import math def f(a): x = 7 x = 9 z = 13 f(z) print x range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x = 9, z = 13,.. a = 13, x = 7 local x global x Value of x..? 9.

6 local namespace def f(a): q = 7 z = 13 f(z) a = 13, q = 7

7 built_in global local import math def f(a): global x x = 7 x = 9 z = 13 f(z) print x range, raw_input, int, float,.. __name__ = ‘__main__’, math, f, x =.., z = 13,.. a = 13 global x Value of x..? 7!

8 Using identifiers outside their scope Scope of a variable – The region of the program where the variable is accessible def area(r): pi = 3.15 return pi*r*r* a = area(1.0) print pi a = area(1.0) def area(r): pi = 3.15 return pi*r*r*  

9 def area(r): pi = 3.15 return pi*r*r* a = area(1.0) print pi a = area(1.0) def area(r): pi = 3.15 return pi*r*r*  

10 Function dir() >>> >>> dir() ['__builtins__', '__doc__', '__name__'] >>> >>> print __name__ __main__ >>> >>> x = 3 >>> dir() ['__builtins__', '__doc__', '__name__', 'x'] >>> >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError',.... 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round',.. built-in function dir() lists the identifiers in the current namespace Since this is not a module (but rather an interactive session), the value of __name__ is __main__ dir(__builtins__) lists identifiers in the __builtins__ module new global variable

11 Function help() >>> help(range) Help on built-in function range: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2,..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. The function help( ) gives you help in the interactive mode

12 Listing identifiers in an imported module Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import math >>> dir() ['__builtins__', '__doc__', '__name__', 'math'] >>> >>> print math >>> >>> dir( math ) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh','e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10','modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> >>> math.sqrt( 9.0 ) 3.0 identifier math now points to a module dir(math) lists all identifiers in the math module

13 Importing only parts of a module The from/import statement – For importing only a specific part of a module – Takes identifiers from a module and inserts them directly into the current program’s name space (avoids e.g. math. prefix) >>> from math import sqrt >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sqrt'] >>> >>> sqrt( 9.0 ) 3.0 >>> >>> from math import sin, cos, tan >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'cos', 'sin', 'sqrt', 'tan'] Now directly a part of the current namespace

14 Directly importing all identifiers from a module >>> from math import * >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp','log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] Danger! If you already have a log() function with a different purpose (perhaps you are a captain and wrote the function to access the log of your spaceship..), it will be shadowed! Either just import math and use math.log(), or..

15 Binding new names to modules and module functions from import as – imports a function but gives it a different name: from math import log as logarithm You can also give a new name to an entire module: – import math as mathtoolbox

16 The __name__ identifier Documentation string. Printed by help() if called on this function This code is only executed if the file is python’ed directly, not if it is imported. gcd_function.py

17 threonine:~...ExamplePrograms% python gcd_function.py Input first integer > 0: 39 Input second integer > 0: 63 The greatest common divisor of 39 and 63 is 3 threonine:~...ExamplePrograms% python Python 2.3.2 (#1, Nov 13 2003, 20:02:35) [GCC 3.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import gcd_function as gcd_module >>> >>> print gcd_module.gcd( 39, 63) 3 >>> Executing file directly: Importing file:

18 Default Arguments A function may sometimes be called repeatedly with the same values – When this is true default arguments can be set Must appear to the right of any other arguments in the function definition’s argument list: def myfunction( a, b = 2, c = 3 ): Given values are ‘filled in from the left’ (resolves ambiguity) myfunction(6, 3) # set a and b, use default for c myfunction(6) # set a, use default for b and c – A default value can also be overridden: myfunction(6, 3, 7) # overrides default c value

19 def boxVolume( length = 3, width = 2, height = 1 ): return length * width * height print "The default box volume is:", boxVolume() print "\nThe volume of a box with length 10," print "width 2 and height 1 is:", boxVolume( 10 ) print "\nThe volume of a box with length 10," print "width 5 and height 1 is:", boxVolume( 10, 5 ) print "\nThe volume of a box with length 10," print "width 5 and height 2 is:", boxVolume( 10, 5, 2 ) The default box volume is: 6 The volume of a box with length 10, width 2 and height 1 is: 20 The volume of a box with length 10, width 5 and height 1 is: 50 The volume of a box with length 10, width 5 and height 2 is: 100 All default values usedThe 10 will replace the 3 and the other default values will be used No default values used Here two values are sent replacing the two left-most default values

20 Keyword Arguments Keyword arguments – You can use argument names as keywords: – Allows arguments to be passed in any order as long as they are explicitly stated: def myfunction( a = 2, b = 3 ):.. myfunction ( b = 5, a = 9 ) – Will use default values for those arguments that were not given by keyword: myfunction ( b = 5 ) # use a=2

21 Personal data: George, 53, president (US) Personal data: Tony, 53, prime minister (GB) Personal data: Ronald, 92, president (US) name can be used as keyword as well, even though it doesn’t have a default value Some of the arguments have default values The arguments are given new values except age which uses the default. Values need not be entered in order. Sets first argument, uses the defaults for all the others

22 How not to use keyword arguments >>> >>> def test( name, age = 10, town = “Canberra” ):... pass... >>> test( age = 30, “Alice" ) SyntaxError: non-keyword arg after keyword arg >>> >>> test( age = 30 ) Traceback (most recent call last): File " ", line 1, in ? TypeError: test() takes at least 1 non-keyword argument (0 given) Keyword arguments must appear to the right of any other arguments in a function call. Otherwise ambiguity may arise. Is “Alice” the value for name or town ? No value given for name which doesn’t have a default value


Download ppt "Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –"

Similar presentations


Ads by Google