KEMBAR78
Introduction to python | PPTX
Introduction to Python
Alexander Popov
July 24, 2013 www.ExigenServices.com
2 www.ExigenServices.com
• Who‟s using it?
• Why?
• Overview
• Kind of magic: special keywords
• Decorators
• Samples
• Zen
Presentation index
3 www.ExigenServices.com
Who’s using it?
Sourceforge, Fedora
community
TurboGears
Google, Yahoo, Zope,
Battlefield 2, Vampires:
TM, Civilization 4,
Blender, SGI, Red Hat,
Nokia, Caligari, ABN
AMRO Bank, NASA,
Thawte consulting, IBM,
……
OVER 9000!
Python
Instagram, Pinterest,
Mozilla, The Guardian,
The New York Times, The
Washington Post, Quora
Django
4 www.ExigenServices.com
Why?
5 www.ExigenServices.com
Why Python, not Ruby, Smalltack, Brainf*ck?
• Small core
• 29 keywords, 80 built-in functions
• Elegant syntax
• Embeddable to everything you want
• True cross platform
• Absolutely free
• Extendable (via C++ modules)
• Rich standard library
• Binding almost to everything
6 www.ExigenServices.com
• Fast logic prototyping
• It automates for you mechanical work
• Improves you mind
• Force you to write clear code (on other langs also, sad but true)
• Web development
• Desktop development
• Access to system internal features (WinAPI, Dbus)
• You can find tool for everything.
Why should I spend my time on it instead of beer?
7 www.ExigenServices.com
• Easier than Pascal
• Better than Basic
• Slimmer than PHP
• Prettier than Ruby (empty? empty! empty!! empty!!!!!)
• Does not suffer of abundance of parentheses (((hello) (,) (Lisp!)))
• Pointers? What is it? Ahhhh, it is C++!
• More much dynamic than Java (hello, dynamic typing)
• Improves karma and makes you happy
Wait, what does it means? Really, why?
8 www.ExigenServices.com
• Structural
• OOP
• Functional
• Imperative
• Aspect-oriented
Python paradigms
9 www.ExigenServices.com
Python overview
10 www.ExigenServices.com
• Dynamic (duck) typing
• Variety of basic data types
• Hierarchy marked by indentation
• Code may be grouped to modules
• Exception infrastructure
• Advanced features like generators and list comprehension
• Garbage collector and automatic memory management
Overview: Heap, part 1
11 www.ExigenServices.com
• Function marked by keyword „def‟
• Classes marked by keyword „class‟
• String are immutable
• Special keywords surrounded by
double underscore
• Variables not marked.
Just assign and use.
• Lambda functions
• Object model
Overview: Heap, part 2
12 www.ExigenServices.com
• Do you like objects?
• Class instance is object
• Class definition is object
too.
• Functions. It is objects also.
• Aren‟t you bored of objects?
Elementary types are objects.
• Types… Ok, you know…
• EVERYTHING IS OBJECT!
Everything is object! No exceptions.
13 www.ExigenServices.com
• Just one operator
• Function-powered
variant
• Class example
Hello world
14 www.ExigenServices.com
Class introspection
15 www.ExigenServices.com
• There are matter how to declare
class data members: class-
or instance-wide.
• Class data members
Declared inside class body.
Accessible for all instances
• Instance data members
Declared inside constructor.
Accessible only for one instance.
Class introspection: Members declaration
16 www.ExigenServices.com
• Data members
• Public (no special marks)
• Private-by-convention (started with at least one underscore and
finished with not more than 1 underscore)
• Private-by-mangling (started with 2 underscores and finished
with not more than 1 underscore)
Class introspection: Member access
17 www.ExigenServices.com
• Each class member contains
reference to class object
• Class methods (except static)
are unbound
• Instance methods are bound
• Instance methods may be
called directly
• Class methods may be
called indirectly
Class introspection: Method calls
18 www.ExigenServices.com
• Class definition creation on the fly
• Metaclasses
Class introspection: Fatality
19 www.ExigenServices.com
Sequences
20 www.ExigenServices.com
• Immutable
• String
• Unicode
• Tuple
• Mutable
• List
• Byte Array
• Pseudo sequences
• Sets & frosensets
• Dictionary
Sequences
21 www.ExigenServices.com
List comprehension
22 www.ExigenServices.com
0 1 2 3
[1, 2, 3, 4]
-4 -3 -2 -1
• Index model:
• Indexation
• Indices started from 0
• Indices may be negative
• Slices
• With positive indices
• With negative indices
(be careful with order!)
• With step
Sequences indexation and slicing
23 www.ExigenServices.com
Ranges and generators
24 www.ExigenServices.com
• Ranges
• range( [start], stop, [step] )
• xrange( [start], stop, [step] )
• Generator
Ranges and generators
25 www.ExigenServices.com
Special keywords magic
26 www.ExigenServices.com
• Started and finished with 2 underscore: __foo__
• __call__
• __add__
• __iadd__
• Using special keywords we can emulate any native type:
• Callable (__call__)
• Container (__len__, __getitem__, __setitem__, __delitem__,
__iter__, __reversed__, …)
• Numeric (__add__, __sub__, __mul__, __floordiv__, ...)
Special keywords magic
27 www.ExigenServices.com
Decorators
28 www.ExigenServices.com
• Decorator
• A function that takes one argument
(i.e. the function being decorated)
• Returns the same function or a function
with a similar signature
(i.e. something useful)
• Still WTF? Do not bother,
“what is decorator” is one of most
popular Python questions
Decorators
29 www.ExigenServices.com
• Similar interface
• Similar behavior
• But not the same
Decorators, live
30 www.ExigenServices.com
• Declare the decorator
• Wrap the function
• …
• PROFIT!
• Hey! I want to wrap MY
function!
• Add some magic
• …
• PROFIT again!
Decorators: Wrap the function
31 www.ExigenServices.com
A bit harder…
Decorators: Count function calls
32 www.ExigenServices.com
Decorators: Count function calls, usage
33 www.ExigenServices.com
Meet the Samples
34 www.ExigenServices.com
• Simple HTTP server
python -m SimpleHTTPServer 8888
• SMTP server
python -m smtpd -n -c DebuggingServer localhost:25
• CGI server
python -m CGIHTTPServer 9080
• How many bytes in…
zip(
('Byte','KByte','MByte','GByte',TByte'),
(1 << 10*i for i in xrange(5))
)
• Windows clipboard
import win32clipboard
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text)
win32clipboard.CloseClipboard()
One-, two- and three-line scripts, part 1
35 www.ExigenServices.com
• Decode base64
import base64, sys;
base64.decode(
open(“encoded.file”, "rb"),
open(“decoded.file”, "wb")
)
• COM
• Test via Python
• Test via VB
One-, two- and three-line scripts, part 2
36 www.ExigenServices.com
Web development
37 www.ExigenServices.com
• Import module Flask
• Create application
• Add route and view
• Run application
Flask micro framework, part 1
38 www.ExigenServices.com
Flask micro framework, part 2
39 www.ExigenServices.com
Flask micro framework, part 3
Alex
40 www.ExigenServices.com
• Fast
• Customizable
• Rich functionality
Templating with Jinja2
41 www.ExigenServices.com
Templating with Jinja2
42 www.ExigenServices.com
• http://docs.python.org/
• http://learnpythonthehardway.org/
• Google Python Days on Youtube
• Coursera:
https://www.coursera.org/course/interactivepython
https://www.coursera.org/course/programming1
• EdX:
https://www.edx.org/courses/MITx/6.00x/2012_Fall/about
• Google, do you speak it?!
• Stackoverflow
• http://www.tornadoweb.org/
• http://www.pylonsproject.org/
• https://www.djangoproject.com/
• http://flask.pocoo.org/
• http://wiki.python.org/moin/PythonDecoratorLibrary
Additional resources
43 www.ExigenServices.com
>>> import this
• 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.
to be continued…
The Zen of Python
44 www.ExigenServices.com
>>> import this
• 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!
The Zen of Python, part 2
45 www.ExigenServices.com
Afterpaty
46 www.ExigenServices.com
main.py (Create application, initialize database, setup error handlers, Add blueprints)
|=> application1 (account, blog, core)
|=> constants.py (application-wide constants)
|=> forms.py (form used in application)
|=> models.py (database models)
|=> views.py (views)
|=> utils.py
|=> application2
|=> constants.py
|=> forms.py
|=> models.py
|=> views.py
|=> utils.py
…………..
Flask blog code explanation, structure
47 www.ExigenServices.com
Flask blog code explanation, constants
48 www.ExigenServices.com
Flask blog code explanation, forms
49 www.ExigenServices.com
Flask blog code explanation, models
50 www.ExigenServices.com
Flask blog code explanation, views
51 www.ExigenServices.com
Flask blog code explanation, templates
52 www.ExigenServices.com
Thank you!
P.S.: You are fantastic!

Introduction to python

  • 1.
    Introduction to Python AlexanderPopov July 24, 2013 www.ExigenServices.com
  • 2.
    2 www.ExigenServices.com • Who‟susing it? • Why? • Overview • Kind of magic: special keywords • Decorators • Samples • Zen Presentation index
  • 3.
    3 www.ExigenServices.com Who’s usingit? Sourceforge, Fedora community TurboGears Google, Yahoo, Zope, Battlefield 2, Vampires: TM, Civilization 4, Blender, SGI, Red Hat, Nokia, Caligari, ABN AMRO Bank, NASA, Thawte consulting, IBM, …… OVER 9000! Python Instagram, Pinterest, Mozilla, The Guardian, The New York Times, The Washington Post, Quora Django
  • 4.
  • 5.
    5 www.ExigenServices.com Why Python,not Ruby, Smalltack, Brainf*ck? • Small core • 29 keywords, 80 built-in functions • Elegant syntax • Embeddable to everything you want • True cross platform • Absolutely free • Extendable (via C++ modules) • Rich standard library • Binding almost to everything
  • 6.
    6 www.ExigenServices.com • Fastlogic prototyping • It automates for you mechanical work • Improves you mind • Force you to write clear code (on other langs also, sad but true) • Web development • Desktop development • Access to system internal features (WinAPI, Dbus) • You can find tool for everything. Why should I spend my time on it instead of beer?
  • 7.
    7 www.ExigenServices.com • Easierthan Pascal • Better than Basic • Slimmer than PHP • Prettier than Ruby (empty? empty! empty!! empty!!!!!) • Does not suffer of abundance of parentheses (((hello) (,) (Lisp!))) • Pointers? What is it? Ahhhh, it is C++! • More much dynamic than Java (hello, dynamic typing) • Improves karma and makes you happy Wait, what does it means? Really, why?
  • 8.
    8 www.ExigenServices.com • Structural •OOP • Functional • Imperative • Aspect-oriented Python paradigms
  • 9.
  • 10.
    10 www.ExigenServices.com • Dynamic(duck) typing • Variety of basic data types • Hierarchy marked by indentation • Code may be grouped to modules • Exception infrastructure • Advanced features like generators and list comprehension • Garbage collector and automatic memory management Overview: Heap, part 1
  • 11.
    11 www.ExigenServices.com • Functionmarked by keyword „def‟ • Classes marked by keyword „class‟ • String are immutable • Special keywords surrounded by double underscore • Variables not marked. Just assign and use. • Lambda functions • Object model Overview: Heap, part 2
  • 12.
    12 www.ExigenServices.com • Doyou like objects? • Class instance is object • Class definition is object too. • Functions. It is objects also. • Aren‟t you bored of objects? Elementary types are objects. • Types… Ok, you know… • EVERYTHING IS OBJECT! Everything is object! No exceptions.
  • 13.
    13 www.ExigenServices.com • Justone operator • Function-powered variant • Class example Hello world
  • 14.
  • 15.
    15 www.ExigenServices.com • Thereare matter how to declare class data members: class- or instance-wide. • Class data members Declared inside class body. Accessible for all instances • Instance data members Declared inside constructor. Accessible only for one instance. Class introspection: Members declaration
  • 16.
    16 www.ExigenServices.com • Datamembers • Public (no special marks) • Private-by-convention (started with at least one underscore and finished with not more than 1 underscore) • Private-by-mangling (started with 2 underscores and finished with not more than 1 underscore) Class introspection: Member access
  • 17.
    17 www.ExigenServices.com • Eachclass member contains reference to class object • Class methods (except static) are unbound • Instance methods are bound • Instance methods may be called directly • Class methods may be called indirectly Class introspection: Method calls
  • 18.
    18 www.ExigenServices.com • Classdefinition creation on the fly • Metaclasses Class introspection: Fatality
  • 19.
  • 20.
    20 www.ExigenServices.com • Immutable •String • Unicode • Tuple • Mutable • List • Byte Array • Pseudo sequences • Sets & frosensets • Dictionary Sequences
  • 21.
  • 22.
    22 www.ExigenServices.com 0 12 3 [1, 2, 3, 4] -4 -3 -2 -1 • Index model: • Indexation • Indices started from 0 • Indices may be negative • Slices • With positive indices • With negative indices (be careful with order!) • With step Sequences indexation and slicing
  • 23.
  • 24.
    24 www.ExigenServices.com • Ranges •range( [start], stop, [step] ) • xrange( [start], stop, [step] ) • Generator Ranges and generators
  • 25.
  • 26.
    26 www.ExigenServices.com • Startedand finished with 2 underscore: __foo__ • __call__ • __add__ • __iadd__ • Using special keywords we can emulate any native type: • Callable (__call__) • Container (__len__, __getitem__, __setitem__, __delitem__, __iter__, __reversed__, …) • Numeric (__add__, __sub__, __mul__, __floordiv__, ...) Special keywords magic
  • 27.
  • 28.
    28 www.ExigenServices.com • Decorator •A function that takes one argument (i.e. the function being decorated) • Returns the same function or a function with a similar signature (i.e. something useful) • Still WTF? Do not bother, “what is decorator” is one of most popular Python questions Decorators
  • 29.
    29 www.ExigenServices.com • Similarinterface • Similar behavior • But not the same Decorators, live
  • 30.
    30 www.ExigenServices.com • Declarethe decorator • Wrap the function • … • PROFIT! • Hey! I want to wrap MY function! • Add some magic • … • PROFIT again! Decorators: Wrap the function
  • 31.
    31 www.ExigenServices.com A bitharder… Decorators: Count function calls
  • 32.
  • 33.
  • 34.
    34 www.ExigenServices.com • SimpleHTTP server python -m SimpleHTTPServer 8888 • SMTP server python -m smtpd -n -c DebuggingServer localhost:25 • CGI server python -m CGIHTTPServer 9080 • How many bytes in… zip( ('Byte','KByte','MByte','GByte',TByte'), (1 << 10*i for i in xrange(5)) ) • Windows clipboard import win32clipboard win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(text) win32clipboard.CloseClipboard() One-, two- and three-line scripts, part 1
  • 35.
    35 www.ExigenServices.com • Decodebase64 import base64, sys; base64.decode( open(“encoded.file”, "rb"), open(“decoded.file”, "wb") ) • COM • Test via Python • Test via VB One-, two- and three-line scripts, part 2
  • 36.
  • 37.
    37 www.ExigenServices.com • Importmodule Flask • Create application • Add route and view • Run application Flask micro framework, part 1
  • 38.
  • 39.
  • 40.
    40 www.ExigenServices.com • Fast •Customizable • Rich functionality Templating with Jinja2
  • 41.
  • 42.
    42 www.ExigenServices.com • http://docs.python.org/ •http://learnpythonthehardway.org/ • Google Python Days on Youtube • Coursera: https://www.coursera.org/course/interactivepython https://www.coursera.org/course/programming1 • EdX: https://www.edx.org/courses/MITx/6.00x/2012_Fall/about • Google, do you speak it?! • Stackoverflow • http://www.tornadoweb.org/ • http://www.pylonsproject.org/ • https://www.djangoproject.com/ • http://flask.pocoo.org/ • http://wiki.python.org/moin/PythonDecoratorLibrary Additional resources
  • 43.
    43 www.ExigenServices.com >>> importthis • 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. to be continued… The Zen of Python
  • 44.
    44 www.ExigenServices.com >>> importthis • 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! The Zen of Python, part 2
  • 45.
  • 46.
    46 www.ExigenServices.com main.py (Createapplication, initialize database, setup error handlers, Add blueprints) |=> application1 (account, blog, core) |=> constants.py (application-wide constants) |=> forms.py (form used in application) |=> models.py (database models) |=> views.py (views) |=> utils.py |=> application2 |=> constants.py |=> forms.py |=> models.py |=> views.py |=> utils.py ………….. Flask blog code explanation, structure
  • 47.
    47 www.ExigenServices.com Flask blogcode explanation, constants
  • 48.
    48 www.ExigenServices.com Flask blogcode explanation, forms
  • 49.
    49 www.ExigenServices.com Flask blogcode explanation, models
  • 50.
    50 www.ExigenServices.com Flask blogcode explanation, views
  • 51.
    51 www.ExigenServices.com Flask blogcode explanation, templates
  • 52.