Python



Python

0 0


python-talk

Presentation to accompany my talk on python.

On Github parthrbhatt / python-talk

Python

Parth Bhatt

Different Flavours

CPython Python2, Python3. Python written in C. Jython Converts Python code to Java Bytecode. IronPython Python for the .NET framework. Integrates well with Visual Studio. PythonNet Integration with .NET CLR. PyPy Intepreter written in RPython.

Say Hello to Python

  • An interpreted, object-oriented programming language.
  • High programmer productivity.
  • Simple & easy to learn. Clear Syntax.
  • High-level language.
  • Extensible in C or C++.
  • Portable: It runs on many Unix variants, Mac, PC.
  • Extensive libraries.

Setup: virtualenv

  • Helps create self-contained environment for your projects.
  • Solves the "Project X depends on version 1.x but, Project Y needs 4.x" dilemma.
  • Install virtualenv
    $ pip install virtualenv
    
  • Create a virtalenv for a project:
    $ cd my_project_folder
    $ virtualenv venv
    $ source venv/bin/activate
    

Tools & Utils: Package Managers

  • easy_install
  • pip

A Simple Python Program

fib.py

import sys

def fib(n):
    """Fibonacci series"""

    a, b = 0, 1

    sys.stdout.write('%s ' %a)
    while b < n:
        a, b = b, a + b
        sys.stdout.write('%s ' %a)

if '__main__' == __name__:
    n = raw_input('Enter a number: ')
    print 'Fibonacci series'
    fib(int(n))

A Simple Python Program

main.py

from fib import fib

if '__main__' == __name__:
    fib(10)

Data Types

  • Numeric Types: int, float, long, complex.
  • Built-in data types: dict, list, tuple, set.

Variables and Types

  • The types module and type()
  • Strongly typed and Dynamic.
  • Size of an object sys.getsizeof().

Syntax

  • Delimit blocks simply by indenting the code, no brackets or statements like BEGIN and END.
  • Import external libs using import.
  • Comments start with a #.
  • Swap two vars:
    a, b = b, a
    
  • Also, statements dont need to end with a semicolon.

Strings

a = 'This is a string.'
b = "This is also a string."
c = "do or don't"
d = 'She said "I know python"'

e = "This string spans\
across multiple lines"

f = """This string spans
across multiple lines"""

print '='*80
print a[3], a[-3]
print len(a)

Syntax: Flow Control

  • if-elif-else
  • for, while loops. No do-while loop, who uses that anyways ? :)
  • switch. Oh ! Wait. There is no switch.
  • break, continue & pass
  • try-except-finally
  • else clauses for for, while, try loops

py, pyc & pyo files

.py A python module's source code in plain text. .pyc Contains byte-compiled version of a module. Platform independent. .pyo Optimized byte code.

Modules

  • Builtin modules e.g: os, sys, datetime, hashlib, math, select, bz2, platform etc.
  • Importing modules:
    import sys
    from os.path import join
    
  • Creating your own modules
  • Understanding 'main'
    if '__main__' == __name__:
      fib(10)
    
  • The module search path: PYTHONPATH, sys.path

Packages

Structure Python's module namespace.

from sound.formats import waveread, wavewrite
import sound.effects.echo
from sound.formats import *
from sound.effects.echo import echofilter

Everything is an object

  • Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
  • Everything has attributes and methods:
    • types have member functions.
    • functions have attributes.
    • modules can be passed as arguments, etc.
  • To checkout what's contained inside anything use dir()

Writing Pythonic Code

  • Duck typing: If it looks like a duck & quacks like a duck, it must be a duck.
  • EAFP (as opposed to LBYL): Easier to Ask for Forgiveness than Permission.
  • List Comprehensions.

Modify behavior at runtime

  • Powerful mechanism.
  • Allows you to generate classes.
  • Lets you add fields and define / modify a class's behavior.

lambda

  • Create small anonymous functions.

    add = lambda a, b: a+b
    add(10, 20)
    
  • Syntactically restricted to a single expression.

filter

  • Returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true
    filter(function, sequence)
    
  • Eg: Find all even numbers in a given sequence:
    filter(lambda x: not x%2, [1,2,3,4])
    

map

  • Calls function(item) for each of the sequence's items and returns a list of the return values.
    map(function, sequence)
    
  • Eg:
def sq(a):
    return (a*a)

lst = [1,2,3,4]

map(sq, lst)

Or, of course:

map(lambda x: x*x, [1,2,3,4])

reduce

  • Returns a single value constructed by calling the (binary) function on the first two items of the sequence, then on the result and the next item, and so on

    reduce(function, sequence)
    
  • Eg:

def add(a, b):
    return (a+b)

lst = [1,2,3,4]

reduce(add, lst)

Of course, the above is same as:

reduce(lambda x,y: x+y, [1,2,3,4])

Concurrency

  • Threads? Think Twice.
  • Multiprocessing.
  • Asynchronous / Event-Driven Programming.
  • Global Interpreter Lock.

Global Interpreter Lock

  • A mutex. Actually, a binary semaphore inside the python interpreter.
  • Limits the amount of parallelism reachable through concurrency of a single interpreter process with multiple threads.
  • GIL exists because:
    • Increased speed of single-threaded programs.
    • Greatly simplifies integration with C libs that are usually not thread safe.
    • Ease of implementation of the Compiler.

Links

Links

Thank You !

Python Parth Bhatt