python: the project, the language and the style
DESCRIPTION
An introduction to the python language and its organization as an open-source project.TRANSCRIPT
Python: the Project, the Language and the Style
Juan Manuel Gimeno Illa
October 2008
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 1 / 28
Outline
1 Introduction
2 Python, the project
3 Python, the languageReferencesFunctionsModules and PackagesNamespaces and Scopes
4 Python, the style
5 Hands on Work
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 2 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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)I We will focus on those elements and concepts that are most shocking
for people coming from C, C++, Java, . . .I 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 ofdoing things (the style)
(In the live session we will also present the interpreter (python), anenhanced interpreter (ipython) and the default integrateddevelopment environment (idle) among other things)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 3 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
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 ofPython have emerged:
SourceForge: patches, bugs, etc.Mailing lists: python-dev, python-listNewsgroup: comp.lang.python
PEPs: Python Enhancement ProposalsSIGs: Special Interest GroupsPSF: 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 ([email protected]) Python: the Project, ... October 2008 4 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 28
Python, the project
ImplementationsThe 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 JVMbyte-codeCurrently at version 2.2.1 of the language (alpha version2.5a3)
IronPython: .NET implementation that compiles python code to CLRCurrently at version 2.4 of the language (with minordifferences)
Stackless: enhanced version using micro-threads, implemented in CCurrently 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 ([email protected]) Python: the Project, ... October 2008 5 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 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 referencedobject (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, classand import
The del statement unbinds the reference (does not deletes theobject)
Bindings live in name-spaces (more on this later)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 6 / 28
Python, the language References
Binding, Rebinding and Unbinding
l gets bound though assignment to a list(id returns the identity of an object)l maintains its identity through methodapplicationBut gets rebound with assignmentIn this case, augmented assignment doesnot rebinddel statement unbinds the reference (itdoes not delete objects!!)
>>> l = []>>> id(l)-1210453844
>>> l.append(1)>>> id(l)-1210453844>>> l = l + [2]>>> id(l)-1210467412>>> l += [3]>>> id(l)-1210467412>>> del l>>> id(l)Traceback (most recent call last):File ’<stdin>’, line 1, in ?NameError: name ’l’ is not defined
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 7 / 28
Python, the language References
Binding, Rebinding and Unbinding
l gets bound though assignment to a list(id returns the identity of an object)l maintains its identity through methodapplicationBut gets rebound with assignmentIn this case, augmented assignment doesnot rebinddel statement unbinds the reference (itdoes not delete objects!!)
>>> l = []>>> id(l)-1210453844>>> l.append(1)>>> id(l)-1210453844
>>> l = l + [2]>>> id(l)-1210467412>>> l += [3]>>> id(l)-1210467412>>> del l>>> id(l)Traceback (most recent call last):File ’<stdin>’, line 1, in ?NameError: name ’l’ is not defined
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 7 / 28
Python, the language References
Binding, Rebinding and Unbinding
l gets bound though assignment to a list(id returns the identity of an object)l maintains its identity through methodapplicationBut gets rebound with assignmentIn this case, augmented assignment doesnot rebinddel statement unbinds the reference (itdoes not delete objects!!)
>>> l = []>>> id(l)-1210453844>>> l.append(1)>>> id(l)-1210453844>>> l = l + [2]>>> id(l)-1210467412
>>> l += [3]>>> id(l)-1210467412>>> del l>>> id(l)Traceback (most recent call last):File ’<stdin>’, line 1, in ?NameError: name ’l’ is not defined
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 7 / 28
Python, the language References
Binding, Rebinding and Unbinding
l gets bound though assignment to a list(id returns the identity of an object)l maintains its identity through methodapplicationBut gets rebound with assignmentIn this case, augmented assignment doesnot rebinddel statement unbinds the reference (itdoes not delete objects!!)
>>> l = []>>> id(l)-1210453844>>> l.append(1)>>> id(l)-1210453844>>> l = l + [2]>>> id(l)-1210467412>>> l += [3]>>> id(l)-1210467412
>>> del l>>> id(l)Traceback (most recent call last):File ’<stdin>’, line 1, in ?NameError: name ’l’ is not defined
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 7 / 28
Python, the language References
Binding, Rebinding and Unbinding
l gets bound though assignment to a list(id returns the identity of an object)l maintains its identity through methodapplicationBut gets rebound with assignmentIn this case, augmented assignment doesnot rebinddel statement unbinds the reference (itdoes not delete objects!!)
>>> l = []>>> id(l)-1210453844>>> l.append(1)>>> id(l)-1210453844>>> l = l + [2]>>> id(l)-1210467412>>> l += [3]>>> id(l)-1210467412>>> del l>>> id(l)Traceback (most recent call last):File ’<stdin>’, line 1, in ?NameError: name ’l’ is not defined
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 7 / 28
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 parameterOptional If the call does not supply a value, the default is used
The def statement evaluates the expression and saves a reference tothe expression value (the default value of the parameter) among theattributes of the function object
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 8 / 28
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 parameterOptional If the call does not supply a value, the default is used
The def statement evaluates the expression and saves a reference tothe expression value (the default value of the parameter) among theattributes of the function object
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 8 / 28
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 parameterOptional If the call does not supply a value, the default is used
The def statement evaluates the expression and saves a reference tothe expression value (the default value of the parameter) among theattributes of the function object
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 8 / 28
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 parameterOptional If the call does not supply a value, the default is used
The def statement evaluates the expression and saves a reference tothe expression value (the default value of the parameter) among theattributes of the function object
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 8 / 28
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 parameterOptional If the call does not supply a value, the default is used
The def statement evaluates the expression and saves a reference tothe expression value (the default value of the parameter) among theattributes of the function object
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 8 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Evaluation of the defaults
The default expression is not evaluated when the function gets called.
>>> def f(x, y=[]):... y.append(x)... return y...>>> print f(23)[23]>>> print f(42)[23, 42]
>>> def f(x, y=None):... if y is None: y = []... y.append(x)... return y...>>> print f(23)[23]>>> print f(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 ([email protected]) Python: the Project, ... October 2008 9 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)
>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)
1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()
>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)
>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)
1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Positional Arguments
At the end of the arguments list you may optionally add the specialform *args
This binds args to a tuple containing the extra values passed in thefunction 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)
>>> def eggs(a, *args):... spam(a, args)>>> eggs(1, 2, 3, 4, 5)1 (2, 3, 4, 5) ()>>> def ham(a, *args):... spam(a, *args)>>> ham(1, 2, 3, 4, 5)1 2 (3, 4, 5)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 10 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)
>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)
1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}
>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)
>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)
1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
Python, the language Functions
Extra Named Arguments
At the end of the arguments list you may optionally add the specialfrom **kwargs
This binds kwargs to a dictionary containing the extra values passedin 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) {}
>>> def ham(a,**kw):... spam(a, kw)>>> ham(1, b=2, c=3)1 {’c’: 3, ’b’: 2} {}>>> def pram(a,**kw):... spam(a, **kw)>>> pram(1, b=2, c=3)1 2 {’c’: 3}
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 11 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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 reuseA module explicitly establishes its dependencies using the import andfrom statements
I In some languages global variables provide a hidden mechanism forcoupling between modules
I In Python global variables are not global to all modules: they areattributes 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 codeIn Python everything is defined in a module:
I main program or interactive sessions in module mainI built-ins in preloaded module builtin accessible via import
builtinI at loading, modules get an extra attribute named builtins which
refers to either to module builtin or to its dictionary
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 12 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> import spam
>>> spam
<module ’spam’ from ’spam.pyc’>
>>> eggs()
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’eggs’ is not defined
>>> spam.eggs()
eggs !!!
>>> ham=spam
>>> ham.spam()
spam !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’ham’, ’spam’]
>>> dir(ham)
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 13 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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()
>>> from spam import eggs
>>> spam
Traceback (most recent call last):
File ’<stdin>’, line 1, in ?
NameError: name ’spam’ is not defined
>>> eggs()
eggs !!!
>>> dir()
[’__builtins__’, ’__doc__’, ’__name__’,
’eggs’]
>>> eggs.__module__
’spam’
>>> import sys
>>> dir(sys.modules[’spam’])
[’__builtins__’, ’__doc__’, ’__file__’,
’__name__’, ’eggs’, ’spam’]
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 14 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 itI the name is loooooooooooooooongI the name conflicts with something in this module
from spam import *I all “non private” attributes of module are bound as global variables in
the importing moduleI dangerous!!!!! because muy have unforeseen consequencesI attribute all in imported module can restrict the imported names
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 15 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
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 withname M
Then looks for the right way to initialize (load) the moduleI If module is a built-in (listed in sys.builtin module names) it calls
its initialization functionI If not, the module has to be searched in the filesystem
F Variable sys.path contains the list of paths to be searchedF Its value is initialized with the contents of environment variable
PYTHONPATH
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 16 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
Python, the language Modules and Packages
The reload Function
As we have seen, python only loads a module the first time youimport it
This may be inconvenient when developing interactivedly because youneed 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 thebuil-in fuction reload
reload(M) ensures the new version of M is used by clients that relyon import M and accesses attributes with the syntax M.A
reload(M) has no effect on other existing references bound toprevious values of M’s attributes. E.g:
I those imported with a from statementI ( class attributte of previously created objects)
reload is not recursive: when you reload module M, modulesimported by M are not reloaded
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 17 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
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, resultingin an hierarchical structure
A package named P resides in a subdirectory, also called P, of somedirectory in sys.path
(Modern python allows package living in ZIP files but the mechanicsis 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 apackage (can be empty)
I this body is executed the first time you import it (of any of itssubmodules)
I files in subdirectory P are the modules in package PI subdirectories of P which have a file named init .py are
subpackages of P
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 18 / 28
Python, the language Modules and Packages
Importing Package Components
import PI imports package PI executes P/ init .pyI binds variable P to the package object
import P.MI imports module M of package PI executes P/ init .pyI executes P/M.py or P/M/ init .py or . . .I binds variable P to the module (package) objectI 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 offrom P import *
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 19 / 28
Python, the language Modules and Packages
Importing Package Components
import PI imports package PI executes P/ init .pyI binds variable P to the package object
import P.MI imports module M of package PI executes P/ init .pyI executes P/M.py or P/M/ init .py or . . .I binds variable P to the module (package) objectI 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 offrom P import *
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 19 / 28
Python, the language Modules and Packages
Importing Package Components
import PI imports package PI executes P/ init .pyI binds variable P to the package object
import P.MI imports module M of package PI executes P/ init .pyI executes P/M.py or P/M/ init .py or . . .I binds variable P to the module (package) objectI 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 offrom P import *
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 19 / 28
Python, the language Modules and Packages
Importing Package Components
import PI imports package PI executes P/ init .pyI binds variable P to the package object
import P.MI imports module M of package PI executes P/ init .pyI executes P/M.py or P/M/ init .py or . . .I binds variable P to the module (package) objectI 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 offrom P import *
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 19 / 28
Python, the language Modules and Packages
Importing Package Components
import PI imports package PI executes P/ init .pyI binds variable P to the package object
import P.MI imports module M of package PI executes P/ init .pyI executes P/M.py or P/M/ init .py or . . .I binds variable P to the module (package) objectI 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 offrom P import *
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 19 / 28
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. localscope)
Each of these variables is known as a local variable of the function.
Variables that are not local (in the absence of nested functions) areknown as global variables
Global variables are attributes of the module object in which thefunction is defined
Local variables can hide global ones with the same name
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 20 / 28
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. localscope)
Each of these variables is known as a local variable of the function.
Variables that are not local (in the absence of nested functions) areknown as global variables
Global variables are attributes of the module object in which thefunction is defined
Local variables can hide global ones with the same name
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 20 / 28
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. localscope)
Each of these variables is known as a local variable of the function.
Variables that are not local (in the absence of nested functions) areknown as global variables
Global variables are attributes of the module object in which thefunction is defined
Local variables can hide global ones with the same name
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 20 / 28
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. localscope)
Each of these variables is known as a local variable of the function.
Variables that are not local (in the absence of nested functions) areknown as global variables
Global variables are attributes of the module object in which thefunction is defined
Local variables can hide global ones with the same name
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 20 / 28
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. localscope)
Each of these variables is known as a local variable of the function.
Variables that are not local (in the absence of nested functions) areknown as global variables
Global variables are attributes of the module object in which thefunction is defined
Local variables can hide global ones with the same name
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 20 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
_count = 0def counter():
_count += 1return _count
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
_count = 0def counter():
_count += 1return _count
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
_count = 0def counter():
global _count_count += 1return _count
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
_accum = []def counter(n):
_accum.append(n)return _accum
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
Python, the language Namespaces and Scopes
The global statement
By default, any variable that is bound within afunction body is a local variable of the functionIts an error because variable count does nothave a binding in local namespace when += isexecutedThe global declaration allows us to signal thatwe want count bindings be done in the globalnamespaceDon’t use global if the function body just usesthe variable (including mutating the objectreferred)As a matter of style:
I don’t use global unless it is strictly necessaryI better use classe to group state and behaviourI put it in the first line of the functionI don’t use it to create new bindings, only for
rebinding
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 21 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
Without nested scopes
def percent1(a, b, c):def pc(x, total=a+b+c):
return (x*100.0)/totalprint "Percentages are:", pc(a), pc(b), pc(c)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso 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 ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
Creating a closure
def make_adder(augend):def add(addend):
return addend + augendreturn add
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 outerfunction to the nested one
Code in a nested funcion’s body may access but not rebind localvariables of an outer function (free variables of the nested function)
A nested function that accesses values from outer local variables isalso known as a closure.
I closures are an exception to the general rule that OO is the best way tobundle together data and code
I when you need to construct callable objects with some parameters fixedat construction time, closures may be simpler than classes
I the outer function that returns the closure is a factory of a family offunctions distinguished by some parameters
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 22 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
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 areference are:
1 First, the Local namespace2 Next, the Enclosing namespaces (the immediate outer function etc.)3 Then, the Global namespace4 Finally, the Built-ins namespace is considered
Rebinding references is possible inI local namespaceI global namespace (using global statement)I built-in namespace (explicitedly importing builtin module)
So no rebinding at enclosing namespace(but some tricks do the work !!!)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 23 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
Python, the style
Python Culture
Python culture influences both the project and the languageI Each software project has its own culture, its own way of doing thingsI Each programming language has its style, its own approach to solving
problems
Python (language) tries to keep things simple, to be orthogonal andto assist the programmer as much as possible
Python (project) emphasizes the motto “Correctness and claritybefore speed”
Part of this culture is written in some meta-PEPs (the one whichmostly interests us is PEP-8)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 24 / 28
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 ([email protected]) Python: the Project, ... October 2008 25 / 28
Hands on Work
And Now for Something Completely Different1 Read (and understand !!!) the scripts: cvs2dnis and unmail
cvs2dni Used to build the components of the mailing fromRedCampus data (pre-sakai days)
unmail Used to process a mailbox containing the practicesdelivered by the students.
I Extracts each mail in a different directoryI Extracts the mail text in a fileI Extracts the practice (a compressed file)I Tries to build it using makeI Detects copies, grades the assignment, makes coffee,
. . . (just kidding !!!)
shutil.py This is a module of the stdlib that defines very simplefunctions
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 ofbuiltin .reload)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 26 / 28
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 LearningFoundation(I don’t like this podcast very much but this session is above themean)
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 27 / 28
License
License
Aquesta obra esta subjecta a una llicencia Reconeixement-Compartir ambla mateixa llicencia 2.5 Espanya de Creative Commons.Per veure’n una copia, visiteu
http://creativecommons.org/licenses/by-sa/2.5/es/
o envieu una carta a
Creative Commons559 Nathan Abbott WayStanfordCalifornia 94305USA
J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 28 / 28