Python
Getting started
Environment
Interpreter
- cython
- jython
- pypy
Python 2
2.7 ~ jul 2010
print "foo"
<>
u"foo"
class C:
__metaclass__ = M
except Exception, e:
Python 3
3.4 ~ mar 2014
print("foo")
!=
"foo"
class C(metaclass=M):
except Exception as e:
PIP
$ apt-get install python-pip
$ pip install ansible
$ pip install git+https://github.com/x/y.git@branch
$ pip install ./
http://pypi.python.org
http://rtfd.org
setup.py
#!/usr/bin/env python
import os
import sys
from glob import glob
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='michael@ansible.com',
url='http://ansible.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML", 'setuptools', 'pycrypto >= 2.6'],
package_dir={ 'ansible': 'lib/ansible' },
packages=find_packages('lib'),
package_data={
'': ['module_utils/*.ps1', 'modules/core/windows/*.ps1', 'modules/extras/windows/*.ps1'],
},
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy',
'bin/ansible-vault',
],
data_files=[],
)
Virtualenv
$ pip install virtualenvwrapper
$ source /usr/local/bin/virtualenvwrapper.sh
$ pip freeze
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1
$ mkvirtualenv projectA
(projectA) $ pip install fabric
(projectA) $ pip freeze
Fabric==1.10.0
ecdsa==0.11
paramiko==1.15.1
pycrypto==2.6.1
(projectA) $ deactivate
$ pip freeze
virtualenv==1.11.6
virtualenv-clone==0.2.5
virtualenvwrapper==4.3.1
$ workon projectA
(projectA) $
Code
int = 0
string = "foo" + 'bar'
bool = False
def great(name):
return "Hello %s" % name
class MyObject(ParentA, ParentB):
"""This is my Object
"""
def __init__(self, foo):
self.foo = foo
def a_method(self, default_value, flag = True):
"""Class contructor
:param default_value:
:type default_value: str
:returns: Something
:rtpye: str
"""
if flag:
return self.foo
return default_value
def __private(self):
pass
def _protected(self):
pass
def public(self):
pass
@staticmethod
def static_method(x):
pass
@property
def my_property(self):
return self._my_property
Doc
def multiply(a, b):
"""
>>> multiply(4, 3)
12
>>> multiply('a', 3)
'aaa'
"""
return a * b
if __name__ == "__main__":
import doctest
doctest.testmod()
def foo():
"""This is the foo method
"""
pass
print(foo.__doc__)
Operators
1 + 1 == 2
"A" + "B" == "AB"
"A" * 3 == "AAA"
"Hello %s" % "Sensiolabs" == "Hello Sensiolabs"
"Hello %s %s" % ("John", "Doe") == "Hello John Doe"
isA or isB
isA and isB
"foo bar"[2:5] == "o b"
"foo bar"[-2] == "a"
"foo bar"[4:] == " bar"
"foo bar"[:-1] == "foo ba"
my_tupple = ("A", "B")
Array
my_set = set({"a": "A", "b": "B"})
my_dict = {"a": "A", "b": "B"}
my_dict = dict([("a", "A"), ("b", "B")])
my_dict["c"] = "C"
my_list = ["A", "B"]
my_list = list(my_tupple)
my_list.append("C")
for
lst = range(10)
doubled = [ num * 2 for num in lst ]
even = [ x for x in lst if x % 2 == 1 ]
odd_or_negative = [ x if not x % 2 else -x for x in lst ]
byte_sizes = [ "%i => %i" % (j, 256**j-1) for j in [ 1 << i for i in range(6) ] ]
for item in my_tupple:
print(item)
for key in my_dict.keys():
print(key)
for value in my_dict.values():
print(value)
for (key, value) in my_dict.items():
print(key, value)
square = lambda x: x**2
sorted_users = sorted(users, key=lambda user: user.age)
fib = lambda n: n if n < 2 else fib(n-1) + fib(n-2)
def make_printer(msg):
def printer(msg=msg):
print msg
return printer
printer = make_printer("Foo!")
printer()
lambda & Closures
Modules
# main.py
import module_a
import module_b
import os
print(os.path.dirname(__file__))
from os.path import dirname
print(dirname(__file__))
$ tree
.
├── main.py
├── module_a
│ └── __init__.py
└── module_b.py
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── models.py
├── urls.py
└── views.py
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── models
│ ├── __init__.py
│ ├── user.py
│ └── catalog.py
├── urls.py
└── views.py
NAMED Parameter
def info(object, spacing=10, collapse=1):
pass
info(object, collapse=2)
b = Blog(name='Foo', tagline='Bar')
Entry.objects.filter(
headline__startswith='What'
).exclude(
pub_date__gte=datetime.date.today()
).filter(
pub_date__gte=datetime(2005, 1, 30)
)
*args **kwargs
def foo(arg1, *args, **kwargs):
print(arg1)
print(args)
print(kwargs)
foo("A", "B", "C", bar = "D", baz = "E")
# A
# ('B', 'C')
# {'baz': 'E', 'bar': 'D'}
def foo(arg1, arg2):
pass
args = ["A", "B"]
foo(*args)
kwargs = {"arg1": "C", "arg2": "D"}
foo(**kwargs)
Decorator
def log_console(function):
def wrapper(*args, **kwargs):
result = function(*args, **kwargs)
print('Call func "{0}" with {1} and {2} returns: {3}'.format(
function.__name__, args, kwargs, result))
return result
return wrapper
@log_console
def addition(a, b):
return a+b
addition(1, 2)
# log_console(addition)(1, 2)
# Call func "addition" with (1, 2) and {} returns: 3
Context Manager
@contextmanager
def transaction(con):
con.begin_transaction()
try:
yield con
con.commit()
except Exception as e:
con.rollback()
raise
with transaction(con) as con:
con.execute(sql)
Method override
def my_len(string):
return 42
print(len("hello")) # 5
len = my_len
print(len("hello")) # 42
from mock import mock_open, patch
m = mock_open()
with patch('{}.open'.format(__name__), m, create=True):
with open('foo', 'w') as h:
h.write('some stuff')
m.assert_called_once_with('foo', 'w')
handle = m()
handle.write.assert_called_once_with('some stuff')
operator overloading
from functools import total_ordering
@total_ordering
class Person():
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def __eq__(self, other):
return (self.lastname, self.firstname) == (other.lastname, other.firstname)
def __lt__(self, other):
return (self.lastname, self.firstname) < (other.lastname, other.firstname)
print(Person("John", "Doe") == Person("Jane", "Doe"))
print(Person("John", "Doe") < Person("Jane", "Doe"))
print(Person("John", "Doe") > Person("Jane", "Doe"))
print(Person("John", "Doe") != Person("Jane", "Doe"))
# False
# False
# True
# True
Metaclass
class PropertyMetaclass(type):
def __init__(cls, name, bases, dict):
type.__init__(cls, name, bases, dict)
props = getattr(cls, '__properties__', {})
for name, default in props.items():
type(cls).create_property(cls, name, default)
def attr_name(cls, prop):
return '_%s'%prop
def create_property(cls, name, default):
getter=lambda self: getattr(self, cls.attr_name(name))
setter=lambda self, value: setattr(self, cls.attr_name(name), value)
prop=property(getter, setter, None, None)
setattr(cls, cls.attr_name(name), default)
setattr(cls, name, prop)
class Book(object, metaclass = PropertyMetaclass):
__properties__ = {
'author': '[unknown title]',
'title': '[unknown author]'
}
book = Book()
book.title = "I love python"
print(book.author)
Questions ?
Python
By Jérémy DERUSSÉ
Python
- 1,324