78
Libraries Python Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information.

Libraries

Embed Size (px)

Citation preview

Libraries

Python

Libraries

Copyright © Software Carpentry 2010

This work is licensed under the Creative Commons Attribution License

See http://software-carpentry.org/license.html for more information.

A function is a way to turn a bunch of related

statements into a single "chunk"

Python Libraries

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

Python Libraries

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

Python Libraries

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Python Libraries

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Hierarchical organization

Python Libraries

A function is a way to turn a bunch of related

statements into a single "chunk"

– Avoid duplication– Avoid duplication

– Make code easier to read

A library does the same thing for related functions

Hierarchical organization

Python Libraries

family library

genus function

species statement

Every Python file can be used as a library

Python Libraries

Every Python file can be used as a library

Use import to load it

Python Libraries

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

Python Libraries

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

# program.py

importimportimportimport halman

readings = [0.1, 0.4, 0.2]

printprintprintprint 'signal threshold is', halman.threshold(readings)

Python Libraries

printprintprintprint 'signal threshold is', halman.threshold(readings)

Every Python file can be used as a library

Use import to load it

# halman.py# halman.py

defdefdefdef threshold(signal):

returnreturnreturnreturn 1.0 / sum(signal)

# program.py

importimportimportimport halman

readings = [0.1, 0.4, 0.2]

printprintprintprint 'signal threshold is', halman.threshold(readings)

Python Libraries

printprintprintprint 'signal threshold is', halman.threshold(readings)

$$$$ python program.py

signal threshold is 1.42857

When a module is imported, Python:

Python Libraries

When a module is imported, Python:

1. Executes the statements it contains

Python Libraries

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

Python Libraries

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

>>>>>>>>>>>> import noisy

is this module being loaded?

When a module is imported, Python:

1. Executes the statements it contains

2. Creates an object that stores references to2. Creates an object that stores references to

the top-level items in that module

# noisy.py

printprintprintprint 'is this module being loaded?'

NOISE_LEVEL = 1./3.

Python Libraries

>>>>>>>>>>>> import noisy

is this module being loaded?

>>>>>>>>>>>> print noisy.NOISE_LEVEL

0.33333333

Each module is a namespace

Python Libraries

Each module is a namespace

function

Python Libraries

Each module is a namespace

modulemodule

function

Python Libraries

Each module is a namespace

global

modulemodule

function

Python Libraries

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

>>>>>>>>>>>> import module

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Each module is a namespace

global

module

# module.py

NAME = 'Transylvania'

defdefdefdef func(arg):

module

function

>>>>>>>>>>>> NAME = 'Hamunaptra'

>>>>>>>>>>>> import module

>>>>>>>>>>>> print module.func('!!!')

Transylvania !!!

Python Libraries

defdefdefdef func(arg):

returnreturnreturnreturn NAME + ' ' + arg

Transylvania !!!

Python comes with many standard libraries

Python Libraries

Python comes with many standard libraries

>>> import math

Python Libraries

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

Python Libraries

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

>>> >>> >>> >>> print print print print math.hypot(2, 3) # sqrt(x**2 + y**2)

3.6055512754639891

Python Libraries

Python comes with many standard libraries

>>> import math

>>> >>> >>> >>> printprintprintprint math.sqrt(2)

1.41421356237309511.4142135623730951

>>> >>> >>> >>> print print print print math.hypot(2, 3) # sqrt(x**2 + y**2)

3.6055512754639891

>>> >>> >>> >>> print print print print math.e, math.pi # as accurate as possible

2.7182818284590451 3.1415926535897931

Python Libraries

Python also provides a help function

Python Libraries

Python also provides a help function

>>> >>> >>> >>> import import import import math

>>> >>> >>> >>> help(math)Help on module math:Help on module math:NAME

mathFILE

/usr/lib/python2.5/lib-dynload/math.soMODULE DOCS

http://www.python.org/doc/current/lib/module-math.htmlDESCRIPTION

This module is always available. It provides access to themathematical functions defined by the C standard.

Python Libraries

mathematical functions defined by the C standard.FUNCTIONS

acos(...)acos(x)Return the arc cosine (measured in radians) of x.

And some nicer ways to do imports

Python Libraries

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

Python Libraries

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0

Python Libraries

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Python Libraries

>>>>>>>>>>>>

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Generally a bad idea

Python Libraries

>>>>>>>>>>>>

And some nicer ways to do imports

>>> >>> >>> >>> fromfromfromfrom math importimportimportimport sqrt

>>> >>> >>> >>> sqrt(3)

1.73205080756887721.7320508075688772

>>>>>>>>>>>> fromfromfromfrom math importimportimportimport hypot asasasas euclid

>>>>>>>>>>>> euclid(3, 4)

5.0>>> >>> >>> >>> fromfromfromfrom math importimportimportimport *

>>> >>> >>> >>> sin(pi)

1.2246063538223773e-16>>>>>>>>>>>>

Generally a bad idea

Someone could add to

the library after you

Python Libraries

>>>>>>>>>>>>the library after you

start using it

Almost every program uses the sys library

Python Libraries

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

Python Libraries

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]

Python Libraries

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32

Python Libraries

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32>>>>>>>>>>>> printprintprintprint sys.maxint

2147483647

Python Libraries

Almost every program uses the sys library

>>> >>> >>> >>> importimportimportimport sys

>>> >>> >>> >>> printprintprintprint sys.version

2.7 (r27:82525, Jul 4 2010, 09:01:59)2.7 (r27:82525, Jul 4 2010, 09:01:59)

[MSC v.1500 32 bit (Intel)]>>>>>>>>>>>> printprintprintprint sys.platform

win32>>>>>>>>>>>> printprintprintprint sys.maxint

2147483647

>>> >>> >>> >>> printprintprintprint sys.path

['',

Python Libraries

['','C:\\WINDOWS\\system32\\python27.zip',

'C:\\Python27\\DLLs', 'C:\\Python27\\lib','C:\\Python27\\lib\\plat-win',

'C:\\Python27', 'C:\\Python27\\lib\\site-packages']

sys.argv holds command-line arguments

Python Libraries

sys.argv holds command-line arguments

Script name is sys.argv[0]

Python Libraries

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

Python Libraries

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

$ $ $ $ python echo.py

0 echo.py

$$$$

Python Libraries

$$$$

sys.argv holds command-line arguments

Script name is sys.argv[0]

# echo.py# echo.py

importimportimportimport sys

forforforfor i inininin range(len(sys.argv)):

printprintprintprint i, '"' + sys.argv[i] + '"'

$ $ $ $ python echo.py

0 echo.py

$$$$ python echo.py first second

Python Libraries

$$$$ python echo.py first second

0 echo.py

1 first

2 second

$$$$

sys.stdin is standard input (e.g., the keyboard)

Python Libraries

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

Python Libraries

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

sys.stderr is standard error (usually also the screen)sys.stderr is standard error (usually also the screen)

Python Libraries

sys.stdin is standard input (e.g., the keyboard)

sys.stdout is standard output (e.g., the screen)

sys.stderr is standard error (usually also the screen)sys.stderr is standard error (usually also the screen)

See the Unix shell lecture for more information

Python Libraries

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

Python Libraries

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

$$$$ python count.py < a.txt

48

$$$$

Python Libraries

$$$$

# count.py

importimportimportimport sys

ifififif len(sys.argv) == 1:

count_lines(sys.stdin)

else:else:else:else:else:else:else:else:

rd = open(sys.argv[1], 'r')

count_lines(rd)

rd.close()

$$$$ python count.py < a.txt

48

$$$$ python count.py b.txt

Python Libraries

$$$$ python count.py b.txt

227

$$$$

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

The more polite way

'''Count lines in files. If no filename arguments given,

read from standard input.'''

importimportimportimport sys

defdefdefdef count_lines(reader):

'''Return number of lines in text read from reader.'''

returnreturnreturnreturn len(reader.readlines())

ifififif __name__ == '__main__':

Python Libraries

ifififif __name__ == '__main__':

...as before...

If the first statement in a module or function is

a string, it is saved as a docstring

Python Libraries

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

Python Libraries

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

Python Libraries

returnreturnreturnreturn a+b

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

>>> >>> >>> >>> import adder

>>>>>>>>>>>> help(adder)

NAME

adder - Addition utilities.

FUNCTIONSadd(a, b)

Python Libraries

returnreturnreturnreturn a+b add(a, b)Add arguments.

>>>>>>>>>>>>

If the first statement in a module or function is

a string, it is saved as a docstring

Used for online (and offline) helpUsed for online (and offline) help

# adder.py

'''Addition utilities.'''

defdefdefdef add(a, b):

'''Add arguments.'''

returnreturnreturnreturn a+b

>>> >>> >>> >>> import adder

>>>>>>>>>>>> help(adder)

NAME

adder - Addition utilities.

FUNCTIONSadd(a, b)

Python Libraries

returnreturnreturnreturn a+b add(a, b)Add arguments.

>>>>>>>>>>>> help(adder.add)

add(a, b)

Add arguments.>>>>>>>>>>>>

When Python loads a module, it assigns a value

to the module-level variable __name__

Python Libraries

When Python loads a module, it assigns a value

to the module-level variable __name__

main program

'__main__'

Python Libraries

When Python loads a module, it assigns a value

to the module-level variable __name__

main program loaded as library

'__main__' module name

Python Libraries

When Python loads a module, it assigns a value

to the module-level variable __name__

main program loaded as library

'__main__' module name

...module definitions...

Python Libraries

ifififif __name__ == '__main__':

...run as main program...

When Python loads a module, it assigns a value

to the module-level variable __name__

main program loaded as library

'__main__' module name

...module definitions... Always executed

Python Libraries

ifififif __name__ == '__main__':

...run as main program...

When Python loads a module, it assigns a value

to the module-level variable __name__

main program loaded as library

'__main__' module name

...module definitions... Always executed

Python Libraries

ifififif __name__ == '__main__':

...run as main program... Only executed when

file run directly

# stats.py

'''Useful statistical tools.'''

defdefdefdef average(values):

'''Return average of values or None if no data.''''''Return average of values or None if no data.'''

ifififif values:

returnreturnreturnreturn sum(values) / len(values)

else:else:else:else:

return Nonereturn Nonereturn Nonereturn None

if if if if __name__ == '__main__':

printprintprintprint 'test 1 should be None:', average([])

Python Libraries

printprintprintprint 'test 1 should be None:', average([])

printprintprintprint 'test 2 should be 1:', average([1])

printprintprintprint 'test 3 should be 2:', average([1, 2, 3])

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint 'test 5 should be -1:', average({0, -1, -2})

Python Libraries

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint 'test 5 should be -1:', average({0, -1, -2})

$$$$ python stats.py

test 1 should be None: None

test 2 should be 1: 1

test 3 should be 2: 2

$$$$

Python Libraries

# test-stats.py

from from from from stats importimportimportimport average

printprintprintprint 'test 4 should be None:', average(set())

printprintprintprint 'test 5 should be -1:', average({0, -1, -2})

$$$$ python stats.py

test 1 should be None: None

test 2 should be 1: 1

test 3 should be 2: 2

$$$$ python test-stats.py

test 4 should be None: None

test 5 should be -1: -1

Python Libraries

test 5 should be -1: -1

$$$$

October 2010

created by

Greg Wilson

October 2010

Copyright © Software Carpentry 2010

This work is licensed under the Creative Commons Attribution License

See http://software-carpentry.org/license.html for more information.