Python: the Project, the Language and the Style

Loading...

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

0 comments

Post a comment

    Post a comment
    Embed Video
    Edit your comment Cancel

    1 Favorite

    Python: the Project, the Language and the Style - Presentation Transcript

    1. Python: the Project, the Language and the Style Juan Manuel Gimeno Illa jmgimeno@diei.udl.cat October 2008 J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 1 / 28
    2. Outline 1 Introduction 2 Python, the project 3 Python, the language References Functions Modules and Packages Namespaces and Scopes 4 Python, the style 5 Hands on Work J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 2 / 28
    3. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    4. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    5. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    6. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    7. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    8. Introduction What this session pretends A very light introduction to the making of Python (the project) A presentation of some aspects of Python (the language) We will focus on those elements and concepts that are most shocking for people coming from C, C++, Java, . . . A basic knowledge of the language is assumed (a casual reading the Python Tutorial is enough) We will begin to get into what me might call the python style of doing things (the style) (In the live session we will also present the interpreter (python), an enhanced interpreter (ipython) and the default integrated development environment (idle) among other things) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 3 / 28
    9. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    10. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    11. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    12. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    13. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    14. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    15. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    16. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    17. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    18. Python, the project Organization Initiated by Guido van Rossum (BDFL: Benevolent Dictator For Life) in 1990 and made public in 1991 By the years, a process and an infrastructure for the development of Python have emerged: SourceForge: patches, bugs, etc. Mailing lists: python-dev, python-list Newsgroup: comp.lang.python PEPs: Python Enhancement Proposals SIGs: Special Interest Groups PSF: Python Software Foundation holds the copyright of Python since version 2.1 All of this is accessible from http://python.org Its a very open project provided you follow some rules!! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 4 / 28
    19. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    20. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    21. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    22. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    23. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    24. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    25. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    26. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    27. Python, the project Implementations The language Python has different implementations CPython: Standard implementation of the python language in C. Currently at version 2.6 of the language Jython: Java implementation that compiles python code to JVM byte-code Currently at version 2.2.1 of the language (alpha version 2.5a3) IronPython: .NET implementation that compiles python code to CLR Currently at version 2.4 of the language (with minor differences) Stackless: enhanced version using micro-threads, implemented in C Currently at version 2.6 of the language PyPy: Rather experimental version of python written in python Python 3000: (or py3k) non-backwards compatible evolution of CPython We will use CPython versions 2.4 (very little differences) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 5 / 28
    28. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    29. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    30. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    31. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    32. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    33. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    34. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    35. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    36. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    37. Python, the language References Variables and References A Python program access data values through references A reference is a name that refers to the location in memory of a value (object) (Python classes, functions and methods are also objects) References takes the form of variables (x), attributes (x.y) and items (x[y]) A reference has no intrinsic type but gets the type of the referenced object (duck typing) The process of linking a reference to a value is called binding References can be rebound to another object Statements that create/modify bindings are assignment, def, class and import The del statement unbinds the reference (does not deletes the object) Bindings live in name-spaces (more on this later) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 6 / 28
    38. Python, the language References Binding, Rebinding and Unbinding >>> l = [] >>> id(l) -1210453844 l gets bound though assignment to a list (id returns the identity of an object) l maintains its identity through method application But gets rebound with assignment In this case, augmented assignment does not rebind del statement unbinds the reference (it does not delete objects!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 7 / 28
    39. Python, the language References Binding, Rebinding and Unbinding >>> l = [] >>> id(l) -1210453844 >>> l.append(1) l gets bound though assignment to a list >>> id(l) (id returns the identity of an object) -1210453844 l maintains its identity through method application But gets rebound with assignment In this case, augmented assignment does not rebind del statement unbinds the reference (it does not delete objects!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 7 / 28
    40. Python, the language References Binding, Rebinding and Unbinding >>> l = [] >>> id(l) -1210453844 >>> l.append(1) l gets bound though assignment to a list >>> id(l) (id returns the identity of an object) -1210453844 l maintains its identity through method >>> l = l + [2] application >>> id(l) But gets rebound with assignment -1210467412 In this case, augmented assignment does not rebind del statement unbinds the reference (it does not delete objects!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 7 / 28
    41. Python, the language References Binding, Rebinding and Unbinding >>> l = [] >>> id(l) -1210453844 >>> l.append(1) l gets bound though assignment to a list >>> id(l) (id returns the identity of an object) -1210453844 l maintains its identity through method >>> l = l + [2] application >>> id(l) But gets rebound with assignment -1210467412 In this case, augmented assignment does >>> l += [3] not rebind >>> id(l) del statement unbinds the reference (it -1210467412 does not delete objects!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 7 / 28
    42. Python, the language References Binding, Rebinding and Unbinding >>> l = [] >>> id(l) -1210453844 >>> l.append(1) l gets bound though assignment to a list >>> id(l) (id returns the identity of an object) -1210453844 l maintains its identity through method >>> l = l + [2] application >>> id(l) But gets rebound with assignment -1210467412 In this case, augmented assignment does >>> l += [3] not rebind >>> id(l) del statement unbinds the reference (it -1210467412 does not delete objects!!) >>> del l >>> id(l) Traceback (most recent call last): File ’<stdin>’, line 1, in ? NameError: name ’l’ is not defined J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 7 / 28
    43. Python, the language Functions The def statement def function-name(mandatory, optional=expression): statement(s) Formal parameters can be Mandatory Each call must supply a value for the parameter Optional If the call does not supply a value, the default is used The def statement evaluates the expression and saves a reference to the expression value (the default value of the parameter) among the attributes of the function object J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 8 / 28
    44. Python, the language Functions The def statement def function-name(mandatory, optional=expression): statement(s) Formal parameters can be Mandatory Each call must supply a value for the parameter Optional If the call does not supply a value, the default is used The def statement evaluates the expression and saves a reference to the expression value (the default value of the parameter) among the attributes of the function object J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 8 / 28
    45. Python, the language Functions The def statement def function-name(mandatory, optional=expression): statement(s) Formal parameters can be Mandatory Each call must supply a value for the parameter Optional If the call does not supply a value, the default is used The def statement evaluates the expression and saves a reference to the expression value (the default value of the parameter) among the attributes of the function object J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 8 / 28
    46. Python, the language Functions The def statement def function-name(mandatory, optional=expression): statement(s) Formal parameters can be Mandatory Each call must supply a value for the parameter Optional If the call does not supply a value, the default is used The def statement evaluates the expression and saves a reference to the expression value (the default value of the parameter) among the attributes of the function object J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 8 / 28
    47. Python, the language Functions The def statement def function-name(mandatory, optional=expression): statement(s) Formal parameters can be Mandatory Each call must supply a value for the parameter Optional If the call does not supply a value, the default is used The def statement evaluates the expression and saves a reference to the expression value (the default value of the parameter) among the attributes of the function object J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 8 / 28
    48. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    49. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    50. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    51. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    52. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    53. Python, the language Functions Evaluation of the defaults The default expression is not evaluated when the function gets called. >>> def f(x, y=None): >>> def f(x, y=[]): ... if y is None: y = [] ... y.append(x) ... y.append(x) ... return y ... return y ... ... >>> print f(23) >>> print f(23) [23] [23] >>> print f(42) >>> print f(42) [23, 42] [42] The y=None idiom is the standard way to deal with mutable defaults. Problem: Do you find another solution in this case? J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 9 / 28
    54. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    55. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    56. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    57. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    58. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) 1 2 () J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    59. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) 1 2 () >>> spam(b=1, a=2) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    60. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) 1 2 () >>> spam(b=1, a=2) 2 1 () J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    61. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) 1 2 () >>> spam(b=1, a=2) 2 1 () >>> spam(1, 2, 3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    62. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): ... print a, b, args >>> spam(1, 2) 1 2 () >>> spam(b=1, a=2) 2 1 () >>> spam(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    63. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) 1 2 () >>> spam(b=1, a=2) 2 1 () >>> spam(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    64. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) >>> eggs(1, 2, 3, 4, 5) 1 2 () >>> spam(b=1, a=2) 2 1 () >>> spam(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    65. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) >>> eggs(1, 2, 3, 4, 5) 1 2 () 1 (2, 3, 4, 5) () >>> spam(b=1, a=2) 2 1 () >>> spam(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    66. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) >>> eggs(1, 2, 3, 4, 5) 1 2 () 1 (2, 3, 4, 5) () >>> spam(b=1, a=2) >>> def ham(a, *args): 2 1 () ... spam(a, *args) >>> spam(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    67. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) >>> eggs(1, 2, 3, 4, 5) 1 2 () 1 (2, 3, 4, 5) () >>> spam(b=1, a=2) >>> def ham(a, *args): 2 1 () ... spam(a, *args) >>> spam(1, 2, 3, 4, 5) >>> ham(1, 2, 3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    68. Python, the language Functions Extra Positional Arguments At the end of the arguments list you may optionally add the special form *args This binds args to a tuple containing the extra values passed in the function call >>> def spam(a, b, *args): >>> def eggs(a, *args): ... print a, b, args ... spam(a, args) >>> spam(1, 2) >>> eggs(1, 2, 3, 4, 5) 1 2 () 1 (2, 3, 4, 5) () >>> spam(b=1, a=2) >>> def ham(a, *args): 2 1 () ... spam(a, *args) >>> spam(1, 2, 3, 4, 5) >>> ham(1, 2, 3, 4, 5) 1 2 (3, 4, 5) 1 2 (3, 4, 5) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 10 / 28
    69. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    70. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    71. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    72. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    73. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    74. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    75. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    76. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    77. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    78. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): ... print a, b, kw >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    79. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    80. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) >>> ham(1, b=2, c=3) 1 2 {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    81. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) >>> ham(1, b=2, c=3) 1 2 {} 1 {’c’: 3, ’b’: 2} {} >>> spam(b=1, a=2, c=3, d=4) 2 1 {’c’: 3, ’d’: 4} >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    82. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) >>> ham(1, b=2, c=3) 1 2 {} 1 {’c’: 3, ’b’: 2} {} >>> spam(b=1, a=2, c=3, d=4) >>> def pram(a,**kw): 2 1 {’c’: 3, ’d’: 4} ... spam(a, **kw) >>> def eggs(a, *args, **kw): ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    83. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) >>> ham(1, b=2, c=3) 1 2 {} 1 {’c’: 3, ’b’: 2} {} >>> spam(b=1, a=2, c=3, d=4) >>> def pram(a,**kw): 2 1 {’c’: 3, ’d’: 4} ... spam(a, **kw) >>> def eggs(a, *args, **kw): >>> pram(1, b=2, c=3) ... print a, args, kw >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    84. Python, the language Functions Extra Named Arguments At the end of the arguments list you may optionally add the special from **kwargs This binds kwargs to a dictionary containing the extra values passed in the function call and their names >>> def spam(a, b, **kw): >>> def ham(a,**kw): ... print a, b, kw ... spam(a, kw) >>> spam(1, 2) >>> ham(1, b=2, c=3) 1 2 {} 1 {’c’: 3, ’b’: 2} {} >>> spam(b=1, a=2, c=3, d=4) >>> def pram(a,**kw): 2 1 {’c’: 3, ’d’: 4} ... spam(a, **kw) >>> def eggs(a, *args, **kw): >>> pram(1, b=2, c=3) ... print a, args, kw 1 2 {’c’: 3} >>> eggs(1,2,3,4) 1 (2, 3, 4) {} J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 11 / 28
    85. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    86. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    87. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    88. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    89. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    90. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    91. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    92. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    93. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    94. Python, the language Modules and Packages Modules A typical Python program is made up of several source files Each source file corresponds to a module that groups variables, functions, classes, etc. for reuse A module explicitly establishes its dependencies using the import and from statements In some languages global variables provide a hidden mechanism for coupling between modules In Python global variables are not global to all modules: they are attributes of a module object (module.variable) Extensions, components coded in other languages such as C, C++, Java, C#, are treated as modules by the python code In Python everything is defined in a module: main program or interactive sessions in module main built-ins in preloaded module builtin accessible via import builtin at loading, modules get an extra attribute named builtins which refers to either to module builtin or to its dictionary J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 12 / 28
    95. Python, the language Modules and Packages import modulename spam.py #!/usr/bin/env python # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    96. Python, the language Modules and Packages import modulename >>> import spam spam.py #!/usr/bin/env python # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    97. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    98. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    99. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    100. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    101. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    102. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    103. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    104. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    105. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): spam !!! \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    106. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): spam !!! \"\"\"spam documentation\"\"\" >>> dir() print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    107. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): spam !!! \"\"\"spam documentation\"\"\" >>> dir() print \"spam !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’ham’, ’spam’] if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    108. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): spam !!! \"\"\"spam documentation\"\"\" >>> dir() print \"spam !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’ham’, ’spam’] if __name__ == \"__main__\": >>> dir(ham) eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    109. Python, the language Modules and Packages import modulename >>> import spam spam.py >>> spam #!/usr/bin/env python <module ’spam’ from ’spam.pyc’> # -*- coding: latin-1 -*- >>> eggs() \"\"\"Documentation of the Traceback (most recent call last): spam module.\"\"\" File ’<stdin>’, line 1, in ? NameError: name ’eggs’ is not defined def eggs(): >>> spam.eggs() \"\"\"eggs documentation\"\"\" eggs !!! print \"eggs !!!\" >>> ham=spam >>> ham.spam() def spam(s): spam !!! \"\"\"spam documentation\"\"\" >>> dir() print \"spam !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’ham’, ’spam’] if __name__ == \"__main__\": >>> dir(ham) eggs() [’__builtins__’, ’__doc__’, ’__file__’, ’__name__’, ’eggs’, ’spam’] J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 13 / 28
    110. Python, the language Modules and Packages from module import name1, name2, . . . spam.py #!/usr/bin/env python # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    111. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    112. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- \"\"\"Documentation of the spam module.\"\"\" def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    113. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    114. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    115. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    116. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    117. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    118. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): >>> eggs.__module__ \"\"\"spam documentation\"\"\" print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    119. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): >>> eggs.__module__ \"\"\"spam documentation\"\"\" ’spam’ print \"spam !!!\" if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    120. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): >>> eggs.__module__ \"\"\"spam documentation\"\"\" ’spam’ print \"spam !!!\" >>> import sys if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    121. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): >>> eggs.__module__ \"\"\"spam documentation\"\"\" ’spam’ print \"spam !!!\" >>> import sys >>> dir(sys.modules[’spam’]) if __name__ == \"__main__\": eggs() J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    122. Python, the language Modules and Packages from module import name1, name2, . . . spam.py >>> from spam import eggs #!/usr/bin/env python >>> spam # -*- coding: latin-1 -*- Traceback (most recent call last): \"\"\"Documentation of the File ’<stdin>’, line 1, in ? spam module.\"\"\" NameError: name ’spam’ is not defined >>> eggs() def eggs(): eggs !!! \"\"\"eggs documentation\"\"\" >>> dir() print \"eggs !!!\" [’__builtins__’, ’__doc__’, ’__name__’, ’eggs’] def spam(s): >>> eggs.__module__ \"\"\"spam documentation\"\"\" ’spam’ print \"spam !!!\" >>> import sys >>> dir(sys.modules[’spam’]) if __name__ == \"__main__\": [’__builtins__’, ’__doc__’, ’__file__’, eggs() ’__name__’, ’eggs’, ’spam’] J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 14 / 28
    123. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    124. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    125. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    126. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    127. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    128. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    129. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    130. Python, the language Modules and Packages More about import import module with problematic name as i love it from module import something i dont like as i like it the name is loooooooooooooooong the name conflicts with something in this module from spam import * all “non private” attributes of module are bound as global variables in the importing module dangerous!!!!! because muy have unforeseen consequences attribute all in imported module can restrict the imported names J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 15 / 28
    131. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    132. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    133. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    134. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    135. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    136. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    137. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    138. Python, the language Modules and Packages How Modules are Loaded Module importing is processed by the built-in function import First checks if already loaded (using dictionary sys.modules) If not, binds sys.modules[M] to an empty module object with name M Then looks for the right way to initialize (load) the module If module is a built-in (listed in sys.builtin module names) it calls its initialization function If not, the module has to be searched in the filesystem Variable sys.path contains the list of paths to be searched Its value is initialized with the contents of environment variable PYTHONPATH J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 16 / 28
    139. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    140. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    141. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    142. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    143. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    144. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    145. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    146. Python, the language Modules and Packages The reload Function As we have seen, python only loads a module the first time you import it This may be inconvenient when developing interactivedly because you need to be sure that you are executing the last version of the code To reload a module pass the module object (not its name) to the buil-in fuction reload reload(M) ensures the new version of M is used by clients that rely on import M and accesses attributes with the syntax M.A reload(M) has no effect on other existing references bound to previous values of M’s attributes. E.g: those imported with a from statement ( class attributte of previously created objects) reload is not recursive: when you reload module M, modules imported by M are not reloaded J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 17 / 28
    147. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    148. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    149. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    150. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    151. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    152. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    153. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    154. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    155. Python, the language Modules and Packages Packages A package is a module that contains other modules Some or all the modules in a package can be subpackages, resulting in an hierarchical structure A package named P resides in a subdirectory, also called P, of some directory in sys.path (Modern python allows package living in ZIP files but the mechanics is the same) The body of P is in the file P/ init .py You need this file in order to indicate that the subdirectory is a package (can be empty) this body is executed the first time you import it (of any of its submodules) files in subdirectory P are the modules in package P subdirectories of P which have a file named init .py are subpackages of P J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 18 / 28
    156. Python, the language Modules and Packages Importing Package Components import P imports package P executes P/ init .py binds variable P to the package object import P.M imports module M of package P executes P/ init .py executes P/M.py or P/M/ init .py or . . . binds variable P to the module (package) object binds attribute M of variable P to the module object import S.P.A.M to any depth from P import M as R . . . P init .py can define variable all to tune the behaviour of from P import * J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 19 / 28
    157. Python, the language Modules and Packages Importing Package Components import P imports package P executes P/ init .py binds variable P to the package object import P.M imports module M of package P executes P/ init .py executes P/M.py or P/M/ init .py or . . . binds variable P to the module (package) object binds attribute M of variable P to the module object import S.P.A.M to any depth from P import M as R . . . P init .py can define variable all to tune the behaviour of from P import * J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 19 / 28
    158. Python, the language Modules and Packages Importing Package Components import P imports package P executes P/ init .py binds variable P to the package object import P.M imports module M of package P executes P/ init .py executes P/M.py or P/M/ init .py or . . . binds variable P to the module (package) object binds attribute M of variable P to the module object import S.P.A.M to any depth from P import M as R . . . P init .py can define variable all to tune the behaviour of from P import * J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 19 / 28
    159. Python, the language Modules and Packages Importing Package Components import P imports package P executes P/ init .py binds variable P to the package object import P.M imports module M of package P executes P/ init .py executes P/M.py or P/M/ init .py or . . . binds variable P to the module (package) object binds attribute M of variable P to the module object import S.P.A.M to any depth from P import M as R . . . P init .py can define variable all to tune the behaviour of from P import * J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 19 / 28
    160. Python, the language Modules and Packages Importing Package Components import P imports package P executes P/ init .py binds variable P to the package object import P.M imports module M of package P executes P/ init .py executes P/M.py or P/M/ init .py or . . . binds variable P to the module (package) object binds attribute M of variable P to the module object import S.P.A.M to any depth from P import M as R . . . P init .py can define variable all to tune the behaviour of from P import * J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 19 / 28
    161. Python, the language Namespaces and Scopes Local and Global Namespaces (of a function) A function’s parameters, plus any variables bound (by assignment, def, . . . ) in the function body make the local namespace (a.k.a. local scope) Each of these variables is known as a local variable of the function. Variables that are not local (in the absence of nested functions) are known as global variables Global variables are attributes of the module object in which the function is defined Local variables can hide global ones with the same name J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 20 / 28
    162. Python, the language Namespaces and Scopes Local and Global Namespaces (of a function) A function’s parameters, plus any variables bound (by assignment, def, . . . ) in the function body make the local namespace (a.k.a. local scope) Each of these variables is known as a local variable of the function. Variables that are not local (in the absence of nested functions) are known as global variables Global variables are attributes of the module object in which the function is defined Local variables can hide global ones with the same name J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 20 / 28
    163. Python, the language Namespaces and Scopes Local and Global Namespaces (of a function) A function’s parameters, plus any variables bound (by assignment, def, . . . ) in the function body make the local namespace (a.k.a. local scope) Each of these variables is known as a local variable of the function. Variables that are not local (in the absence of nested functions) are known as global variables Global variables are attributes of the module object in which the function is defined Local variables can hide global ones with the same name J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 20 / 28
    164. Python, the language Namespaces and Scopes Local and Global Namespaces (of a function) A function’s parameters, plus any variables bound (by assignment, def, . . . ) in the function body make the local namespace (a.k.a. local scope) Each of these variables is known as a local variable of the function. Variables that are not local (in the absence of nested functions) are known as global variables Global variables are attributes of the module object in which the function is defined Local variables can hide global ones with the same name J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 20 / 28
    165. Python, the language Namespaces and Scopes Local and Global Namespaces (of a function) A function’s parameters, plus any variables bound (by assignment, def, . . . ) in the function body make the local namespace (a.k.a. local scope) Each of these variables is known as a local variable of the function. Variables that are not local (in the absence of nested functions) are known as global variables Global variables are attributes of the module object in which the function is defined Local variables can hide global ones with the same name J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 20 / 28
    166. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    167. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global _count = 0 namespace def counter(): Don’t use global if the function body just uses _count += 1 the variable (including mutating the object return _count referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    168. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global _count = 0 namespace def counter(): Don’t use global if the function body just uses _count += 1 the variable (including mutating the object return _count referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    169. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that _count = 0 we want count bindings be done in the global def counter(): namespace global _count Don’t use global if the function body just uses _count += 1 the variable (including mutating the object return _count referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    170. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global _accum = [] namespace def counter(n): Don’t use global if the function body just uses _accum.append(n) the variable (including mutating the object return _accum referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    171. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    172. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    173. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    174. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    175. Python, the language Namespaces and Scopes The global statement By default, any variable that is bound within a function body is a local variable of the function Its an error because variable count does not have a binding in local namespace when += is executed The global declaration allows us to signal that we want count bindings be done in the global namespace Don’t use global if the function body just uses the variable (including mutating the object referred) As a matter of style: don’t use global unless it is strictly necessary better use classe to group state and behaviour put it in the first line of the function don’t use it to create new bindings, only for rebinding J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 21 / 28
    176. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    177. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    178. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    179. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. Without nested scopes def percent1(a, b, c): def pc(x, total=a+b+c): return (x*100.0)/total print \"Percentages are:\", pc(a), pc(b), pc(c) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    180. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. With nested scopes def percent2(a, b, c): def pc(x): return (x*100.0)/(a+b+c) print \"Percentages are:\", pc(a), pc(b), pc(c) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    181. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    182. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. Creating a closure def make_adder(augend): def add(addend): return addend + augend return add J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    183. Python, the language Namespaces and Scopes Nested Functions and Nested Scopes A def statement within a function body defines a nested function The function whose body includes the def is known as an outer function to the nested one Code in a nested funcion’s body may access but not rebind local variables of an outer function (free variables of the nested function) A nested function that accesses values from outer local variables is also known as a closure. closures are an exception to the general rule that OO is the best way to bundle together data and code when you need to construct callable objects with some parameters fixed at construction time, closures may be simpler than classes the outer function that returns the closure is a factory of a family of functions distinguished by some parameters J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 22 / 28
    184. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    185. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    186. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    187. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    188. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    189. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    190. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    191. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    192. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    193. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    194. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    195. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    196. Python, the language Namespaces and Scopes The LEGB Rule This is the rule since version 2.2 (PEP-227) The namespaces in which python searches for the binding of a reference are: 1 First, the Local namespace 2 Next, the Enclosing namespaces (the immediate outer function etc.) 3 Then, the Global namespace 4 Finally, the Built-ins namespace is considered Rebinding references is possible in local namespace global namespace (using global statement) built-in namespace (explicitedly importing builtin module) So no rebinding at enclosing namespace (but some tricks do the work !!!) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 23 / 28
    197. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    198. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    199. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    200. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    201. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    202. Python, the style Python Culture Python culture influences both the project and the language Each software project has its own culture, its own way of doing things Each programming language has its style, its own approach to solving problems Python (language) tries to keep things simple, to be orthogonal and to assist the programmer as much as possible Python (project) emphasizes the motto “Correctness and clarity before speed” Part of this culture is written in some meta-PEPs (the one which mostly interests us is PEP-8) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 24 / 28
    203. Python, the style The Zen of Python (Tim Peters 1999) Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one– and preferably only one –obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea – let’s do more of those! J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 25 / 28
    204. Hands on Work And Now for Something Completely Different 1 Read (and understand !!!) the scripts: cvs2dnis and unmail cvs2dni Used to build the components of the mailing from RedCampus data (pre-sakai days) unmail Used to process a mailbox containing the practices delivered by the students. Extracts each mail in a different directory Extracts the mail text in a file Extracts the practice (a compressed file) Tries to build it using make Detects copies, grades the assignment, makes coffee, . . . (just kidding !!!) shutil.py This is a module of the stdlib that defines very simple functions 2 Solve awk assignments in python. 3 Redefine reload to not only accept a module object but its name (Hint: use a non-public variable to save the old value of builtin .reload) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 26 / 28
    205. Bibliography Bibliography Guido Van Rossum, Python Tutorial (2.5 version) Guido Van Rossum, Python Library Reference (2.5 version) Session Python Modules of the Python411 podcast Python Learning Foundation (I don’t like this podcast very much but this session is above the mean) J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 27 / 28
    206. License License Aquesta obra est` subjecta a una llic`ncia Reconeixement-Compartir amb a e la mateixa llic`ncia 2.5 Espanya de Creative Commons. e Per veure’n una c`pia, visiteu o http://creativecommons.org/licenses/by-sa/2.5/es/ o envieu una carta a Creative Commons 559 Nathan Abbott Way Stanford California 94305 USA J.M.Gimeno (jmgimeno@diei.udl.cat) Python: the Project, ... October 2008 28 / 28

    + Juan-Manuel GimenoJuan-Manuel Gimeno, 5 months ago

    custom

    361 views, 1 favs, 1 embeds more stats

    An introduction to the python language and its orga more

    More info about this document

    CC Attribution-ShareAlike LicenseCC Attribution-ShareAlike License

    Go to text version

    • Total Views 361
      • 360 on SlideShare
      • 1 from embeds
    • Comments 0
    • Favorites 1
    • Downloads 0
    Most viewed embeds
    • 1 views on http://python.rk.edu.pl

    more

    All embeds
    • 1 views on http://python.rk.edu.pl

    less

    Flagged as inappropriate Flag as inappropriate
    Flag as inappropriate

    Select your reason for flagging this presentation as inappropriate. If needed, use the feedback form to let us know more details.

    Cancel
    File a copyright complaint
    Having problems? Go to our helpdesk?

    Categories