A talk given at PHP Cambridge all about Python
The slides cover Python from any other programmer's prospective - but the talk as given involved comparisons to PHP.
1. Python for PHP Developers
@ben_nuttall
Raspberry Pi Foundation
2. About me
● Education Developer Advocate for Raspberry Pi Foundation
– Developer & maintainer of www.raspberrypi.org
– Education – teacher training & learning resources
– Outreach – open source, education & programming conferences
● From Sheffield
● BSc Mathematics & Computing in Manchester (MMU)
● Lived in Cambridge since late 2013
● Interested in programming, open source, Linux
3. About Raspberry Pi
● Family of affordable single board computers
– ~£15 700MHz single core 256MB RAM
– ~£25 900MHz quad core 1GB RAM
● Designed for use in education
● Used in education, industry and by hobbyists
● We're a charity (UK charity 1129409)
● Founded and based in Cambridge
● Staff of < 20
● Raspberry Pi manufactured in Pencoed, Wales (not China)
● Sold 6 million units since 2012 launch
4. What this talk is not
PHP
● $a = 1;
● function foo() {
return “bar”;
}
● T_PAAMAYIM_NEKUDOTAYIM
Python
● a = 1
● def foo():
return “bar”
● ???
5. What this talk is also not
YOU ARE ALL IDIOTS YOU
SHOULD BE USING PYTHON NOT
PHP IT'S NOT EVEN A REAL
LANGUAGE IT'S SO
INCONSISTENT I DON'T EVEN
6. What this talk is
● Examples of Python
● What makes Python code Pythonic
● How to think like a Python programmer
● Python Idioms
● Practical Python – frameworks, libraries, infrastructure
7. About Python
● General purpose high-level programming language
● Created in 1991 by Guido van Rossum
● Cross-platform
● Implemented in C (alternatives: Java, Python, C#)
● Multi-paradigm (OO, Imperative, Functional, Procedural)
● Dynamic type
● Designed for readability
8. Python is for...
● Web programming (Django, Pyramid, Bottle, Flask...)
● GUI development (wxPython, tkInter, PyGtk, PyQt...)
● Scientific and Numeric (SciPy, NumPy, Pandas...)
● Software development (Buildbot, Trac, Roundup...)
● System Administration (Ansible, Salt, OpenStack...)
● Embedded computing (Raspberry Pi, MicroPython, BeagleBone...)
● Education (Raspberry Pi, Turtle, Robotics...)
9. Why Python?
● Professional and powerful modern language
● Focus on readability
● Strong community
● Good documentation
● Flexible
● Full stack
10. Python 2 or Python 3?
● Python 3 was released in 2008, its current version is 3.4
● Python 2 is considered legacy, its EOL is 2020
– No more major revisions (2.7.x – no 2.8)
– However, everyone still uses it
● Python 3 is the present and future of the language
● Python 3 contains some nice new features
– But apparently not different enough for people to bother to change
– What version of PHP are you currently using in production? My guess: 5.3
● Some libraries don't support Python 3 yet
● Examples in this presentation are for Python 3
11. Which version do I have?
● Linux (including Raspberry Pi):
– python is Python 2
– python3 is Python 3
– (except Arch Linux – rebels)
● Mac:
– Python 2 pre-installed, Python 3 available from python.org/downloads
● Windows:
– Download either or both from python.org/downloads
16. Keywords
● False
● None
● True
● and
● as
● assert
● break
● class
● continue
● def
● del
● elif
● else
● except
● finally
● for
● from
● global
● if
● import
● in
● is
● lambda
● nonlocal
● not
● or
● pass
● raise
● return
● try
● while
● with
● yield
17. Built-in functions
● abs
● all
● any
● ascii
● bin
● bool
● bytearray
● bytes
● callable
● chr
● classmethod
● compile
● complex
● delattr
● dict
● dir
● divmod
● enumerate
● eval
● exec
● filter
● float
● format
● frozenset
● getattr
● globals
● hasattr
● hash
● help
● hex
● id
● input
● int
● isinstance
● issubclass
● iter
● len
● list
● locals
● map
● max
● memoryview
● min
● next
● object
● oct
● open
● ord
● pow
● print
● property
● range
● repr
● reversed
● round
● set
● setattr
● slice
● sorted
● staticmethod
● str
● sum
● super
● tuple
● type
● vars
● zip
18. Import
● import time
● from time import sleep
● from picamera import
PiCamera
● Import the whole time module,
namespaced as time
● Import only the sleep function
from time module
● Import only the PiCamera class
from the picamera module
19. Import
● from datetime import
datetime, timedelta
● import numpy as np
● from numpy import *
● Import only the datetime and
timedelta functions from the
datetime module
● Import the numpy module,
namespaced as np
● Import all objects from numpy
module, polluting the namespace
(don't do this)
39. functools & itertools
● functools - for higher-order functions: functions that act on or
return other functions
● itertools - a number of iterator building blocks inspired by
constructs from APL, Haskell, and SML, each recast in a form
suitable for Python
– product
– combinations
– permutations
47. The Zen of Python
● 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!
48. Python Idioms
● “The specific grammatical, syntactic, and structural character of
a given language”
● “A commonly used and understood way of expressing a fact,
idea or intention.”
Examples by Safe Hammad
http://safehammad.com/downloads/python-idioms-2014-01-16.pdf
49. Python Idioms
● "Programs must be written for people to read, and only incidentally for machines to execute."
- Abelson & Sussman, SICP
● “There should be one - and preferably only one - obvious way to do it.”
- The Zen of Python
● The use of commonly understood syntax or coding constructs can aid readability and clarity.
● Some idioms can be faster or use less memory than their “non-idiomatic” counterparts.
● Python's idioms can make your code Pythonic!
50. Make a script both importable and executable
if __name__ == '__main__':
main()
55. in – iteration (list)
people = [“Alice”, “Bob”, “Charlie”]
# GOOD
for name in people:
print(name)
# BAD
for i in range(len(people)):
print(people[i])
56. in – iteration (dictionary)
people = {“Alice”: 23, “Bob”: 21, “Charlie”: 30}
# GOOD
for name, age in people.items():
print(“%s is %i” % (name, age))
# BAD
for name in people:
print(“%s is %i” % (name, people[name]))
65. Exceptions – patch to work in Python 2 and 3
try:
input = raw_input
except NameError:
pass
66. Exceptions – patch to work in Python 2 and 3
from __future__ import (
unicode_literals,
print_function,
division,
absolute_import,
)
# Make Py2's str and range equivalent to Py3's
str = type('')
try:
range = xrange
except NameError:
pass
69. PyPi: Python Packaging Index
● Free-for-all upload of Python packages and modules
● Namespace based
● Browsable online
● Easy to upload & update
● Easy to download
● Easy to install & upgrade
70. What a Python package looks like
├── energenie
│ ├── energenie.py
│ └── __init__.py
└── setup.py
71. Write in C - optional
● Python modules can be written in C for optimal speed
73. Virtualenv
● Isolated environment for running an appplication with specific
version dependencies
● Run multiple apps requiring different versions of libraries
● Use pip to install within a virtualenv
74. Secrets from the Future
● from __future__ import print_function, division
Bring Python 3 features into Python 2
75. 2to3
● Convert a Python file, set of files or module from Python 2 to
Python 3 syntax
– Often trivial
– Sometimes requires manual intervention
– Dry run to see suggested changes first
77. Community
● PyCon
– PyCon (Montreal)
– PyConUK (Coventry)
– EuroPython (Bilbao)
– PyCon Ireland (Dublin)
– EuroSciPy (Cambridge)
– Many more!
● User groups & organisations
– Campug
– London Python Dojo
– PyLadies
– Django Girls
– Python Software Foundation
78. Further reading
● Why Python is a Great First Language
http://blog.trinket.io/why-python/
● Python Success Stories
https://www.python.org/about/success/
● Python in Education
http://www.oreilly.com/programming/free/python-in-education.
csp