1 / 37

Python: Overview and Advanced Topics

Python: Overview and Advanced Topics. Kirby Urner 4D Solutions. Python World. 3 rd Party Add-Ons. Standard Library. Core. Applications. Topics to Cover. Overview Core Python “Batteries Included” (adding power) Python as Glue Language (talking to other apps). Part 1: Overview.

sumana
Download Presentation

Python: Overview and Advanced Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python:Overview and Advanced Topics Kirby Urner 4D Solutions

  2. Python World 3rd Party Add-Ons Standard Library Core Applications GIS in Action 2005

  3. Topics to Cover • Overview • Core Python • “Batteries Included” (adding power) • Python as Glue Language (talking to other apps) GIS in Action 2005

  4. Part 1: Overview • What is Python? • Community • On Ramps • Development Environments • Design Philosophy • Evolution GIS in Action 2005

  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 GIS in Action 2005

  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 GIS in Action 2005

  7. Python - why settle for snake oil when you can have the whole snake? — From Usenet posting by Mark Jackson, June 1998 GIS in Action 2005

  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”) GIS in Action 2005

  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 GIS in Action 2005

  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 >>>a = [1,2,3]; b = a; b[1]=0 >>>a [1, 0, 3] GIS in Action 2005

  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) GIS in Action 2005

  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 GIS in Action 2005

  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 GIS in Action 2005

  14. High Level Powerful built-in types:list, 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. GIS in Action 2005

  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 GIS in Action 2005

  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. GIS in Action 2005

  17. On Ramps O’Reilly:Learning PythonProgramming in PythonPython in a Nutshell Apress:Dive Into Python (on-line edition!) Guido’s Tutorial in Python docs Python Programming: An Intro to CS GIS in Action 2005

  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 GIS in Action 2005

  19. Design Philosophy >>> 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! GIS in Action 2005

  20. Evolution Change to division operator:/ vs. // Addition of new types:set, Decimal Type / Class unification:newstyle vs. classic classes List comprehensions, generators from __future__ import … GIS in Action 2005

  21. Part 2: Nuts and Bolts Invoking the interpreter Statements and Expressions Scoping Control Structures Functions and Generators Classes Modules Packages GIS in Action 2005

  22. D:\Python24>python -m test2 < inputs.txt ['D:\\Python24\\test2.py'] Enter text: "Hello world" D:\Python24>type test2.py import sys print sys.argv a = raw_input("Enter text: ") print print a D:\Python24>type 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 GIS in Action 2005

  24. Scoping Locals: lexically defined Globals: per module Built-ins: always available >>> import math>>> math.pi3.1415926535897931>>> from math import pi>>> pi3.1415926535897931>>>frommathimportatanasarctan GIS in Action 2005

  25. >>> a = 2 >>>def f():return a + 2 >>>f() 4 >>>def f(): a = a + 2 # try to bind local variable return a >>>f() Traceback (most recent call last): File "<pyshell#8>", line 1, in -toplevel- f() File "<pyshell#7>", line 2, in f a = a + 2 UnboundLocalError: local variable 'a' referenced before assignment

  26. >>>def f(): global a # explicit binding to a global a = a + 2 return a >>>a = 2 >>> f() 4 >>> f() 6 >>> a 6 >>>globals() # built-in function {'a': 6, 'f': <function f at 0x00C96F30>, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None}

  27. Control Structures The usual things but…no 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: GIS in Action 2005

  28. >>> pb = {'guido': 4127, 'kirby': 4127, 'jack': 4098} >>> pb['marla'] = 4147 # add an entry definvert(table): index = {} # empty dictionaryfor key in table.keys(): value = table[key] if not index.has_key(value): index[value] = [] # empty list index[value].append(key) return index >>> inverted_pb = invert(pb) >>>print inverted_pb {4098: ['jack'], 4127: ['guido','kirby'], 4147: ['marla']}

  29. >>> pb.get('jason',[]); pb.get('guido',[]) [] 4127 definvert(table):"""Alternative invert function"""index = {} # empty dictionaryfor key,value in table.items(): index[value] = index.get(value,[]) index[value].append(key) return index >>> from tutor1 import invert >>> help(invert)Help on function invert in module tutor1: invert(table) Alternative invert function

  30. >>> 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')] >>> 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')] defgetedges(faces):"""Extract edges from the faces list""" edges = set() for f in faces: pairs = zip( f , f[1:] + (f[0],) ) 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’ GIS in Action 2005

  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” GIS in Action 2005

  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 GIS in Action 2005

  34. Packages Packages = directories with subdirectories __init__ defines what’s imported orimportable __all__ governs the behavior of ‘from xxx import *’ Packages may have subpackages GIS in Action 2005

  35. Cross-platform: wxPython, Tk, GTK, Qt Platform specific: MFC, .NET (?) Part 3: GUI Programming GIS in Action 2005

  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 GIS in Action 2005

  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 GIS in Action 2005

More Related