Top Banner
Python: the Project, the Language and the Style Juan Manuel Gimeno Illa [email protected] October 2008 J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 1 / 28
206

Python: the Project, the Language and the Style

Sep 03, 2014

Download

Education

An introduction to the python language and its organization as an open-source project.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Python: the Project, the Language and the Style

Python: the Project, the Language and the Style

Juan Manuel Gimeno Illa

[email protected]

October 2008

J.M.Gimeno ([email protected]) Python: the Project, ... October 2008 1 / 28

Page 2: Python: the Project, the Language and the Style

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

Page 3: Python: the Project, the Language and the Style

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

Page 4: Python: the Project, the Language and the Style

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

Page 5: Python: the Project, the Language and the Style

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

Page 6: Python: the Project, the Language and the Style

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

Page 7: Python: the Project, the Language and the Style

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

Page 8: Python: the Project, the Language and the Style

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

Page 9: Python: the Project, the Language and the Style

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

Page 10: Python: the Project, the Language and the Style

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

Page 11: Python: the Project, the Language and the Style

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

Page 12: Python: the Project, the Language and the Style

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

Page 13: Python: the Project, the Language and the Style

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

Page 14: Python: the Project, the Language and the Style

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

Page 15: Python: the Project, the Language and the Style

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

Page 16: Python: the Project, the Language and the Style

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

Page 17: Python: the Project, the Language and the Style

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

Page 18: Python: the Project, the Language and the Style

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

Page 19: Python: the Project, the Language and the Style

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

Page 20: Python: the Project, the Language and the Style

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

Page 21: Python: the Project, the Language and the Style

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

Page 22: Python: the Project, the Language and the Style

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

Page 23: Python: the Project, the Language and the Style

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

Page 24: Python: the Project, the Language and the Style

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

Page 25: Python: the Project, the Language and the Style

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

Page 26: Python: the Project, the Language and the Style

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

Page 27: Python: the Project, the Language and the Style

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

Page 28: Python: the Project, the Language and the Style

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

Page 29: Python: the Project, the Language and the Style

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

Page 30: Python: the Project, the Language and the Style

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

Page 31: Python: the Project, the Language and the Style

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

Page 32: Python: the Project, the Language and the Style

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

Page 33: Python: the Project, the Language and the Style

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

Page 34: Python: the Project, the Language and the Style

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

Page 35: Python: the Project, the Language and the Style

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

Page 36: Python: the Project, the Language and the Style

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

Page 37: Python: the Project, the Language and the Style

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

Page 38: Python: the Project, the Language and the Style

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

Page 39: Python: the Project, the Language and the Style

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

Page 40: Python: the Project, the Language and the Style

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

Page 41: Python: the Project, the Language and the Style

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

Page 42: Python: the Project, the Language and the Style

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

Page 43: Python: the Project, the Language and the Style

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

Page 44: Python: the Project, the Language and the Style

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

Page 45: Python: the Project, the Language and the Style

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

Page 46: Python: the Project, the Language and the Style

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

Page 47: Python: the Project, the Language and the Style

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

Page 48: Python: the Project, the Language and the Style

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

Page 49: Python: the Project, the Language and the Style

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

Page 50: Python: the Project, the Language and the Style

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

Page 51: Python: the Project, the Language and the Style

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

Page 52: Python: the Project, the Language and the Style

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

Page 53: Python: the Project, the Language and the Style

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

Page 54: Python: the Project, the Language and the Style

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

Page 55: Python: the Project, the Language and the Style

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

Page 56: Python: the Project, the Language and the Style

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

Page 57: Python: the Project, the Language and the Style

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

Page 58: Python: the Project, the Language and the Style

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

Page 59: Python: the Project, the Language and the Style

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

Page 60: Python: the Project, the Language and the Style

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

Page 61: Python: the Project, the Language and the Style

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

Page 62: Python: the Project, the Language and the Style

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

Page 63: Python: the Project, the Language and the Style

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

Page 64: Python: the Project, the Language and the Style

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

Page 65: Python: the Project, the Language and the Style

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

Page 66: Python: the Project, the Language and the Style

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

Page 67: Python: the Project, the Language and the Style

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

Page 68: Python: the Project, the Language and the Style

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

Page 69: Python: the Project, the Language and the Style

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

Page 70: Python: the Project, the Language and the Style

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

Page 71: Python: the Project, the Language and the Style

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

Page 72: Python: the Project, the Language and the Style

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

Page 73: Python: the Project, the Language and the Style

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

Page 74: Python: the Project, the Language and the Style

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

Page 75: Python: the Project, the Language and the Style

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

Page 76: Python: the Project, the Language and the Style

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

Page 77: Python: the Project, the Language and the Style

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

Page 78: Python: the Project, the Language and the Style

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

Page 79: Python: the Project, the Language and the Style

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

Page 80: Python: the Project, the Language and the Style

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

Page 81: Python: the Project, the Language and the Style

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

Page 82: Python: the Project, the Language and the Style

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

Page 83: Python: the Project, the Language and the Style

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

Page 84: Python: the Project, the Language and the Style

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

Page 85: Python: the Project, the Language and the Style

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

Page 86: Python: the Project, the Language and the Style

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

Page 87: Python: the Project, the Language and the Style

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

Page 88: Python: the Project, the Language and the Style

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

Page 89: Python: the Project, the Language and the Style

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

Page 90: Python: the Project, the Language and the Style

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

Page 91: Python: the Project, the Language and the Style

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

Page 92: Python: the Project, the Language and the Style

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

Page 93: Python: the Project, the Language and the Style

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

Page 94: Python: the Project, the Language and the Style

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

Page 95: Python: the Project, the Language and the Style

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

Page 96: Python: the Project, the Language and the Style

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

Page 97: Python: the Project, the Language and the Style

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

Page 98: Python: the Project, the Language and the Style

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

Page 99: Python: the Project, the Language and the Style

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

Page 100: Python: the Project, the Language and the Style

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

Page 101: Python: the Project, the Language and the Style

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

Page 102: Python: the Project, the Language and the Style

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

Page 103: Python: the Project, the Language and the Style

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

Page 104: Python: the Project, the Language and the Style

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

Page 105: Python: the Project, the Language and the Style

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

Page 106: Python: the Project, the Language and the Style

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

Page 107: Python: the Project, the Language and the Style

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

Page 108: Python: the Project, the Language and the Style

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

Page 109: Python: the Project, the Language and the Style

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

Page 110: Python: the Project, the Language and the Style

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

Page 111: Python: the Project, the Language and the Style

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

Page 112: Python: the Project, the Language and the Style

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

Page 113: Python: the Project, the Language and the Style

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

Page 114: Python: the Project, the Language and the Style

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

Page 115: Python: the Project, the Language and the Style

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

Page 116: Python: the Project, the Language and the Style

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

Page 117: Python: the Project, the Language and the Style

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

Page 118: Python: the Project, the Language and the Style

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

Page 119: Python: the Project, the Language and the Style

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

Page 120: Python: the Project, the Language and the Style

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

Page 121: Python: the Project, the Language and the Style

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

Page 122: Python: the Project, the Language and the Style

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

Page 123: Python: the Project, the Language and the Style

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

Page 124: Python: the Project, the Language and the Style

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

Page 125: Python: the Project, the Language and the Style

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

Page 126: Python: the Project, the Language and the Style

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

Page 127: Python: the Project, the Language and the Style

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

Page 128: Python: the Project, the Language and the Style

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

Page 129: Python: the Project, the Language and the Style

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

Page 130: Python: the Project, the Language and the Style

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

Page 131: Python: the Project, the Language and the Style

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

Page 132: Python: the Project, the Language and the Style

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

Page 133: Python: the Project, the Language and the Style

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

Page 134: Python: the Project, the Language and the Style

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

Page 135: Python: the Project, the Language and the Style

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

Page 136: Python: the Project, the Language and the Style

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

Page 137: Python: the Project, the Language and the Style

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

Page 138: Python: the Project, the Language and the Style

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

Page 139: Python: the Project, the Language and the Style

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

Page 140: Python: the Project, the Language and the Style

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

Page 141: Python: the Project, the Language and the Style

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

Page 142: Python: the Project, the Language and the Style

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

Page 143: Python: the Project, the Language and the Style

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

Page 144: Python: the Project, the Language and the Style

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

Page 145: Python: the Project, the Language and the Style

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

Page 146: Python: the Project, the Language and the Style

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

Page 147: Python: the Project, the Language and the Style

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

Page 148: Python: the Project, the Language and the Style

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

Page 149: Python: the Project, the Language and the Style

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

Page 150: Python: the Project, the Language and the Style

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

Page 151: Python: the Project, the Language and the Style

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

Page 152: Python: the Project, the Language and the Style

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

Page 153: Python: the Project, the Language and the Style

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

Page 154: Python: the Project, the Language and the Style

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

Page 155: Python: the Project, the Language and the Style

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

Page 156: Python: the Project, the Language and the Style

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

Page 157: Python: the Project, the Language and the Style

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

Page 158: Python: the Project, the Language and the Style

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

Page 159: Python: the Project, the Language and the Style

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

Page 160: Python: the Project, the Language and the Style

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

Page 161: Python: the Project, the Language and the Style

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

Page 162: Python: the Project, the Language and the Style

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

Page 163: Python: the Project, the Language and the Style

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

Page 164: Python: the Project, the Language and the Style

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

Page 165: Python: the Project, the Language and the Style

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

Page 166: Python: the Project, the Language and the Style

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

Page 167: Python: the Project, the Language and the Style

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

Page 168: Python: the Project, the Language and the Style

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

Page 169: Python: the Project, the Language and the Style

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

Page 170: Python: the Project, the Language and the Style

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

Page 171: Python: the Project, the Language and the Style

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

Page 172: Python: the Project, the Language and the Style

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

Page 173: Python: the Project, the Language and the Style

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

Page 174: Python: the Project, the Language and the Style

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

Page 175: Python: the Project, the Language and the Style

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

Page 176: Python: the Project, the Language and the Style

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

Page 177: Python: the Project, the Language and the Style

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

Page 178: Python: the Project, the Language and the Style

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

Page 179: Python: the Project, the Language and the Style

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

Page 180: Python: the Project, the Language and the Style

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

Page 181: Python: the Project, the Language and the Style

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

Page 182: Python: the Project, the Language and the Style

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

Page 183: Python: the Project, the Language and the Style

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

Page 184: Python: the Project, the Language and the Style

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

Page 185: Python: the Project, the Language and the Style

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

Page 186: Python: the Project, the Language and the Style

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

Page 187: Python: the Project, the Language and the Style

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

Page 188: Python: the Project, the Language and the Style

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

Page 189: Python: the Project, the Language and the Style

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

Page 190: Python: the Project, the Language and the Style

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

Page 191: Python: the Project, the Language and the Style

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

Page 192: Python: the Project, the Language and the Style

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

Page 193: Python: the Project, the Language and the Style

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

Page 194: Python: the Project, the Language and the Style

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

Page 195: Python: the Project, the Language and the Style

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

Page 196: Python: the Project, the Language and the Style

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

Page 197: Python: the Project, the Language and the Style

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

Page 198: Python: the Project, the Language and the Style

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

Page 199: Python: the Project, the Language and the Style

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

Page 200: Python: the Project, the Language and the Style

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

Page 201: Python: the Project, the Language and the Style

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

Page 202: Python: the Project, the Language and the Style

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

Page 203: Python: the Project, the Language and the Style

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

Page 204: Python: the Project, the Language and the Style

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

Page 205: Python: the Project, the Language and the Style

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

Page 206: Python: the Project, the Language and the Style

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