python-intro



python-intro

0 0


python-intro

Introductory python training

On Github catalyst-training / python-intro

Catalyst

Python for Perl developers

Presented by Tom Eastman

Cheat sheet

Course outline

The Python language

The Python environment

The Python ecosystem

Part 1: The Python language

  • How to write some Python

  • The core datatypes and how to use them

  • A crash course in language features (spotters guide)

Getting set up

This setup script will:

  • Use apt to install Python 2 and 3

  • Use pip to install IPython Notebook

  • Clone my python-for-perl-developers repository.

$ wget http://tap.wgtn.cat-it.co.nz/python-for-perl-developers/setup.sh
$ bash ./setup.sh

Running the IPython Notebook

Running...

ipython notebook

...will get you a workspace to start writing Python.

You can create workbooks for both Python 2 and Python 3

- Make sure everyone can get the IPython Notebook fired up.

Python 3 vs Python 2

Python 3

  • Python 3 was a backwards-incompatible update to the Python language.
  • It's Python 2 with the warts removed.
  • Python 3.3 added back some backwards compatibility
  • Use Python 3.3 or greater.

Python 2

  • Python 2.7 will be the last version of Python 2
  • It'll probably be around forever.
  • There will never be new features added to it...
  • ...although many libraries are back-ported via PyPI (mock, enum, etc)
  • You can use __future__ to make Python 2 look more like Python 3
- SSL was a special case

Should I use Python 2 or Python 3?

  • Use Python 3 unless you have to use Python 2
  • There are almost no reasons left to use Python 2
  • Python 3 is stable, excellent, and well supported
  • Python 2 is the new COBOL

Why would I HAVE TO use Python 2

  • If you're working with a Python 2 legacy codebase.
  • If you ABSOLUTELY depend on a library that:
    • isn't ported to Python 3 AND
    • you can't just port yourself AND
    • there's no functional equivalent in Python 3

Writing cross-Python-platform software.

If you're writing a library, you can make it 2.7 and >3.3 compatible in the same codebase.

  • Libraries like six and python-future help a lot.
  • You end up writing an unpleasant subset of the language.
  • There's also the 2to3.py script.

Make Python 2 act like Python 3

At the module level, you can make Python 2 act a lot more like Python 3:

from __future__ import (
     division,         ## Make 3 / 2 == 1.5
     absolute_import,  ## New path syntax for importing modules
     print_function,   ## Replace keyword with the print() function
     unicode_literals  ## All "strings" are not implicitly u"strings"
)

If you're using Python 2.7, you should do this in all your modules.

The REPL (read-eval-print loop)

The REPL

Python 2

$ python
>>> print "Hello World!"
Hello World!
>>>

Python 3

$ python3
>>> print("Hello World!")
Hello World!
>>>

Getting help

Python is self documenting:

>>> help()

Welcome to Python 3.4!  This is the interactive help utility.

[...]

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>

Getting help

You can get help on any function, class, or module:

>>> help(str)

Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer

[... cont'd ...]

Getting help

Sometimes you don't need the full help(), just a hint:

>>> dir(str)

['__add__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__',
'__gt__', '__hash__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index',
'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier',
'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']

Getting help

[Use help() to look up the documentation for dir() and see what it's doing]

Built-in types

  • In Python, everything is an object.
  • All objects are an instance of a class/type.

Let's talk about the literal types (the ones that are built into the syntax of the language)

## These mean the same thing
>>> 1
1
>>> int(1)
1
>>> int("1")
1
- There used to be a difference between classes and types. It's not relevant anymore.

Boolean values (bool)

>>> True
True
>>> False
False
>>> True or False
True
>>> True and "Bob"
True
>>> bool("")
False
>>> bool("0")
False

Integers (int)

Integers are integers. You do integery things with them.

>>> 1
1
>>> 1000000000000000000000000
1000000000000000000000000
>>> 1000000000000000000000000 - 5
999999999999999999999995
>>> int("-17")
-17
- Integers won't overflow in Python

Floats (float)

Floats are double-precision floating point numbers.

>>> 3.0 / 2.0
1.5

Integers and Floats: Division

Careful: Division works differently in Python 2 and 3

In Python 3:

>>> 5 / 4
1.25

In Python 2:

>>> 5 / 4
1
>>> 5 / 4.0
1.25

Strings (Python 3)

  • Python gives you several ways to delimit a string.
  • In Python 3, strings are unicode.
  • You can delimit strings a whole bunch of ways.
'hi!'
"hi!"
'''hi!'''
"""hi!"""
'hi!'

... are all the same string

Lists

Lists are your general purpose ordered container type in Python.

>>> my_list = ["one", "two", "three"]
>>> my_list.append(4.0)
>>> print(my_list)
['one', 'two', 'three', 4.0]
  • Lists can have mixed types in them, but this is almost always a bad idea.

Dictionaries

Dictionaries are your key value store/hash table.

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098'
  • Any immutable type can be the key.
  • Dictionaries are fundamental to Python's internals.
  • You can solve most of your computational data structure needs with clever use of lists and dictionaries.
  • Even so, there are way way more data types.

Sets

Imagine a dictionary that is 'keys only'.

  • Contains immutable types.
  • Only ever has one of each value.
  • Can do set operations (intersections etc) quickly.
  • Surprisingly handy in a lot of places.

Tuples and named tuples

Whitespace and indentation

In Python, blocks of code are delimited by indentation of whitespace.

>>> if 1 >= 0:
...     print("Well, obviously")
... else:
...     print("Wait, what?")
...
Well, obviously
  • Indentation is always prefaced by a colon.
  • In practice, you will always use indentation delimited by four spaces.

Line continuations

Long lines can be broken up with a \

>>> 1 + 2 + 3 + 4 + 5 + \
... 6 + 7 + 8 + 9 + 0
45

Long lines are almost always broken up using parentheses, brackets, or braces.

>>> (1 + 2 + 3 + 4 + 5 +
...  6 + 7 + 8 + 9 + 0)
45

Line continuations

The indentation of a continued line is ignored, except stylistically:

foo = long_function_name(var_one, var_two,
                         var_three, var_four)

Language features

For loops

While loops

Functions

Ternery operators

Classes

Generators

Decorators

Exceptions

Docstrings

  • An unassigned string literal at the VERY TOP of a module, class, or function.

List comprehensions

Part 2: The Python environment

  • Python 3 vs Python 2
  • How to write a Python program
  • How to write a Python project
  • What on earth is a 'virtualenv'?
  • What on earth is 'WSGI'?

Python 3 Vs Python 2

  • We've already covered this.
  • We can talk about availability?

Modules

  • What is a .py file, really?
  • What is a .pyc file, really?
  • What happens when you directly execute a .py file?
  • What happens when you don't?

Modules

#!/usr/bin/env python3

def main():
    print("Hello World!")

if __name__ == "__main__":
   main()
  • Why is this the standard boilerplate?

Modules

  • Importing a module executes the file.
  • So you want to stick to variable, class, and function definitions.
  • __name__ is set to the name of the module, EXCEPT...

Whacky ways of importing modules

Packages

  • A package is a directory full of Python modules.
    • Or sub-packages.
    • Or data files.
  • It must* have a file called __init__.py in it.
  • __init__.py doesn't have to have any code in it.

What does a CPython install look like?

  • (First, what is CPython?)

Where do libraries end up living?

System libraries are in...

/usr/lib/pythonX.Y/

3rd party libraries in

/usr/lib/pythonX.Y/site-packages/

Or maybe in

/usr/local/lib/pythonX.Y/site-packages/

Virtualenvs

If everything you need is in the standard library, or in Ubuntu/Debian package distributions, yay for you!

If not, your options are to install libraries system-wide in /usr/local or site-packages, or...

... use a virtualenv.

Setting up a virtualenv

$ virtualenv my_venv
New python executable in my_venv/bin/python
Installing setuptools, pip...done.
$ tree -d my_venv/
my_venv/
├── bin
├── include
│   └── python2.7 -> /usr/include/python2.7
├── lib
│   └── python2.7
│       ├── distutils
│       └── site-packages
│           ├── pip
│           ├── pip-1.5.4.dist-info
│           ├── setuptools
│           └── setuptools-2.2.dist-info
└── local
    ├── bin -> /home/tom/my_venv/bin
    ├── include -> /home/tom/my_venv/include
    └── lib -> /home/tom/my_venv/lib

Activate that virtualenv

$ source my_venv/bin/activate
(my_venv) $

(Note the altered command prompt)

(my_venv) $ which python
/home/tom/my_venv/bin/python

(my_venv) $ which pip
/home/tom/my_venv/bin/pip

Installing packages into your activated virtualenv

(my_venv) $ pip install --use-wheel django
Downloading/unpacking django
  Downloading Django-1.7.7-py2.py3-none-any.whl (7.4MB): 7.4MB downloaded
Installing collected packages: django
Successfully installed django
Cleaning up...

Now you have your own python environment in which you can use Django.

If you don't want to (or can't) source the environment file you can run the python binary directly:

$ /home/tom/my_venv/bin/python <FILE>

As of Python 3.3, virtualenvs (renamed 'venv') are a feature of the standard library.

$ python3.4 -m venv my_venv --without-pip

On Ubuntu Trusty, you have to include --without-pip and install pip yourself with get-pip.py

Other useful facts about virtualenvs:

  • Specify the path to the python binary you want a virtualenv for (e.g. python2 or python3)
  • You can optionally include 'system' installed libraries, or treat it completely separately.
  • They hardwire paths internally, you can't zip them up and move them around.
  • virtualenvwrapper is super handy if you work with virtualenvs a lot (not for deployments)

Creating Python Packages

The messy past

  • distutils is deprecated
  • distribute is deprecated
  • setuptools < 0.6 is deprecated
  • buildout is... unconventional
  • eggs are deprecated
  • The documentation/HOWTOs are all LIES!

So what are you supposed to use?

So what are you supposed to use?

This page has all you need:

https://packaging.python.org/en/latest/current.html

What's a "setup.py"?

Part 3: The Python ecosystem

  • A tour of the standard library
  • The third-party libraries everyone uses
  • How to use the Python Package Index (PyPI)

A tour of the standard library

  • Python's standard library is famously handy.
  • No new libraries are being added to 2.7 anymore
    • (But lots of great Python 3 libraries are backported and available on PyPI)

Catalyst

Your presentation title

Presented by Name

Title goes here

Large title

This will only display in the notes window.

Title

List title

  • List item
  • List item
  • List item

Fragmented list

  • List item
  • List item
  • List item

Title (press down to see vertical slides)

Paragraph

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.

Blockquote

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.

Nested lists

  • One
  • Two
  • Three
    • Nested One
    • Nested Two

Title

Some text

function linkify( selector ) {
    if( supports3DTransforms ) {

        var nodes = document.querySelectorAll( selector );

        for( var i = 0, len = nodes.length; i < len; i++ ) {
            var node = nodes[i];

            if( !node.className ) {
                node.className += ' roll';
            }
        }
    }
}

Image backgrounds

open source technologists

Catalyst Python for Perl developers Presented by Tom Eastman