Python: Overview and Advanced Topics - PowerPoint PPT Presentation

About This Presentation
Title:

Python: Overview and Advanced Topics

Description:

... after the BBC show 'Monty Python's Flying Circus' and has nothing ... Making references to Monty Python skits in documentation is not only allowed, it ... – PowerPoint PPT presentation

Number of Views:4308
Avg rating:3.0/5.0
Slides: 38
Provided by: kirby5
Category:

less

Transcript and Presenter's Notes

Title: Python: Overview and Advanced Topics


1
PythonOverview and Advanced Topics
  • Kirby Urner
  • 4D Solutions

2
Python World
3rd Party Add-Ons
Standard Library
Core
Applications
3
Topics to Cover
  • Overview
  • Core Python
  • Batteries Included (adding power)
  • Python as Glue Language (talking to other apps)

4
Part 1 Overview
  • What is Python?
  • Community
  • On Ramps
  • Development Environments
  • Design Philosophy
  • Evolution

5
By the way, the language is named after the BBC
show Monty Python's Flying Circus and has
nothing to do with nasty reptiles. Making
references to Monty Python skits in documentation
is not only allowed, it is encouraged! Guido van
RossumPython Tutorial
6
What is Python?
  • Interpreted compiles to byte codes
  • Interactive shell mode
  • OO everything is an object
  • Modular Standard Library 3rd party
  • Extensible code new modules in C/C
  • Portable Windows, Unix, Linux, Mac
  • High Level built-in dynamic data types
  • Free including for commercial use

7
Python - why settle for snake oil when you can
have the whole snake?
From Usenet posting by
Mark Jackson, June 1998
8
Interpreted
  • Not much compile time checking
  • No type declarations
  • Lots of freedom at runtime
  • Compiling to byte codes .pyc, .pyo
  • Python VM required (a .dll in Windows)
  • No compile/link loop reload instead
  • Rapid development, relatively slow execution
    (but frequently plenty fast)

9
Interactive
  • Many GUI shell options (plus non-GUI shell)
  • Shell mode as work bench
  • Jython interactive access to Java classes
  • Learning / testing time is drastically reduced

10
Object Oriented
  • Ideas from C, Modula-3, SmallTalk etc.
  • Variable names aliases or references to
    objects assignment results in multiple aliases
    to the same object

gtgtgt a 1,2,3 b a b10 gtgtgt a 1, 0, 3
11
Modular
  • Users save code in modules
  • Standard Library consists of modules
  • Modules may be grouped in packages
  • Scripts are modules (.py files)
  • Problem of namespace collisions is handled with
    module prefixes (like in Java)

12
Extensible
  • Wrap existing C/C libraries to make them
    importable as Python modules (e.g. wxPython,
    win32all)
  • Prototype in Python then rewrite speed-critical
    parts in C/C andimport
  • Create Python bindings for yourapplications i.e.
    export an API

13
Portable
  • Language accommodates many platform difference
    (e.g. path nameseparators
  • .pyc byte codes run on any CPythonVM
  • The language may be stripped downto run on cell
    phones, PDAs
  • Python VMs may be written in otherlanguages
    besides C

14
High Level
  • Powerful built-in typeslist, tuple, dictionary
    (also set)string, unicode
  • Native long integers (i.e. multi-precision),
    complex numbers, fixedprecision decimals (new in
    2.4)
  • Built-in and user-defined Exceptionswith try
    except raise finally
  • Canned parsers, protocol servers etc.

15
Free and Open Source
  • license is a built-in function. Call it, i.e.
    enter license() for some fascinating reading
  • Some older versions are more restricted
  • Although current Pythons are GPLcompatible, you
    are not required to release the source of
    derivative works,only to provide a summary of
    changes

16
Community
  • Guido van Rossum is BDFL
  • Language evolves via PEPs
  • Mail Lists technical, tutorial, sigs
  • Web sites add ons, tutorials
  • Documentation python.org, HTML
  • comp.lang.python (very active)
  • Subcultures Numeric, Zope/Plone,wxPython etc.

17
On Ramps
  • OReilly Learning Python Programming in
    Python Python in a Nutshell
  • Apress Dive Into Python (on-line edition!)
  • Guidos Tutorial in Python docs
  • Python Programming An Intro to CS

18
Development Environments
  • Free and Open Source
  • Commercial
  • Experimental
  • Graphical
  • A lot of developers use a text editorof choice
    (vi, emacs, eclipse)
  • Platform specific or more generic

19
Design Philosophy
gtgtgt import this The Zen of Python, by Tim
Peters 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!
20
Evolution
  • Change to division operator/ vs. //
  • Addition of new typesset, Decimal
  • Type / Class unificationnewstyle vs. classic
    classes
  • List comprehensions, generators
  • from __future__ import

21
Part 2 Nuts and Bolts
  • Invoking the interpreter
  • Statements and Expressions
  • Scoping
  • Control Structures
  • Functions and Generators
  • Classes
  • Modules
  • Packages

22
D\Python24gtpython -m test2 lt inputs.txt 'D\\Pyt
hon24\\test2.py' Enter text "Hello
world" D\Python24gttype test2.py import
sys print sys.argv a raw_input("Enter text
") print print a D\Python24gttype
inputs.txt "Hello world"
23
Scoping
  • A namespace is a mapping from names to objects...
  • Examples of namespaces are
  • the set of built-in names (functions such as
    abs(), and built-in exception names)
  • the global names in a module
  • and the local names in a function invocation.
  • from the Python Tutorial
    by GVR

24
Scoping
  • Locals lexically defined
  • Globals per module
  • Built-ins always available

gtgtgt import mathgtgtgt math.pi3.1415926535897931gt
gtgt from math import pigtgtgt pi3.1415926535897931gt
gtgt from math import atan as arctan
25
gtgtgt a 2 gtgtgt def f() return a 2 gtgtgt
f() 4 gtgtgt def f() a a 2 try to
bind local variable return a gtgtgt
f() Traceback (most recent call last) File
"ltpyshell8gt", line 1, in -toplevel- f()
File "ltpyshell7gt", line 2, in f a a
2 UnboundLocalError local variable 'a'
referenced before assignment
26
gtgtgt def f() global a explicit binding
to a global a a 2 return a gtgtgt a
2 gtgtgt f() 4 gtgtgt f() 6 gtgtgt a 6 gtgtgt globals()
built-in function 'a' 6, 'f' ltfunction f at
0x00C96F30gt, '__builtins__' ltmodule
'__builtin__' (built-in)gt, '__name__'
'__main__', '__doc__' None
27
Control Structures
  • The usual things butno case or switch other
    ways to get the same effect
  • break and continue
  • no GO TO or labels
  • for, while, if/elif
  • Exception handlingtry except else finally
    raise

28
gtgtgt pb 'guido' 4127, 'kirby' 4127, 'jack'
4098 gtgtgt pb'marla' 4147 add an entry
  • def invert(table) index empty
    dictionaryfor key in table.keys() value
    tablekey if not index.has_key(value)
    indexvalue empty list indexvalue.a
    ppend(key) return index

gtgtgt inverted_pb invert(pb) gtgtgt print
inverted_pb 4098 'jack', 4127
'guido','kirby', 4147 'marla'
29
gtgtgt pb.get('jason',) pb.get('guido',) 4127
  • def invert(table)"""Alternative invert
    function""" index empty dictionaryfor
    key,value in table.items() indexvalue
    index.get(value,) indexvalue.append(key)
    return index

gtgtgt from tutor1 import invert gtgtgt
help(invert)Help on function invert in module
tutor1 invert(table) Alternative invert
function
30
gtgtgt faces ('A','H','C','F'),
('A','H','B','G'), ('B','E','C','H'),
('B','E','D','G'), ('D','G','A','F'),
('C','E','D','F') gtgtgt getedges(faces) ('A','F'),
('A','G'),('A','H'),('B','E'), ('B','G'),('B','H')
,('C','E'),('C','F'), ('C','H'),('D','E'),('D','F'
),('D','G')
  • def getedges(faces) """Extract edges from the
    faces list"""
  • edges set()
  • for f in faces
  • pairs zip( f , f1 (f0,) )
  • for p in pairs
  • edges.add(tuple(sorted(p)))
  • return sorted(list(edges))

31
Functions and Generators
  • Functions are top level, meaning you may pass
    them as argumentsto other functions
  • Generators save state between function calls.
    Write as a functionbut with keyword yield
    instead of return

32
Classes
  • Classes support multiple inheritance
  • New-style classes inherit from object, are of
    type type
  • Classic classes are of type Classtype
  • Static and class methods supported
  • Late binding means lots of flexibility
  • Duck typing

33
Modules
  • A module may double as a script
  • Sometimes the script does self-testing
  • A module is the logical unit of a small solution
    space
  • Multiple modules organize in packages

34
Packages
  • Packages directories with subdirectories
  • __init__ defines whats imported orimportable
  • __all__ governs the behavior of from xxx import
  • Packages may have subpackages

35
Part 3 GUI Programming
  • Cross-platform wxPython, Tk, GTK, Qt
  • Platform specific MFC, .NET (?)

36
Python as Glue Language
  • win32all available for all versions from
    python.org
  • ActiveState Python incorporates Win32 features
  • Cross-platform GUI solutions
  • Future Python .NET (IronPython) also somewhat
    cross-platform

37
Windows Integration
  • Using win32all extensions, Python may operate as
    a COM client (e.g. control MSFT Office
    applications)
  • Python may also operate as a COM (or DCOM) server
    (e.g. callable from VBA)
  • Other COM objects DAO and ADO for database
    access
  • MSF Microsoft Foundation Classes
Write a Comment
User Comments (0)
About PowerShow.com