├── ch1
├── example
│ ├── run.py
│ ├── core.py
│ └── util
│ │ ├── db.py
│ │ ├── __init__.py
│ │ ├── math.py
│ │ └── network.py
├── files_only
│ ├── core.py
│ ├── db.py
│ ├── math.py
│ ├── run.py
│ └── network.py
├── scopes1.py
├── names.py
├── scopes2.py
├── scopes3.py
└── bike.py
├── ch4
├── lib
│ ├── __init__.py
│ └── funcdef.py
├── func_from.py
├── key.points.argument.passing.py
├── arguments.positional.py
├── arguments.keyword.py
├── func_import.py
├── arguments.defaults.mutable.no.trap.py
├── key.points.mutable.py
├── filter.lambda.py
├── key.points.assignment.py
├── matrix.multiplication.nofunc.py
├── vat.function.py
├── arguments.default.py
├── recursive.factorial.py
├── arguments.variable.keyword.py
├── return.none.py
├── arguments.variable.positional.unpacking.py
├── filter.regular.py
├── key.points.mutable.assignment.py
├── return.single.value.py
├── scoping.level.1.py
├── arguments.all.py
├── arguments.defaults.mutable.py
├── return.single.value.2.py
├── scoping.level.2.py
├── arguments.default.error.py
├── arguments.defaults.mutable.intermediate.call.py
├── matrix.multiplication.func.py
├── no.side.effects.py
├── scoping.level.2.global.py
├── scoping.level.2.nonlocal.py
├── vat.py
├── arguments.all.kwonly.py
├── arguments.variable.positional.py
├── arguments.variable.db.py
├── func.attributes.py
├── arguments.keyword.only.py
├── data.science.example.py
├── lambda.explained.py
├── return.multiple.py
├── docstrings.py
└── primes.py
├── ch10
├── regex
│ ├── regex
│ │ ├── __init__.py
│ │ ├── wsgi.py
│ │ ├── urls.py
│ │ └── settings.py
│ ├── entries
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── __init__.py
│ │ │ └── 0001_initial.py
│ │ ├── templates
│ │ │ └── entries
│ │ │ │ ├── footer.html
│ │ │ │ ├── insert.html
│ │ │ │ ├── home.html
│ │ │ │ ├── base.html
│ │ │ │ └── list.html
│ │ ├── forms.py
│ │ ├── models.py
│ │ ├── admin.py
│ │ ├── static
│ │ │ └── entries
│ │ │ │ └── css
│ │ │ │ └── main.css
│ │ └── views.py
│ ├── db.sqlite3
│ └── manage.py
├── flask
│ ├── templates
│ │ └── main.html
│ └── main.py
└── falcon
│ ├── main.py
│ ├── stress.py
│ └── quotes.py
├── ch12
├── pwdweb
│ ├── pwdweb
│ │ ├── __init__.py
│ │ ├── wsgi.py
│ │ ├── urls.py
│ │ └── settings.py
│ ├── records
│ │ ├── __init__.py
│ │ ├── migrations
│ │ │ ├── __init__.py
│ │ │ └── 0001_initial.py
│ │ ├── templates
│ │ │ └── records
│ │ │ │ ├── footer.html
│ │ │ │ ├── messages.html
│ │ │ │ ├── home.html
│ │ │ │ ├── record_confirm_delete.html
│ │ │ │ ├── base.html
│ │ │ │ ├── list.html
│ │ │ │ └── record_add_edit.html
│ │ ├── admin.py
│ │ ├── templatetags
│ │ │ └── record_extras.py
│ │ ├── forms.py
│ │ ├── static
│ │ │ └── records
│ │ │ │ ├── css
│ │ │ │ └── main.css
│ │ │ │ └── js
│ │ │ │ └── api.js
│ │ ├── urls.py
│ │ ├── models.py
│ │ └── views.py
│ ├── db.sqlite3
│ └── manage.py
└── pwdapi
│ ├── main.py
│ ├── core
│ ├── handlers.py
│ └── passwords.py
│ └── tests
│ └── test_core
│ ├── test_handlers.py
│ └── test_passwords.py
├── requirements
├── requirements_dev.txt
├── requirements_test.in
├── requirements.in
├── requirements_test.txt
└── requirements.txt
├── README.pdf
├── ch11
├── traceback_simple.py
├── assertions.py
├── custom.py
├── traceback_validator.py
├── ipdebugger.py
├── custom_timestamp.py
├── ipdebugger_ipdb.py
└── log.py
├── ch3
├── conditional.1.py
├── permutations.py
├── simple.for.3.py
├── simple.for.py
├── simple.for.4.py
├── conditional.2.py
├── multiple.sequences.zip.py
├── infinite.py
├── multiple.sequences.enumerate.py
├── simple.for.2.py
├── multiple.sequences.py
├── primes.else.py
├── binary.2.py
├── multiple.sequences.while.py
├── multiple.sequences.explicit.py
├── range.py
├── multiple.sequences.implicit.py
├── ternary.py
├── for.else.py
├── taxes.py
├── switch.py
├── compress.py
├── for.no.else.py
├── switch.js
├── any.py
├── primes.py
├── binary.py
├── discount.py
├── coupons.dict.py
├── errorsalert.py
└── coupons.py
├── ch5
├── scopes.for.py
├── scopes.noglobal.py
├── gen.filter.py
├── gen.yield.from.py
├── squares.comprehension.py
├── functions.py
├── gen.yield.for.py
├── sum.example.py
├── pairs.list.comprehension.py
├── squares.py
├── dictionary.comprehensions.duplicates.py
├── dictionary.comprehensions.positions.py
├── sum.example.2.py
├── gen.map.py
├── pairs.for.loop.py
├── set.comprehensions.py
├── maxims.py
├── gen.send.preparation.py
├── dictionary.comprehensions.py
├── even.squares.py
├── gen.send.preparation.stop.py
├── filter.py
├── first.n.squares.py
├── fibonacci.elegant.py
├── gen.map.filter.py
├── gen.yield.return.py
├── scopes.py
├── gen.send.py
├── pythagorean.triple.comprehension.py
├── pythagorean.triple.py
├── fibonacci.first.py
├── zip.grades.py
├── fibonacci.second.py
├── pythagorean.triple.int.py
├── first.n.squares.manual.method.py
├── squares.map.py
├── performances.map.py
├── first.n.squares.manual.py
├── pythagorean.triple.generation.py
├── generator.expressions.py
├── pythagorean.triple.generation.for.py
├── map.example.py
├── decorate.sort.undecorate.py
└── performances.py
├── ch8
├── simple_server
│ ├── serve.sh
│ ├── img
│ │ ├── owl-book.png
│ │ ├── owl-books.png
│ │ ├── owl-ebook.jpg
│ │ ├── owl-rose.jpeg
│ │ └── owl-alcohol.png
│ └── index.html
├── scrape.py
└── guiscrape.py
├── ch7
├── data.py
├── exceptions
│ ├── json.example.py
│ ├── multiple.except.py
│ ├── try.syntax.py
│ ├── for.loop.py
│ └── first.example.py
├── filter_funcs_triangulation.py
├── filter_funcs.py
├── filter_funcs_refactored.py
├── data_flatten.py
└── profiling
│ └── triples.py
├── ch2
├── README.md
├── bytearray.py
├── objects.py
├── defaultdict.py
├── tuples.py
├── namedtuple.py
├── chainmap.py
├── final_considerations.py
├── sets.py
├── sequences.py
├── lists.py
├── dicts.py
└── numbers.py
├── ch6
├── decorators
│ ├── time.measure.start.py
│ ├── time.measure.dry.py
│ ├── time.measure.arguments.py
│ ├── time.measure.deco1.py
│ ├── time.measure.deco2.py
│ ├── decorators.factory.py
│ ├── syntax.py
│ └── two.decorators.py
├── oop
│ ├── class.self.py
│ ├── simplest.class.py
│ ├── class.init.py
│ ├── class.price.py
│ ├── mro.py
│ ├── super.duplication.py
│ ├── mro.simple.py
│ ├── operator.overloading.py
│ ├── class.methods.factory.py
│ ├── private.attrs.py
│ ├── class.attribute.shadowing.py
│ ├── private.attrs.fixed.py
│ ├── super.explicit.py
│ ├── class.namespaces.py
│ ├── super.implicit.py
│ ├── class.methods.split.py
│ ├── property.py
│ ├── static.methods.py
│ ├── class.inheritance.py
│ ├── multiple.inheritance.py
│ └── class.issubclass.isinstance.py
└── iterators
│ └── iterator.py
├── tests
└── test_ch7
│ ├── test_filter_funcs_final.py
│ ├── test_filter_funcs_final_triangulation.py
│ ├── test_filter_funcs_is_positive_correct.py
│ ├── test_filter_funcs_is_positive_better.py
│ ├── test_filter_funcs_is_positive_loose.py
│ ├── test_filter_funcs_refactored.py
│ ├── test_filter_funcs.py
│ └── test_data_flatten.py
├── LICENSE
├── ch9
└── example.ipynb
└── README.md
/ch1/example/run.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/example/core.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/example/util/db.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/files_only/core.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/files_only/db.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/files_only/math.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/files_only/run.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch4/lib/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/example/util/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/example/util/math.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/example/util/network.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch1/files_only/network.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch10/regex/regex/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch10/regex/entries/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch12/pwdweb/pwdweb/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch10/regex/entries/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/migrations/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/requirements/requirements_dev.txt:
--------------------------------------------------------------------------------
1 | ipdb
2 |
--------------------------------------------------------------------------------
/requirements/requirements_test.in:
--------------------------------------------------------------------------------
1 | nose
2 | nose-parameterized
3 |
--------------------------------------------------------------------------------
/README.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/README.pdf
--------------------------------------------------------------------------------
/ch11/traceback_simple.py:
--------------------------------------------------------------------------------
1 | d = {'some': 'key'}
2 | key = 'some-other'
3 | print(d[key])
4 |
--------------------------------------------------------------------------------
/ch3/conditional.1.py:
--------------------------------------------------------------------------------
1 | late = True
2 | if late:
3 | print('I need to call my manager!')
4 |
--------------------------------------------------------------------------------
/ch3/permutations.py:
--------------------------------------------------------------------------------
1 | from itertools import permutations
2 | print(list(permutations('ABC')))
3 |
--------------------------------------------------------------------------------
/ch4/func_from.py:
--------------------------------------------------------------------------------
1 | from lib.funcdef import square, cube
2 |
3 | print(square(10))
4 | print(cube(10))
5 |
--------------------------------------------------------------------------------
/ch4/key.points.argument.passing.py:
--------------------------------------------------------------------------------
1 | x = 3
2 | def func(y):
3 | print(y)
4 |
5 | func(x) # prints: 3
6 |
--------------------------------------------------------------------------------
/ch4/lib/funcdef.py:
--------------------------------------------------------------------------------
1 | def square(n):
2 | return n ** 2
3 |
4 |
5 | def cube(n):
6 | return n ** 3
7 |
--------------------------------------------------------------------------------
/ch10/regex/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch10/regex/db.sqlite3
--------------------------------------------------------------------------------
/ch12/pwdweb/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch12/pwdweb/db.sqlite3
--------------------------------------------------------------------------------
/ch4/arguments.positional.py:
--------------------------------------------------------------------------------
1 | def func(a, b, c):
2 | print(a, b, c)
3 |
4 | func(1, 2, 3) # prints: 1 2 3
5 |
--------------------------------------------------------------------------------
/ch5/scopes.for.py:
--------------------------------------------------------------------------------
1 | s = 0
2 | for A in range(5):
3 | s += A
4 | print(A) # prints: 4
5 | print(globals())
6 |
--------------------------------------------------------------------------------
/ch5/scopes.noglobal.py:
--------------------------------------------------------------------------------
1 | ex1 = [A for A in range(5)]
2 | print(A) # breaks: NameError: name 'A' is not defined
3 |
--------------------------------------------------------------------------------
/ch8/simple_server/serve.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | # start a simple HTTP Server
4 | python -m http.server 8000
5 |
--------------------------------------------------------------------------------
/ch3/simple.for.3.py:
--------------------------------------------------------------------------------
1 | surnames = ['Rivest', 'Shamir', 'Adleman']
2 | for surname in surnames:
3 | print(surname)
4 |
--------------------------------------------------------------------------------
/ch4/arguments.keyword.py:
--------------------------------------------------------------------------------
1 | def func(a, b, c):
2 | print(a, b, c)
3 |
4 | func(a=1, c=2, b=3) # prints: 1 3 2
5 |
--------------------------------------------------------------------------------
/ch4/func_import.py:
--------------------------------------------------------------------------------
1 | import lib.funcdef
2 |
3 |
4 | print(lib.funcdef.square(10))
5 | print(lib.funcdef.cube(10))
6 |
--------------------------------------------------------------------------------
/ch10/regex/entries/templates/entries/footer.html:
--------------------------------------------------------------------------------
1 |
4 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templates/records/footer.html:
--------------------------------------------------------------------------------
1 |
4 |
--------------------------------------------------------------------------------
/ch3/simple.for.py:
--------------------------------------------------------------------------------
1 | for number in [0, 1, 2, 3, 4]:
2 | print(number)
3 |
4 |
5 | for number in range(5):
6 | print(number)
7 |
--------------------------------------------------------------------------------
/ch8/simple_server/img/owl-book.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch8/simple_server/img/owl-book.png
--------------------------------------------------------------------------------
/ch8/simple_server/img/owl-books.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch8/simple_server/img/owl-books.png
--------------------------------------------------------------------------------
/ch8/simple_server/img/owl-ebook.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch8/simple_server/img/owl-ebook.jpg
--------------------------------------------------------------------------------
/ch8/simple_server/img/owl-rose.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch8/simple_server/img/owl-rose.jpeg
--------------------------------------------------------------------------------
/ch8/simple_server/img/owl-alcohol.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PacktPublishing/Learning-Python/HEAD/ch8/simple_server/img/owl-alcohol.png
--------------------------------------------------------------------------------
/ch4/arguments.defaults.mutable.no.trap.py:
--------------------------------------------------------------------------------
1 | def func(a=None):
2 | if a is None:
3 | a = []
4 | # do whatever you want with `a` ...
5 |
--------------------------------------------------------------------------------
/ch3/simple.for.4.py:
--------------------------------------------------------------------------------
1 | surnames = ['Rivest', 'Shamir', 'Adleman']
2 | for position, surname in enumerate(surnames):
3 | print(position, surname)
4 |
--------------------------------------------------------------------------------
/ch4/key.points.mutable.py:
--------------------------------------------------------------------------------
1 | x = [1, 2, 3]
2 | def func(x):
3 | x[1] = 42 # this affects the caller!
4 |
5 | func(x)
6 | print(x) # prints: [1, 42, 3]
7 |
--------------------------------------------------------------------------------
/ch7/data.py:
--------------------------------------------------------------------------------
1 | def get_clean_data(source):
2 |
3 | data = load_data(source)
4 | cleaned_data = clean_data(data)
5 |
6 | return cleaned_data
7 |
--------------------------------------------------------------------------------
/ch3/conditional.2.py:
--------------------------------------------------------------------------------
1 | late = False
2 | if late:
3 | print('I need to call my manager!') #1
4 | else:
5 | print('no need to call my manager...') #2
6 |
--------------------------------------------------------------------------------
/ch4/filter.lambda.py:
--------------------------------------------------------------------------------
1 | def get_multiples_of_five(n):
2 | return list(filter(lambda k: not k % 5, range(n)))
3 |
4 |
5 | print(get_multiples_of_five(50))
6 |
--------------------------------------------------------------------------------
/ch4/key.points.assignment.py:
--------------------------------------------------------------------------------
1 | x = 3
2 | def func(x):
3 | x = 7 # defining a local x, not changing the global one
4 |
5 | func(x)
6 | print(x) # prints: 3
7 |
--------------------------------------------------------------------------------
/ch5/gen.filter.py:
--------------------------------------------------------------------------------
1 | cubes = [x**3 for x in range(10)]
2 |
3 | odd_cubes1 = filter(lambda cube: cube % 2, cubes)
4 | odd_cubes2 = (cube for cube in cubes if cube % 2)
5 |
--------------------------------------------------------------------------------
/ch5/gen.yield.from.py:
--------------------------------------------------------------------------------
1 | def print_squares(start, end):
2 | yield from (n ** 2 for n in range(start, end))
3 |
4 | for n in print_squares(2, 5):
5 | print(n)
6 |
--------------------------------------------------------------------------------
/ch5/squares.comprehension.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> [n ** 2 for n in range(10)]
4 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
5 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.zip.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | for person, age in zip(people, ages):
4 | print(person, age)
5 |
--------------------------------------------------------------------------------
/ch5/functions.py:
--------------------------------------------------------------------------------
1 |
2 | def gcd(a, b):
3 | """Calculate the Greatest Common Divisor of (a, b). """
4 | while b != 0:
5 | a, b = b, a % b
6 | return a
7 |
--------------------------------------------------------------------------------
/ch5/gen.yield.for.py:
--------------------------------------------------------------------------------
1 | def print_squares(start, end):
2 | for n in range(start, end):
3 | yield n ** 2
4 |
5 | for n in print_squares(2, 5):
6 | print(n)
7 |
--------------------------------------------------------------------------------
/ch5/sum.example.py:
--------------------------------------------------------------------------------
1 | s1 = sum([n**2 for n in range(10**6)])
2 | s2 = sum((n**2 for n in range(10**6)))
3 | s3 = sum(n**2 for n in range(10**6))
4 |
5 | print(s1==s2==s3)
6 |
--------------------------------------------------------------------------------
/ch5/pairs.list.comprehension.py:
--------------------------------------------------------------------------------
1 |
2 | items = 'ABCDE'
3 | pairs = [(items[a], items[b])
4 | for a in range(len(items)) for b in range(a, len(items))]
5 |
6 | print(pairs)
7 |
--------------------------------------------------------------------------------
/ch5/squares.py:
--------------------------------------------------------------------------------
1 | def square1(n):
2 | return n ** 2 # squaring through the power operator
3 |
4 | def square2(n):
5 | return n * n # squaring through multiplication
6 |
--------------------------------------------------------------------------------
/ch4/matrix.multiplication.nofunc.py:
--------------------------------------------------------------------------------
1 | a = [[1, 2], [3, 4]]
2 | b = [[5, 1], [2, 1]]
3 |
4 | c = [[sum(i * j for i, j in zip(r, c)) for c in zip(*b)]
5 | for r in a]
6 | print(c)
7 |
--------------------------------------------------------------------------------
/ch5/dictionary.comprehensions.duplicates.py:
--------------------------------------------------------------------------------
1 | word = 'Hello'
2 |
3 | swaps = {c: c.swapcase() for c in word}
4 |
5 | print(swaps) # prints: {'o': 'O', 'l': 'L', 'e': 'E', 'H': 'h'}
6 |
--------------------------------------------------------------------------------
/ch5/dictionary.comprehensions.positions.py:
--------------------------------------------------------------------------------
1 | word = 'Hello'
2 |
3 | positions = {c: k for k, c in enumerate(word)}
4 |
5 | print(positions) # prints: {'l': 3, 'o': 4, 'e': 1, 'H': 0}
6 |
--------------------------------------------------------------------------------
/ch5/sum.example.2.py:
--------------------------------------------------------------------------------
1 | s = sum([n**2 for n in range(10**8)]) # this is killed
2 | s = sum(n**2 for n in range(10**8)) # this succeeds
3 |
4 | print(s) # prints: 333333328333333350000000
5 |
--------------------------------------------------------------------------------
/ch11/assertions.py:
--------------------------------------------------------------------------------
1 | mylist = [1, 2, 3] # this ideally comes from some place
2 |
3 | assert 4 == len(mylist) # this will break
4 |
5 | for position in range(4):
6 | print(mylist[position])
7 |
--------------------------------------------------------------------------------
/ch3/infinite.py:
--------------------------------------------------------------------------------
1 | from itertools import count
2 |
3 | for n in count(5, 3):
4 | if n > 20:
5 | break
6 | print(n, end=', ') # instead of newline, comma and space
7 |
8 | print()
9 |
--------------------------------------------------------------------------------
/ch4/vat.function.py:
--------------------------------------------------------------------------------
1 | def calculate_price_with_vat(price, vat):
2 | return price * (100 + vat) / 100
3 |
4 |
5 | if __name__ == "__main__":
6 | print(calculate_price_with_vat(100, 20))
7 |
--------------------------------------------------------------------------------
/ch5/gen.map.py:
--------------------------------------------------------------------------------
1 | def adder(*n):
2 | return sum(n)
3 |
4 | s1 = sum(map(lambda n: adder(*n), zip(range(100), range(1, 101))))
5 | s2 = sum(adder(*n) for n in zip(range(100), range(1, 101)))
6 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templates/records/messages.html:
--------------------------------------------------------------------------------
1 | {% if messages %}
2 | {% for message in messages %}
3 | {{ message }}
4 | {% endfor %}
5 | {% endif %}
6 |
--------------------------------------------------------------------------------
/ch4/arguments.default.py:
--------------------------------------------------------------------------------
1 | def func(a, b=4, c=88):
2 | print(a, b, c)
3 |
4 | func(1) # prints: 1 4 88
5 | func(b=5, a=7, c=9) # prints: 7 5 9
6 | func(42, c=9) # prints: 42 4 9
7 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.enumerate.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | for position, person in enumerate(people):
4 | age = ages[position]
5 | print(person, age)
6 |
--------------------------------------------------------------------------------
/ch4/recursive.factorial.py:
--------------------------------------------------------------------------------
1 | def factorial(n):
2 | if n in (0, 1): # base case
3 | return 1
4 | return factorial(n - 1) * n # recursive case
5 |
6 |
7 | print([factorial(n) for n in range(10)])
8 |
--------------------------------------------------------------------------------
/ch5/pairs.for.loop.py:
--------------------------------------------------------------------------------
1 |
2 | items = 'ABCDE'
3 | pairs = []
4 |
5 | for a in range(len(items)):
6 | for b in range(a, len(items)):
7 | pairs.append((items[a], items[b]))
8 |
9 | print(pairs)
10 |
--------------------------------------------------------------------------------
/ch5/set.comprehensions.py:
--------------------------------------------------------------------------------
1 | word = 'Hello'
2 |
3 | letters1 = set(c for c in word)
4 | letters2 = {c for c in word}
5 | print(letters1) # prints: {'l', 'o', 'H', 'e'}
6 | print(letters1 == letters2) # prints: True
7 |
--------------------------------------------------------------------------------
/ch10/flask/templates/main.html:
--------------------------------------------------------------------------------
1 |
2 | Hello from Flask
3 |
4 | {% if name %}
5 | Hello {{ name }}!
6 | {% else %}
7 | Hello shy person!
8 | {% endif %}
9 |
10 |
--------------------------------------------------------------------------------
/ch3/simple.for.2.py:
--------------------------------------------------------------------------------
1 | surnames = ['Rivest', 'Shamir', 'Adleman']
2 | for position in range(len(surnames)):
3 | print(position, surnames[position])
4 | # print(surnames[position][0], end='') # try swapping prints
5 |
--------------------------------------------------------------------------------
/ch4/arguments.variable.keyword.py:
--------------------------------------------------------------------------------
1 | def func(**kwargs):
2 | print(kwargs)
3 |
4 | # All calls equivalent. They print: {'a': 1, 'b': 42}
5 | func(a=1, b=42)
6 | func(**{'a': 1, 'b': 42})
7 | func(**dict(a=1, b=42))
8 |
--------------------------------------------------------------------------------
/ch4/return.none.py:
--------------------------------------------------------------------------------
1 | def func():
2 | pass
3 |
4 | func() # the return of this call won't be collected. It's lost.
5 | a = func() # the return of this one instead is collected into `a`
6 | print(a) # prints: None
7 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | for position in range(len(people)):
4 | person = people[position]
5 | age = ages[position]
6 | print(person, age)
7 |
--------------------------------------------------------------------------------
/ch4/arguments.variable.positional.unpacking.py:
--------------------------------------------------------------------------------
1 | def func(*args):
2 | print(args)
3 |
4 | values = (1, 3, -7, 9)
5 | func(values) # equivalent to: func((1, 3, -7, 9))
6 | func(*values) # equivalent to: func(1, 3, -7, 9)
7 |
--------------------------------------------------------------------------------
/ch4/filter.regular.py:
--------------------------------------------------------------------------------
1 | def is_multiple_of_five(n):
2 | return not n % 5
3 |
4 |
5 | def get_multiples_of_five(n):
6 | return list(filter(is_multiple_of_five, range(n)))
7 |
8 |
9 | print(get_multiples_of_five(50))
10 |
--------------------------------------------------------------------------------
/ch7/exceptions/json.example.py:
--------------------------------------------------------------------------------
1 | import json
2 |
3 | json_data = '{}' # try: json_data = 2, and json_data = '{{'
4 |
5 | try:
6 | data = json.loads(json_data)
7 | except (ValueError, TypeError) as e:
8 | print(type(e), e)
9 |
--------------------------------------------------------------------------------
/ch1/scopes1.py:
--------------------------------------------------------------------------------
1 | # Local versus Global
2 |
3 | # we define a function, called local
4 | def local():
5 | m = 7
6 | print(m)
7 |
8 | m = 5
9 | print(m)
10 |
11 | # we call, or `execute` the function local
12 | local()
13 |
--------------------------------------------------------------------------------
/ch7/filter_funcs_triangulation.py:
--------------------------------------------------------------------------------
1 | def filter_ints(v):
2 | return [3, 5, 8]
3 |
4 | def is_positive(n):
5 | return n > 0
6 |
7 |
8 | if __name__ == "__main__":
9 | print(filter_ints([3, -4, 0, 5, 8])) # [3, 5, 8]
10 |
--------------------------------------------------------------------------------
/requirements/requirements.in:
--------------------------------------------------------------------------------
1 | jupyter
2 | ipython
3 | pandas
4 | numpy
5 | matplotlib
6 | Faker
7 | pep8
8 | beautifulsoup4
9 | requests
10 | Delorean
11 | xlwt
12 | django==1.8.17
13 | falcon
14 | Flask
15 | gunicorn
16 | cryptography
--------------------------------------------------------------------------------
/ch4/key.points.mutable.assignment.py:
--------------------------------------------------------------------------------
1 | x = [1, 2, 3]
2 | def func(x):
3 | x[1] = 42 # this changes the caller!
4 | x = 'something else' # this points x to a new string object
5 |
6 | func(x)
7 | print(x) # still prints: [1, 42, 3]
8 |
--------------------------------------------------------------------------------
/requirements/requirements_test.txt:
--------------------------------------------------------------------------------
1 | #
2 | # This file is autogenerated by pip-compile
3 | # To update, run:
4 | #
5 | # pip-compile --output-file requirements_test.txt requirements_test.in
6 | #
7 | nose-parameterized==0.5.0
8 | nose==1.3.7
9 |
--------------------------------------------------------------------------------
/ch3/primes.else.py:
--------------------------------------------------------------------------------
1 | primes = []
2 | upto = 100
3 | for n in range(2, upto + 1):
4 | for divisor in range(2, n):
5 | if n % divisor == 0:
6 | break
7 | else:
8 | primes.append(n)
9 |
10 | print(primes)
11 |
--------------------------------------------------------------------------------
/ch4/return.single.value.py:
--------------------------------------------------------------------------------
1 | def factorial(n):
2 | if n in (0, 1):
3 | return 1
4 | result = n
5 | for k in range(2, n):
6 | result *= k
7 | return result
8 |
9 | f5 = factorial(5) # f5 = 120
10 | print(f5)
11 |
--------------------------------------------------------------------------------
/ch5/maxims.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> a = [5, 9, 2, 4, 7]
4 | >>> b = [3, 7, 1, 9, 2]
5 | >>> c = [6, 8, 0, 5, 3]
6 | >>> maxs = map(lambda n: max(*n), zip(a, b, c))
7 | >>> list(maxs)
8 | [6, 9, 2, 9, 7]
9 |
--------------------------------------------------------------------------------
/ch1/names.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | n = 3 # integer number
4 | address = "221b Baker Street, NW1 6XE, London" # Sherlock Holmes' address
5 | employee = {
6 | 'age': 45,
7 | 'role': 'CTO',
8 | 'SSN': 'AB1234567',
9 | }
10 |
--------------------------------------------------------------------------------
/ch4/scoping.level.1.py:
--------------------------------------------------------------------------------
1 | def my_function():
2 | test = 1 # this is defined in the local scope of the function
3 | print('my_function:', test)
4 |
5 |
6 | test = 0 # this is defined in the global scope
7 | my_function()
8 | print('global:', test)
9 |
--------------------------------------------------------------------------------
/ch7/filter_funcs.py:
--------------------------------------------------------------------------------
1 | def filter_ints(v):
2 | return [num for num in v if is_positive(num)]
3 |
4 | def is_positive(n):
5 | return n > 0
6 |
7 |
8 | if __name__ == "__main__":
9 | print(filter_ints([3, -4, 0, 5, 8])) # [3, 5, 8]
10 |
--------------------------------------------------------------------------------
/ch2/README.md:
--------------------------------------------------------------------------------
1 | Chapter 2 data files
2 | ====================
3 |
4 | The files in this folder are not supposed to work if run.
5 | They serve as source for the book chapters, and to provide a
6 | quick copy/paste tool for whoever would need their content.
7 |
--------------------------------------------------------------------------------
/ch5/gen.send.preparation.py:
--------------------------------------------------------------------------------
1 | def counter(start=0):
2 | n = start
3 | while True:
4 | yield n
5 | n += 1
6 |
7 | c = counter()
8 | print(next(c)) # prints: 0
9 | print(next(c)) # prints: 1
10 | print(next(c)) # prints: 2
11 |
--------------------------------------------------------------------------------
/ch3/binary.2.py:
--------------------------------------------------------------------------------
1 | n = 39
2 | remainders = []
3 | while n > 0:
4 | n, remainder = divmod(n, 2)
5 | remainders.append(remainder)
6 |
7 | # reassign the list to its reversed copy and print it
8 | remainders = remainders[::-1]
9 | print(remainders)
10 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.while.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | position = 0
4 | while position < len(people):
5 | person = people[position]
6 | age = ages[position]
7 | print(person, age)
8 | position += 1
9 |
--------------------------------------------------------------------------------
/ch10/regex/entries/forms.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.forms import ModelForm
3 |
4 | from .models import Entry
5 |
6 |
7 | class EntryForm(ModelForm):
8 | class Meta:
9 | model = Entry
10 | fields = ['pattern', 'test_string']
11 |
--------------------------------------------------------------------------------
/ch5/dictionary.comprehensions.py:
--------------------------------------------------------------------------------
1 | from string import ascii_lowercase
2 |
3 |
4 | lettermap = dict((c, k) for k, c in enumerate(ascii_lowercase, 1))
5 | # lettermap = {c: k for k, c in enumerate(ascii_lowercase, 1)}
6 |
7 |
8 | from pprint import pprint
9 | pprint(lettermap)
--------------------------------------------------------------------------------
/ch4/arguments.all.py:
--------------------------------------------------------------------------------
1 | def func(a, b, c=7, *args, **kwargs):
2 | print('a, b, c:', a, b, c)
3 | print('args:', args)
4 | print('kwargs:', kwargs)
5 |
6 | func(1, 2, 3, *(5, 7, 9), **{'A': 'a', 'B': 'b'})
7 | func(1, 2, 3, 5, 7, 9, A='a', B='b') # same as previous one
8 |
--------------------------------------------------------------------------------
/ch11/custom.py:
--------------------------------------------------------------------------------
1 | def debug(*msg, print_separator=True):
2 | print(*msg)
3 | if print_separator:
4 | print('-' * 40)
5 |
6 |
7 | debug('Data is ...')
8 | debug('Different', 'Strings', 'Are not a problem')
9 | debug('After while loop', print_separator=False)
10 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.explicit.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | nationalities = ['Belgium', 'Spain', 'England', 'Bangladesh']
4 | for person, age, nationality in zip(people, ages, nationalities):
5 | print(person, age, nationality)
6 |
--------------------------------------------------------------------------------
/ch4/arguments.defaults.mutable.py:
--------------------------------------------------------------------------------
1 | def func(a=[], b={}):
2 | print(a)
3 | print(b)
4 | print('#' * 12)
5 | a.append(len(a)) # this will affect a's default value
6 | b[len(a)] = len(a) # and this will affect b's one
7 |
8 | func()
9 | func()
10 | func()
11 |
--------------------------------------------------------------------------------
/ch4/return.single.value.2.py:
--------------------------------------------------------------------------------
1 | from functools import reduce
2 | from operator import mul
3 |
4 |
5 | def factorial(n):
6 | return reduce(mul, range(1, n + 1), 1)
7 |
8 |
9 | f5 = factorial(5) # f5 = 120
10 | print(f5)
11 | print([factorial(k) for k in range(10)])
12 |
--------------------------------------------------------------------------------
/ch3/range.py:
--------------------------------------------------------------------------------
1 | >>> list(range(10)) # one value: from 0 to value (excluded)
2 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3 | >>> list(range(3, 8)) # two values: from start to stop (excluded)
4 | [3, 4, 5, 6, 7]
5 | >>> list(range(-10, 10, 4)) # three values: step is added
6 | [-10, -6, -2, 2, 6]
7 |
--------------------------------------------------------------------------------
/ch3/multiple.sequences.implicit.py:
--------------------------------------------------------------------------------
1 | people = ['Jonas', 'Julio', 'Mike', 'Mez']
2 | ages = [25, 30, 31, 39]
3 | nationalities = ['Belgium', 'Spain', 'England', 'Bangladesh']
4 | for data in zip(people, ages, nationalities):
5 | person, age, nationality = data
6 | print(person, age, nationality)
7 |
--------------------------------------------------------------------------------
/ch4/scoping.level.2.py:
--------------------------------------------------------------------------------
1 | def outer():
2 | test = 1 # outer scope
3 |
4 | def inner():
5 | test = 2 # inner scope
6 | print('inner:', test)
7 |
8 | inner()
9 | print('outer:', test)
10 |
11 |
12 | test = 0 # global scope
13 | outer()
14 | print('global:', test)
15 |
--------------------------------------------------------------------------------
/ch7/filter_funcs_refactored.py:
--------------------------------------------------------------------------------
1 | def filter_ints(v):
2 | v = [num for num in v if num != 0] # 1
3 | return [num for num in v if is_positive(num)]
4 |
5 | def is_positive(n):
6 | return n > 0
7 |
8 |
9 | if __name__ == "__main__":
10 | print(filter_ints([3, -4, 0, 5, 8])) # [3, 5, 8]
11 |
--------------------------------------------------------------------------------
/ch10/regex/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "regex.settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/ch12/pwdweb/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | import os
3 | import sys
4 |
5 | if __name__ == "__main__":
6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pwdweb.settings")
7 |
8 | from django.core.management import execute_from_command_line
9 |
10 | execute_from_command_line(sys.argv)
11 |
--------------------------------------------------------------------------------
/ch3/ternary.py:
--------------------------------------------------------------------------------
1 | order_total = 247 # GBP
2 |
3 | # classic if/else form
4 | if order_total > 100:
5 | discount = 25 # GBP
6 | else:
7 | discount = 0 # GBP
8 | print(order_total, discount)
9 |
10 | # ternary operator
11 | discount = 25 if order_total > 100 else 0
12 | print(order_total, discount)
13 |
--------------------------------------------------------------------------------
/ch5/even.squares.py:
--------------------------------------------------------------------------------
1 | # using map and filter
2 | sq1 = list(
3 | filter(lambda n: not n % 2, map(lambda n: n ** 2, range(10)))
4 | )
5 |
6 | # equivalent, but using list comprehensions
7 | sq2 = [n ** 2 for n in range(10) if not n % 2]
8 |
9 | print(sq1, sq1 == sq2) # prints: [0, 4, 16, 36, 64] True
10 |
--------------------------------------------------------------------------------
/ch5/gen.send.preparation.stop.py:
--------------------------------------------------------------------------------
1 | stop = False
2 |
3 | def counter(start=0):
4 | n = start
5 | while not stop:
6 | yield n
7 | n += 1
8 |
9 | c = counter()
10 | print(next(c)) # prints: 0
11 | print(next(c)) # prints: 1
12 | stop = True
13 | print(next(c)) # raises StopIteration
14 |
--------------------------------------------------------------------------------
/ch3/for.else.py:
--------------------------------------------------------------------------------
1 | class DriverException(Exception):
2 | pass
3 |
4 |
5 | people = [('James', 17), ('Kirk', 9), ('Lars', 13), ('Robert', 8)]
6 | for person, age in people:
7 | if age >= 18:
8 | driver = (person, age)
9 | break
10 | else:
11 | raise DriverException('Driver not found.')
12 |
--------------------------------------------------------------------------------
/ch10/flask/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from flask import Flask, render_template
3 |
4 | app = Flask(__name__)
5 |
6 |
7 | @app.route('/')
8 | @app.route('/')
9 | def hello(name=None):
10 | return render_template('main.html', name=name)
11 |
12 |
13 | if __name__ == '__main__':
14 | app.run()
15 |
--------------------------------------------------------------------------------
/ch3/taxes.py:
--------------------------------------------------------------------------------
1 | income = 15000
2 | if income < 10000:
3 | tax_coefficient = 0.0 #1
4 | elif income < 30000:
5 | tax_coefficient = 0.2 #2
6 | elif income < 100000:
7 | tax_coefficient = 0.35 #3
8 | else:
9 | tax_coefficient = 0.45 #4
10 |
11 | print('I will pay:', income * tax_coefficient, 'in taxes')
12 |
--------------------------------------------------------------------------------
/ch4/arguments.default.error.py:
--------------------------------------------------------------------------------
1 | def func(a, b=4, c=88):
2 | print(a, b, c)
3 |
4 | func(b=1, c=2, 42) # positional argument after keyword one
5 |
6 | """
7 | File "arguments.default.error.py", line 4
8 | func(b=1, c=2, 42)
9 | ^
10 | SyntaxError: non-keyword arg after keyword arg
11 | """
12 |
--------------------------------------------------------------------------------
/ch4/arguments.defaults.mutable.intermediate.call.py:
--------------------------------------------------------------------------------
1 | def func(a=[], b={}):
2 | print(a)
3 | print(b)
4 | print('#' * 12)
5 | a.append(len(a)) # this will affect a's default value
6 | b[len(a)] = len(a) # and this will affect b's one
7 |
8 | func()
9 | func(a=[1, 2, 3], b={'B': 1})
10 | func()
11 |
--------------------------------------------------------------------------------
/ch4/matrix.multiplication.func.py:
--------------------------------------------------------------------------------
1 | # this function could also be defined in another module
2 | def matrix_mul(a, b):
3 | return [[sum(i * j for i, j in zip(r, c)) for c in zip(*b)]
4 | for r in a]
5 |
6 |
7 | a = [[1, 2], [3, 4]]
8 | b = [[5, 1], [2, 1]]
9 |
10 | c = matrix_mul(a, b)
11 | print(c)
12 |
--------------------------------------------------------------------------------
/ch7/exceptions/multiple.except.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | try:
4 | # some code
5 | except Exception1:
6 | # react to Exception1
7 | except (Exception2, Exception3):
8 | # react to Exception2 and Exception3
9 | except Exception3:
10 | # react to Exception3
11 | ...
12 |
--------------------------------------------------------------------------------
/ch3/switch.py:
--------------------------------------------------------------------------------
1 | # this code is not supposed to be run
2 | if 1 <= day_number <= 5:
3 | day = 'Weekday'
4 | elif day_number == 6:
5 | day = 'Saturday'
6 | elif day_number == 0:
7 | day = 'Sunday'
8 | else:
9 | day = ''
10 | raise ValueError(
11 | str(day_number) + ' is not a valid day number.')
12 |
--------------------------------------------------------------------------------
/ch4/no.side.effects.py:
--------------------------------------------------------------------------------
1 | # This file is not meant to be run
2 | >>> numbers = [4, 1, 7, 5]
3 | >>> sorted(numbers) # won't sort the original `numbers` list
4 | [1, 4, 5, 7]
5 | >>> numbers # let's verify
6 | [4, 1, 7, 5] # good, untouched
7 | >>> numbers.sort() # this will act on the list
8 | >>> numbers
9 | [1, 4, 5, 7]
10 |
--------------------------------------------------------------------------------
/ch5/filter.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> test = [2, 5, 8, 0, 0, 1, 0]
4 | >>> list(filter(None, test))
5 | [2, 5, 8, 1]
6 | >>> list(filter(lambda x: x, test)) # equivalent to previous one
7 | [2, 5, 8, 1]
8 | >>> list(filter(lambda x: x > 4, test)) # keep only items > 4
9 | [5, 8]
10 |
--------------------------------------------------------------------------------
/ch4/scoping.level.2.global.py:
--------------------------------------------------------------------------------
1 | def outer():
2 | test = 1 # outer scope
3 |
4 | def inner():
5 | global test
6 | test = 2 # global scope
7 | print('inner:', test)
8 |
9 | inner()
10 | print('outer:', test)
11 |
12 |
13 | test = 0 # global scope
14 | outer()
15 | print('global:', test)
16 |
--------------------------------------------------------------------------------
/ch5/first.n.squares.py:
--------------------------------------------------------------------------------
1 | def get_squares(n): # classic function approach
2 | return [x ** 2 for x in range(n)]
3 |
4 | print(get_squares(10))
5 |
6 |
7 | def get_squares_gen(n): # generator approach
8 | for x in range(n):
9 | yield x ** 2 # we yield, we don't return
10 |
11 | print(list(get_squares_gen(10)))
12 |
--------------------------------------------------------------------------------
/ch11/traceback_validator.py:
--------------------------------------------------------------------------------
1 | class ValidatorError(Exception):
2 | """Raised when accessing a dict results in KeyError. """
3 |
4 | d = {'some': 'key'}
5 | mandatory_key = 'some-other'
6 | try:
7 | print(d[mandatory_key])
8 | except KeyError:
9 | raise ValidatorError(
10 | '`{}` not found in d.'.format(mandatory_key))
11 |
--------------------------------------------------------------------------------
/ch6/decorators/time.measure.start.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 |
3 |
4 | def f():
5 | sleep(.3)
6 |
7 | def g():
8 | sleep(.5)
9 |
10 |
11 | t = time()
12 | f()
13 | print('f took: ', time() - t) # f took: 0.3003859519958496
14 |
15 | t = time()
16 | g()
17 | print('g took:', time() - t) # g took: 0.5005719661712646
18 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/admin.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.contrib import admin
3 |
4 | from .models import Record
5 |
6 |
7 | @admin.register(Record)
8 | class RecordAdmin(admin.ModelAdmin):
9 | list_display = (
10 | 'title', 'username', 'email', 'url', 'created',
11 | 'last_modified', 'password'
12 | )
13 |
--------------------------------------------------------------------------------
/ch3/compress.py:
--------------------------------------------------------------------------------
1 | from itertools import compress
2 | data = range(10)
3 | even_selector = [1, 0] * 10
4 | odd_selector = [0, 1] * 10
5 |
6 | even_numbers = list(compress(data, even_selector))
7 | odd_numbers = list(compress(data, odd_selector))
8 |
9 | print(odd_selector)
10 | print(list(data))
11 | print(even_numbers)
12 | print(odd_numbers)
13 |
--------------------------------------------------------------------------------
/ch5/fibonacci.elegant.py:
--------------------------------------------------------------------------------
1 | def fibonacci(N):
2 | """Return all fibonacci numbers up to N. """
3 | a, b = 0, 1
4 | while a <= N:
5 | yield a
6 | a, b = b, a + b
7 |
8 |
9 | print(list(fibonacci(0))) # [0]
10 | print(list(fibonacci(1))) # [0, 1, 1]
11 | print(list(fibonacci(50))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
12 |
--------------------------------------------------------------------------------
/ch4/scoping.level.2.nonlocal.py:
--------------------------------------------------------------------------------
1 | def outer():
2 | test = 1 # outer scope
3 |
4 | def inner():
5 | nonlocal test
6 | test = 2 # nearest enclosing scope
7 | print('inner:', test)
8 |
9 | inner()
10 | print('outer:', test)
11 |
12 |
13 | test = 0 # global scope
14 | outer()
15 | print('global:', test)
16 |
--------------------------------------------------------------------------------
/ch5/gen.map.filter.py:
--------------------------------------------------------------------------------
1 | # finds the cubes of all multiples of 3 or 5 below N
2 | N = 20
3 |
4 | cubes1 = map(
5 | lambda n: (n, n**3),
6 | filter(lambda n: n % 3 == 0 or n % 5 == 0, range(N))
7 | )
8 |
9 | cubes2 = (
10 | (n, n**3) for n in range(N) if n % 3 == 0 or n % 5 == 0)
11 |
12 | print(list(cubes1))
13 | print(list(cubes2))
14 |
--------------------------------------------------------------------------------
/ch3/for.no.else.py:
--------------------------------------------------------------------------------
1 | class DriverException(Exception):
2 | pass
3 |
4 |
5 | people = [('James', 17), ('Kirk', 9), ('Lars', 13), ('Robert', 8)]
6 | driver = None
7 | for person, age in people:
8 | if age >= 18:
9 | driver = (person, age)
10 | break
11 |
12 | if driver is None:
13 | raise DriverException('Driver not found.')
14 |
--------------------------------------------------------------------------------
/ch4/vat.py:
--------------------------------------------------------------------------------
1 | price = 100 # GBP, no VAT
2 | final_price1 = price * 1.2
3 | final_price2 = price + price / 5.0
4 | final_price3 = price * (100 + 20) / 100.0
5 | final_price4 = price + price * 0.2
6 |
7 |
8 | if __name__ == "__main__":
9 | for var, value in sorted(vars().items()):
10 | if 'price' in var:
11 | print(var, value)
12 |
--------------------------------------------------------------------------------
/ch5/gen.yield.return.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | def geometric_progression(a, q):
4 | k = 0
5 | while True:
6 | result = a * q**k
7 | if result <= 100000:
8 | yield result
9 | else:
10 | return
11 | k += 1
12 |
13 |
14 | for n in geometric_progression(2, 5):
15 | print(n)
16 |
--------------------------------------------------------------------------------
/ch6/decorators/time.measure.dry.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 |
3 |
4 | def f():
5 | sleep(.3)
6 |
7 | def g():
8 | sleep(.5)
9 |
10 | def measure(func):
11 | t = time()
12 | func()
13 | print(func.__name__, 'took:', time() - t)
14 |
15 | measure(f) # f took: 0.30041074752807617
16 | measure(g) # g took: 0.5006198883056641
17 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templatetags/record_extras.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django import template
3 | from django.utils.html import escape
4 |
5 |
6 | register = template.Library()
7 |
8 |
9 | @register.simple_tag
10 | def hide_password(password):
11 | return '{1}'.format(
12 | escape(password), '*' * len(password))
13 |
--------------------------------------------------------------------------------
/ch4/arguments.all.kwonly.py:
--------------------------------------------------------------------------------
1 | def func_with_kwonly(a, b=42, *args, c, d=256, **kwargs):
2 | print('a, b:', a, b)
3 | print('c, d:', c, d)
4 | print('args:', args)
5 | print('kwargs:', kwargs)
6 |
7 | # both calls equivalent
8 | func_with_kwonly(3, 42, c=0, d=1, *(7, 9, 11), e='E', f='F')
9 | func_with_kwonly(3, 42, *(7, 9, 11), c=0, d=1, e='E', f='F')
10 |
--------------------------------------------------------------------------------
/ch6/oop/class.self.py:
--------------------------------------------------------------------------------
1 | class Square():
2 | side = 8
3 | def area(self): # self is a reference to an instance
4 | return self.side ** 2
5 |
6 | sq = Square()
7 | print(sq.area()) # 64 (side is found on the class)
8 | print(Square.area(sq)) # 64 (equivalent to sq.area())
9 |
10 | sq.side = 10
11 | print(sq.area()) # 100 (side is found on the instance)
12 |
--------------------------------------------------------------------------------
/ch1/scopes2.py:
--------------------------------------------------------------------------------
1 | # Local versus Global
2 |
3 | def local():
4 | # m doesn't belong to the scope defined by the local function
5 | # so Python will keep looking into the next enclosing scope.
6 | # m is finally found in the global scope
7 | print(m, 'printing from the local scope')
8 |
9 | m = 5
10 | print(m, 'printing from the global scope')
11 |
12 | local()
13 |
--------------------------------------------------------------------------------
/ch6/oop/simplest.class.py:
--------------------------------------------------------------------------------
1 | class Simplest(): # when empty, the braces are optional
2 | pass
3 |
4 | print(type(Simplest)) # what type is this object?
5 |
6 | simp = Simplest() # we create an instance of Simplest: simp
7 | print(type(simp)) # what type is simp?
8 | # is simp an instance of Simplest?
9 | print(type(simp) == Simplest) # There's a better way for this
10 |
--------------------------------------------------------------------------------
/ch5/scopes.py:
--------------------------------------------------------------------------------
1 | A = 100
2 | ex1 = [A for A in range(5)]
3 | print(A) # prints: 100
4 |
5 | ex2 = list(A for A in range(5))
6 | print(A) # prints: 100
7 |
8 | ex3 = dict((A, 2 * A) for A in range(5))
9 | print(A) # prints: 100
10 |
11 | ex4 = set(A for A in range(5))
12 | print(A) # prints: 100
13 |
14 | s = 0
15 | for A in range(5):
16 | s += A
17 | print(A) # prints: 4
18 |
--------------------------------------------------------------------------------
/ch6/oop/class.init.py:
--------------------------------------------------------------------------------
1 | class Rectangle():
2 | def __init__(self, side_a, side_b):
3 | self.side_a = side_a
4 | self.side_b = side_b
5 |
6 | def area(self):
7 | return self.side_a * self.side_b
8 |
9 | r1 = Rectangle(10, 4)
10 | print(r1.side_a, r1.side_b) # 10 4
11 | print(r1.area()) # 40
12 |
13 | r2 = Rectangle(7, 3)
14 | print(r2.area()) # 21
15 |
--------------------------------------------------------------------------------
/ch6/oop/class.price.py:
--------------------------------------------------------------------------------
1 | class Price():
2 | def final_price(self, vat, discount=0):
3 | """Returns price after applying vat and fixed discount."""
4 | return (self.net_price * (100 + vat) / 100) - discount
5 |
6 | p1 = Price()
7 | p1.net_price = 100
8 | print(Price.final_price(p1, 20, 10)) # 110 (100 * 1.2 - 10)
9 | print(p1.final_price(20, 10)) # equivalent
10 |
--------------------------------------------------------------------------------
/ch4/arguments.variable.positional.py:
--------------------------------------------------------------------------------
1 | def minimum(*n):
2 | # print(n) # n is a tuple
3 | if n: # explained after the code
4 | mn = n[0]
5 | for value in n[1:]:
6 | if value < mn:
7 | mn = value
8 | print(mn)
9 |
10 | minimum(1, 3, -7, 9) # n = (1, 3, -7, 9) - prints: -7
11 | minimum() # n = () - prints: nothing
12 |
--------------------------------------------------------------------------------
/ch5/gen.send.py:
--------------------------------------------------------------------------------
1 | def counter(start=0):
2 | n = start
3 | while True:
4 | result = yield n # A
5 | print(type(result), result) # B
6 | if result == 'Q':
7 | break
8 | n += 1
9 |
10 | c = counter()
11 | print(next(c)) # C
12 | print(c.send('Wow!')) # D
13 | print(next(c)) # E
14 | print(c.send('Q')) # F
15 |
--------------------------------------------------------------------------------
/ch5/pythagorean.triple.comprehension.py:
--------------------------------------------------------------------------------
1 | from math import sqrt
2 | # this step is the same as before
3 | mx = 10
4 | legs = [(a, b, sqrt(a**2 + b**2))
5 | for a in range(1, mx) for b in range(a, mx)]
6 | # here we combine filter and map in one CLEAN list comprehension
7 | legs = [(a, b, int(c)) for a, b, c in legs if c.is_integer()]
8 |
9 | print(legs) # prints: [(3, 4, 5), (6, 8, 10)]
10 |
--------------------------------------------------------------------------------
/ch5/pythagorean.triple.py:
--------------------------------------------------------------------------------
1 | from math import sqrt
2 |
3 | # this will generate all possible pairs
4 | mx = 10
5 | legs = [(a, b, sqrt(a**2 + b**2))
6 | for a in range(1, mx) for b in range(a, mx)]
7 | # this will filter out all non pythagorean triples
8 | legs = list(
9 | filter(lambda triple: triple[2].is_integer(), legs))
10 |
11 | print(legs) # prints: [(3, 4, 5.0), (6, 8, 10.0)]
12 |
--------------------------------------------------------------------------------
/ch5/fibonacci.first.py:
--------------------------------------------------------------------------------
1 | def fibonacci(N):
2 | """Return all fibonacci numbers up to N. """
3 | result = [0]
4 | next_n = 1
5 | while next_n <= N:
6 | result.append(next_n)
7 | next_n = sum(result[-2:])
8 | return result
9 |
10 |
11 | print(fibonacci(0)) # [0]
12 | print(fibonacci(1)) # [0, 1, 1]
13 | print(fibonacci(50)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
14 |
--------------------------------------------------------------------------------
/ch6/decorators/time.measure.arguments.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 |
3 |
4 | def f(sleep_time=0.1):
5 | sleep(sleep_time)
6 |
7 | def measure(func, *args, **kwargs):
8 | t = time()
9 | func(*args, **kwargs)
10 | print(func.__name__, 'took:', time() - t)
11 |
12 | measure(f, sleep_time=0.3) # f took: 0.3004162311553955
13 | measure(f, 0.2) # f took: 0.20028162002563477
14 |
--------------------------------------------------------------------------------
/ch11/ipdebugger.py:
--------------------------------------------------------------------------------
1 | # d comes from a JSON payload we don't control
2 | d = {'first': 'v1', 'second': 'v2', 'fourth': 'v4'}
3 | # keys also comes from a JSON payload we don't control
4 | keys = ('first', 'second', 'third', 'fourth')
5 |
6 | def do_something_with_value(value):
7 | print(value)
8 |
9 | for key in keys:
10 | do_something_with_value(d[key])
11 |
12 | print('Validation done.')
13 |
--------------------------------------------------------------------------------
/ch5/zip.grades.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> grades = [18, 23, 30, 27, 15, 9, 22]
4 | >>> avgs = [22, 21, 29, 24, 18, 18, 24]
5 | >>> list(zip(avgs, grades))
6 | [(22, 18), (21, 23), (29, 30), (24, 27), (18, 15), (18, 9), (24, 22)]
7 | >>> list(map(lambda *a: a, avgs, grades)) # equivalent to zip
8 | [(22, 18), (21, 23), (29, 30), (24, 27), (18, 15), (18, 9), (24, 22)]
9 |
--------------------------------------------------------------------------------
/tests/test_ch7/test_filter_funcs_final.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from nose.tools import assert_list_equal
3 |
4 | from ch7.filter_funcs import filter_ints
5 |
6 |
7 | class FilterIntsTestCase(TestCase):
8 |
9 | def test_filter_ints_return_value(self):
10 | v = [3, -4, 0, -2, 5, 0, 8, -1]
11 | result = filter_ints(v)
12 | assert_list_equal([3, 5, 8], result)
13 |
--------------------------------------------------------------------------------
/ch3/switch.js:
--------------------------------------------------------------------------------
1 | switch (day_number) {
2 | case 1:
3 | case 2:
4 | case 3:
5 | case 4:
6 | case 5:
7 | day = "Weekday";
8 | break;
9 | case 6:
10 | day = "Saturday";
11 | break;
12 | case 0:
13 | day = "Sunday";
14 | break;
15 | default:
16 | day = "";
17 | alert(day_number + ' is not a valid day number.')
18 | }
19 |
--------------------------------------------------------------------------------
/ch5/fibonacci.second.py:
--------------------------------------------------------------------------------
1 | def fibonacci(N):
2 | """Return all fibonacci numbers up to N. """
3 | yield 0
4 | if N == 0:
5 | return
6 | a = 0
7 | b = 1
8 | while b <= N:
9 | yield b
10 | a, b = b, a + b
11 |
12 |
13 | print(list(fibonacci(0))) # [0]
14 | print(list(fibonacci(1))) # [0, 1, 1]
15 | print(list(fibonacci(50))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
16 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/forms.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.forms import ModelForm, Textarea
3 |
4 | from .models import Record
5 |
6 |
7 | class RecordForm(ModelForm):
8 | class Meta:
9 | model = Record
10 | fields = ['title', 'username', 'email', 'url',
11 | 'password', 'notes']
12 | widgets = {'notes': Textarea(
13 | attrs={'cols': 40, 'rows': 4})}
14 |
--------------------------------------------------------------------------------
/ch3/any.py:
--------------------------------------------------------------------------------
1 | items = [0, None, 0.0, True, 0, 7] # True and 7 evaluate to True
2 |
3 | found = False # this is called "flag"
4 | for item in items:
5 | print('scanning item', item)
6 | if item:
7 | found = True # we update the flag
8 | break
9 |
10 | if found: # we inspect the flag
11 | print('At least one item evaluates to True')
12 | else:
13 | print('All items evaluate to False')
14 |
--------------------------------------------------------------------------------
/ch3/primes.py:
--------------------------------------------------------------------------------
1 | primes = [] # this will contain the primes in the end
2 | upto = 100 # the limit, inclusive
3 | for n in range(2, upto + 1):
4 | is_prime = True # flag, new at each iteration of outer for
5 | for divisor in range(2, n):
6 | if n % divisor == 0:
7 | is_prime = False
8 | break
9 | if is_prime: # check on flag
10 | primes.append(n)
11 |
12 | print(primes)
13 |
--------------------------------------------------------------------------------
/ch5/pythagorean.triple.int.py:
--------------------------------------------------------------------------------
1 | from math import sqrt
2 |
3 | mx = 10
4 | legs = [(a, b, sqrt(a**2 + b**2))
5 | for a in range(1, mx) for b in range(a, mx)]
6 | legs = filter(lambda triple: triple[2].is_integer(), legs)
7 |
8 | # this will make the third number in the tuples integer
9 | legs = list(
10 | map(lambda triple: triple[:2] + (int(triple[2]), ), legs))
11 |
12 | print(legs) # prints: [(3, 4, 5), (6, 8, 10)]
13 |
--------------------------------------------------------------------------------
/ch6/oop/mro.py:
--------------------------------------------------------------------------------
1 | class A:
2 | label = 'a'
3 |
4 | class B(A):
5 | pass # was: label = 'b'
6 |
7 | class C(A):
8 | label = 'c'
9 |
10 | class D(B, C):
11 | pass
12 |
13 |
14 | d = D()
15 | print(d.label) # 'c'
16 | print(d.__class__.mro()) # notice another way to get the MRO
17 | # prints:
18 | # [, ,
19 | # , , ]
20 |
--------------------------------------------------------------------------------
/ch12/pwdapi/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import falcon
3 |
4 | from core.handlers import (
5 | PasswordValidatorHandler,
6 | PasswordGeneratorHandler,
7 | )
8 |
9 |
10 | validation_handler = PasswordValidatorHandler()
11 | generator_handler = PasswordGeneratorHandler()
12 |
13 | app = falcon.API()
14 | app.add_route('/password/validate/', validation_handler)
15 | app.add_route('/password/generate/', generator_handler)
16 |
--------------------------------------------------------------------------------
/ch5/first.n.squares.manual.method.py:
--------------------------------------------------------------------------------
1 | def get_squares_gen(n):
2 | for x in range(n):
3 | yield x ** 2
4 |
5 | squares = get_squares_gen(3)
6 | print(squares.__next__()) # prints: 0
7 | print(squares.__next__()) # prints: 1
8 | print(squares.__next__()) # prints: 4
9 | # the following raises StopIteration, the generator is exhausted,
10 | # any further call to next will keep raising StopIteration
11 | print(squares.__next__())
12 |
--------------------------------------------------------------------------------
/ch6/oop/super.duplication.py:
--------------------------------------------------------------------------------
1 | class Book:
2 |
3 | def __init__(self, title, publisher, pages):
4 | self.title = title
5 | self.publisher = publisher
6 | self.pages = pages
7 |
8 |
9 | class Ebook(Book):
10 |
11 | def __init__(self, title, publisher, pages, format_):
12 | self.title = title
13 | self.publisher = publisher
14 | self.pages = pages
15 | self.format_ = format_
16 |
--------------------------------------------------------------------------------
/ch5/squares.map.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | # If you code like this you are not a Python guy! ;)
4 | >>> squares = []
5 | >>> for n in range(10):
6 | ... squares.append(n ** 2)
7 | ...
8 | >>> list(squares)
9 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
10 |
11 | # This is better, one line, nice and readable
12 | >>> squares = map(lambda n: n**2, range(10))
13 | >>> list(squares)
14 | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
15 |
--------------------------------------------------------------------------------
/ch10/falcon/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import json
3 | import random
4 |
5 | import falcon
6 |
7 | from quotes import quotes
8 |
9 |
10 | class QuoteResource:
11 | def on_get(self, req, resp):
12 | quote = {
13 | 'quote': random.choice(quotes),
14 | 'author': 'The Buddha'
15 | }
16 | resp.body = json.dumps(quote)
17 |
18 |
19 | api = falcon.API()
20 | api.add_route('/quote', QuoteResource())
21 |
--------------------------------------------------------------------------------
/ch6/oop/mro.simple.py:
--------------------------------------------------------------------------------
1 | class A:
2 | label = 'a'
3 |
4 | class B(A):
5 | label = 'b'
6 |
7 | class C(A):
8 | label = 'c'
9 |
10 | class D(B, C):
11 | pass
12 |
13 | d = D()
14 | print(d.label) # Hypothetically this could be either 'b' or 'c'
15 | print(d.__class__.mro()) # notice another way to get the MRO
16 | # prints:
17 | # [, ,
18 | # , , ]
19 |
--------------------------------------------------------------------------------
/ch6/oop/operator.overloading.py:
--------------------------------------------------------------------------------
1 | class Weird:
2 | def __init__(self, s):
3 | self._s = s
4 |
5 | def __len__(self):
6 | return len(self._s)
7 |
8 | def __bool__(self):
9 | return '42' in self._s
10 |
11 |
12 | weird = Weird('Hello! I am 9 years old!')
13 | print(len(weird)) # 24
14 | print(bool(weird)) # False
15 |
16 | weird2 = Weird('Hello! I am 42 years old!')
17 | print(len(weird2)) # 25
18 | print(bool(weird2)) # True
19 |
--------------------------------------------------------------------------------
/ch10/regex/regex/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for regex project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "regex.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/ch12/pwdweb/pwdweb/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for pwdweb project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pwdweb.settings")
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/ch7/exceptions/try.syntax.py:
--------------------------------------------------------------------------------
1 |
2 | def try_syntax(numerator, denominator):
3 | try:
4 | print('In the try block: {}/{}'
5 | .format(numerator, denominator))
6 | result = numerator / denominator
7 | except ZeroDivisionError as zde:
8 | print(zde)
9 | else:
10 | print('The result is:', result)
11 | return result
12 | finally:
13 | print('Exiting')
14 |
15 | print(try_syntax(12, 4))
16 | print(try_syntax(11, 0))
17 |
--------------------------------------------------------------------------------
/ch10/regex/entries/models.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.db import models
3 | from django.contrib.auth.models import User
4 | from django.utils import timezone
5 |
6 |
7 | class Entry(models.Model):
8 | user = models.ForeignKey(User)
9 | pattern = models.CharField(max_length=255)
10 | test_string = models.CharField(max_length=255)
11 | date_added = models.DateTimeField(default=timezone.now)
12 |
13 | class Meta:
14 | verbose_name_plural = 'entries'
15 |
--------------------------------------------------------------------------------
/ch5/performances.map.py:
--------------------------------------------------------------------------------
1 | from time import time
2 |
3 | mx = 2 * 10 ** 7
4 |
5 | t = time()
6 | absloop = []
7 | for n in range(mx):
8 | absloop.append(abs(n))
9 | print('for loop: {:.4f} s'.format(time() - t))
10 |
11 | t = time()
12 | abslist = [abs(n) for n in range(mx)]
13 | print('list comprehension: {:.4f} s'.format(time() - t))
14 |
15 | t = time()
16 | absmap = list(map(abs, range(mx)))
17 | print('map: {:.4f} s'.format(time() - t))
18 |
19 | print(absloop == abslist == absmap)
20 |
--------------------------------------------------------------------------------
/ch6/oop/class.methods.factory.py:
--------------------------------------------------------------------------------
1 | class Point:
2 |
3 | def __init__(self, x, y):
4 | self.x = x
5 | self.y = y
6 |
7 | @classmethod
8 | def from_tuple(cls, coords): # cls is Point
9 | return cls(*coords)
10 |
11 | @classmethod
12 | def from_point(cls, point): # cls is Point
13 | return cls(point.x, point.y)
14 |
15 |
16 | p = Point.from_tuple((3, 7))
17 | print(p.x, p.y) # 3 7
18 | q = Point.from_point(p)
19 | print(q.x, q.y) # 3 7
20 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templates/records/home.html:
--------------------------------------------------------------------------------
1 | {% extends "records/base.html" %}
2 | {% block title %}Welcome to the Records website.{% endblock %}
3 |
4 | {% block page-content %}
5 | Welcome {{ user.first_name }}!
6 | To create a record click
7 |
here.
8 |
9 | To see all records click
10 |
here.
11 |
12 | {% endblock page-content %}
13 |
--------------------------------------------------------------------------------
/ch4/arguments.variable.db.py:
--------------------------------------------------------------------------------
1 | def connect(**options):
2 | conn_params = {
3 | 'host': options.get('host', '127.0.0.1'),
4 | 'port': options.get('port', 5432),
5 | 'user': options.get('user', ''),
6 | 'pwd': options.get('pwd', ''),
7 | }
8 | print(conn_params)
9 | # we then connect to the db (commented out)
10 | # db.connect(**conn_params)
11 |
12 | connect()
13 | connect(host='127.0.0.42', port=5433)
14 | connect(port=5431, user='fab', pwd='gandalf')
15 |
--------------------------------------------------------------------------------
/ch6/decorators/time.measure.deco1.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 |
3 | def f(sleep_time=0.1):
4 | sleep(sleep_time)
5 |
6 | def measure(func):
7 | def wrapper(*args, **kwargs):
8 | t = time()
9 | func(*args, **kwargs)
10 | print(func.__name__, 'took:', time() - t)
11 | return wrapper
12 |
13 | f = measure(f) # decoration point
14 |
15 | f(0.2) # f took: 0.2002875804901123
16 | f(sleep_time=0.3) # f took: 0.3003721237182617
17 | print(f.__name__) # wrapper <- ouch!
18 |
--------------------------------------------------------------------------------
/ch4/func.attributes.py:
--------------------------------------------------------------------------------
1 | def multiplication(a, b=1):
2 | """Return a multiplied by b. """
3 | return a * b
4 |
5 |
6 | if __name__ == "__main__":
7 |
8 | special_attributes = [
9 | "__doc__", "__name__", "__qualname__", "__module__",
10 | "__defaults__", "__code__", "__globals__", "__dict__",
11 | "__closure__", "__annotations__", "__kwdefaults__",
12 | ]
13 |
14 | for attribute in special_attributes:
15 | print(attribute, '->', getattr(multiplication, attribute))
16 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templates/records/record_confirm_delete.html:
--------------------------------------------------------------------------------
1 | {% extends "records/base.html" %}
2 | {% block title %}Delete record{% endblock title %}
3 |
4 | {% block page-content %}
5 | Confirm Record Deletion
6 |
12 | {% endblock page-content %}
13 |
--------------------------------------------------------------------------------
/ch8/simple_server/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Cool Owls!
4 |
5 | Welcome to my owl gallery
6 |
7 |

8 |

9 |

10 |

11 |

12 |
13 | Do you like my owls?
14 |
15 |
16 |
--------------------------------------------------------------------------------
/ch10/regex/entries/admin.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from django.contrib import admin
3 |
4 | from .models import Entry
5 |
6 |
7 | @admin.register(Entry)
8 | class EntryAdmin(admin.ModelAdmin):
9 | fieldsets = [
10 | ('Regular Expression',
11 | {'fields': ['pattern', 'test_string']}),
12 | ('Other Information',
13 | {'fields': ['user', 'date_added']}),
14 | ]
15 | list_display = ('pattern', 'test_string', 'user')
16 | list_filter = ['user']
17 | search_fields = ['test_string']
18 |
--------------------------------------------------------------------------------
/tests/test_ch7/test_filter_funcs_final_triangulation.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase, expectedFailure
2 | from nose.tools import assert_list_equal
3 |
4 | from ch7.filter_funcs_triangulation import filter_ints
5 |
6 |
7 | class FilterIntsTestCase(TestCase):
8 |
9 | @expectedFailure
10 | def test_filter_ints_return_value(self):
11 | v1 = [3, -4, 0, -2, 5, 0, 8, -1]
12 | v2 = [7, -3, 0, 0, 9, 1]
13 |
14 | assert_list_equal([3, 5, 8], filter_ints(v1))
15 | assert_list_equal([7, 9, 1], filter_ints(v2))
16 |
--------------------------------------------------------------------------------
/ch1/scopes3.py:
--------------------------------------------------------------------------------
1 | # Local, Enclosing and Global
2 |
3 |
4 | def enclosing_func():
5 | m = 13
6 |
7 | def local():
8 | # m doesn't belong to the scope defined by the local
9 | # function so Python will keep looking into the next
10 | # enclosing scope. This time m is found in the enclosing
11 | # scope
12 | print(m, 'printing from the local scope')
13 |
14 | # calling the function local
15 | local()
16 |
17 | m = 5
18 | print(m, 'printing from the global scope')
19 |
20 | enclosing_func()
21 |
--------------------------------------------------------------------------------
/ch11/custom_timestamp.py:
--------------------------------------------------------------------------------
1 | from time import sleep
2 |
3 |
4 | def debug(*msg, timestamp=[None]):
5 | print(*msg)
6 | from time import time # local import
7 | if timestamp[0] is None:
8 | timestamp[0] = time() #1
9 | else:
10 | now = time()
11 | print(' Time elapsed: {:.3f}s'.format(
12 | now - timestamp[0]))
13 | timestamp[0] = now #2
14 |
15 |
16 | debug('Entering nasty piece of code...')
17 | sleep(.3)
18 | debug('First step done.')
19 | sleep(.5)
20 | debug('Second step done.')
21 |
--------------------------------------------------------------------------------
/ch3/binary.py:
--------------------------------------------------------------------------------
1 | """
2 | 6 / 2 = 3 (remainder: 0)
3 | 3 / 2 = 1 (remainder: 1)
4 | 1 / 2 = 0 (remainder: 1)
5 | List of remainders: 0, 1, 1.
6 | Inverse is 1, 1, 0, which is also the binary repres. of 6: 110
7 | """
8 |
9 | n = 39
10 | remainders = []
11 | while n > 0:
12 | remainder = n % 2 # remainder of division by 2
13 | remainders.append(remainder) # we keep track of remainders
14 | n //= 2 # we divide n by 2
15 |
16 | # reassign the list to its reversed copy and print it
17 | remainders = remainders[::-1]
18 | print(remainders)
19 |
--------------------------------------------------------------------------------
/ch5/first.n.squares.manual.py:
--------------------------------------------------------------------------------
1 | def get_squares_gen(n):
2 | for x in range(n):
3 | yield x ** 2
4 |
5 | squares = get_squares_gen(4) # this creates a generator object
6 | print(squares) #
7 | print(next(squares)) # prints: 0
8 | print(next(squares)) # prints: 1
9 | print(next(squares)) # prints: 4
10 | print(next(squares)) # prints: 9
11 | # the following raises StopIteration, the generator is exhausted,
12 | # any further call to next will keep raising StopIteration
13 | print(next(squares))
14 |
--------------------------------------------------------------------------------
/ch2/bytearray.py:
--------------------------------------------------------------------------------
1 | # bytearray.py
2 |
3 |
4 | >>> bytearray() # empty bytearray object
5 | bytearray(b'')
6 | >>> bytearray(10) # zero-filled instance with given length
7 | bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
8 | >>> bytearray(range(5)) # bytearray from iterable of integers
9 | bytearray(b'\x00\x01\x02\x03\x04')
10 | >>> name = bytearray(b'Lina') #A - bytearray from bytes
11 | >>> name.replace(b'L', b'l')
12 | bytearray(b'lina')
13 | >>> name.endswith(b'na')
14 | True
15 | >>> name.upper()
16 | bytearray(b'LINA')
17 | >>> name.count(b'L')
18 | 1
19 |
--------------------------------------------------------------------------------
/ch5/pythagorean.triple.generation.py:
--------------------------------------------------------------------------------
1 | from functions import gcd
2 |
3 |
4 | N = 50
5 |
6 | triples = sorted( # 1
7 | ((a, b, c) for a, b, c in ( # 2
8 | ((m**2 - n**2), (2 * m * n), (m**2 + n**2)) # 3
9 | for m in range(1, int(N**.5) + 1) # 4
10 | for n in range(1, m) # 5
11 | if (m - n) % 2 and gcd(m, n) == 1 # 6
12 | ) if c <= N), key=lambda *triple: sum(*triple) # 7
13 | )
14 |
15 |
16 | print(triples)
17 |
--------------------------------------------------------------------------------
/ch2/objects.py:
--------------------------------------------------------------------------------
1 | # objects.py
2 |
3 | # code block # 1
4 | >>> age = 42
5 | >>> age
6 | 42
7 | >>> age = 43 #A
8 | >>> age
9 | 43
10 |
11 |
12 | # code block # 2
13 | >>> age = 42
14 | >>> id(age)
15 | 10456352
16 | >>> age = 43
17 | >>> id(age)
18 | 10456384
19 |
20 |
21 | # code block # 3
22 | >>> class Person():
23 | ... def __init__(self, age):
24 | ... self.age = age
25 | ...
26 | >>> fab = Person(age=39)
27 | >>> fab.age
28 | 39
29 | >>> id(fab)
30 | 139632387887456
31 | >>> fab.age = 29 # I wish!
32 | >>> id(fab)
33 | 139632387887456 # still the same id
34 |
--------------------------------------------------------------------------------
/ch4/arguments.keyword.only.py:
--------------------------------------------------------------------------------
1 | def kwo(*a, c):
2 | print(a, c)
3 |
4 | kwo(1, 2, 3, c=7) # prints: (1, 2, 3) 7
5 | kwo(c=4) # prints: () 4
6 | # kwo(1, 2) # breaks, invalid syntax, with the following error
7 | # TypeError: kwo() missing 1 required keyword-only argument: 'c'
8 |
9 | def kwo2(a, b=42, *, c):
10 | print(a, b, c)
11 |
12 | kwo2(3, b=7, c=99) # prints: 3 7 99
13 | kwo2(3, c=13) # prints: 3 42 13
14 | # kwo2(3, 23) # breaks, invalid syntax, with the following error
15 | # TypeError: kwo2() missing 1 required keyword-only argument: 'c'
16 |
--------------------------------------------------------------------------------
/ch6/oop/private.attrs.py:
--------------------------------------------------------------------------------
1 | class A:
2 | def __init__(self, factor):
3 | self._factor = factor
4 |
5 | def op1(self):
6 | print('Op1 with factor {}...'.format(self._factor))
7 |
8 | class B(A):
9 | def op2(self, factor):
10 | self._factor = factor
11 | print('Op2 with factor {}...'.format(self._factor))
12 |
13 |
14 | obj = B(100)
15 | obj.op1() # Op1 with factor 100...
16 | obj.op2(42) # Op2 with factor 42...
17 | obj.op1() # Op1 with factor 42... <- This is BAD
18 |
19 | print(obj.__dict__.keys())
20 | # dict_keys(['_factor'])
21 |
--------------------------------------------------------------------------------
/ch6/decorators/time.measure.deco2.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 | from functools import wraps
3 |
4 |
5 | def measure(func):
6 | @wraps(func)
7 | def wrapper(*args, **kwargs):
8 | t = time()
9 | func(*args, **kwargs)
10 | print(func.__name__, 'took:', time() - t)
11 | return wrapper
12 |
13 |
14 | @measure
15 | def f(sleep_time=0.1):
16 | """I'm a cat. I love to sleep! """
17 | sleep(sleep_time)
18 |
19 |
20 | f(sleep_time=0.3) # f took: 0.30039525032043457
21 | print(f.__name__, ':', f.__doc__)
22 | # f : I'm a cat. I love to sleep!
23 |
--------------------------------------------------------------------------------
/ch5/generator.expressions.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> cubes = [k**3 for k in range(10)] # regular list
4 | >>> cubes
5 | [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
6 | >>> type(cubes)
7 |
8 | >>> cubes_gen = (k**3 for k in range(10)) # create as generator
9 | >>> cubes_gen
10 | at 0x7ff26b5db990>
11 | >>> type(cubes_gen)
12 |
13 | >>> list(cubes_gen) # this will exhaust the generator
14 | [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
15 | >>> list(cubes_gen) # nothing more to give
16 | []
17 |
--------------------------------------------------------------------------------
/ch4/data.science.example.py:
--------------------------------------------------------------------------------
1 | def do_report(data_source):
2 | # fetch and prepare data
3 | data = fetch_data(data_source)
4 | parsed_data = parse_data(data)
5 | filtered_data = filter_data(parsed_data)
6 | polished_data = polish_data(filtered_data)
7 |
8 | # run algorithms on data
9 | final_data = analyse(polished_data)
10 |
11 | # create and return report
12 | report = Report(final_data)
13 | return report
14 |
15 |
16 | if __name__ == "__main__":
17 |
18 | print(
19 | "Please don't call the `do_report` function. "
20 | "It's just and example."
21 | )
22 |
--------------------------------------------------------------------------------
/ch6/oop/class.attribute.shadowing.py:
--------------------------------------------------------------------------------
1 | class Point():
2 | x = 10
3 | y = 7
4 |
5 | p = Point()
6 | print(p.x) # 10 (from class attribute)
7 | print(p.y) # 7 (from class attribute)
8 |
9 | p.x = 12 # p gets its own `x` attribute
10 | print(p.x) # 12 (now found on the instance)
11 | print(Point.x) # 10 (class attribute still the same)
12 |
13 | del p.x # we delete instance attribute
14 | print(p.x) # 10 (now search has to go again to find class attr)
15 |
16 | p.z = 3 # let's make it a 3D point
17 | print(p.z) # 3
18 |
19 | print(Point.z)
20 | # AttributeError: type object 'Point' has no attribute 'z'
21 |
--------------------------------------------------------------------------------
/ch6/oop/private.attrs.fixed.py:
--------------------------------------------------------------------------------
1 | class A:
2 | def __init__(self, factor):
3 | self.__factor = factor
4 |
5 | def op1(self):
6 | print('Op1 with factor {}...'.format(self.__factor))
7 |
8 | class B(A):
9 | def op2(self, factor):
10 | self.__factor = factor
11 | print('Op2 with factor {}...'.format(self.__factor))
12 |
13 |
14 | obj = B(100)
15 | obj.op1() # Op1 with factor 100...
16 | obj.op2(42) # Op2 with factor 42...
17 | obj.op1() # Op1 with factor 100... <- Wohoo! Now it's GOOD!
18 |
19 | print(obj.__dict__.keys())
20 | # dict_keys(['_A__factor', '_B__factor'])
21 |
--------------------------------------------------------------------------------
/ch6/oop/super.explicit.py:
--------------------------------------------------------------------------------
1 | class Book:
2 |
3 | def __init__(self, title, publisher, pages):
4 | self.title = title
5 | self.publisher = publisher
6 | self.pages = pages
7 |
8 |
9 | class Ebook(Book):
10 |
11 | def __init__(self, title, publisher, pages, format_):
12 | Book.__init__(self, title, publisher, pages)
13 | self.format_ = format_
14 |
15 |
16 | ebook = Ebook('Learning Python', 'Packt Publishing', 360, 'PDF')
17 | print(ebook.title) # Learning Python
18 | print(ebook.publisher) # Packt Publishing
19 | print(ebook.pages) # 360
20 | print(ebook.format_) # PDF
21 |
--------------------------------------------------------------------------------
/ch4/lambda.explained.py:
--------------------------------------------------------------------------------
1 | """
2 | myfunc = lambda [parameter_list]: expression
3 |
4 | def myfunc([parameter_list]):
5 | return expression
6 | """
7 |
8 | # example 1: adder
9 | def adder(a, b):
10 | return a + b
11 |
12 | # is equivalent to:
13 | adder_lambda = lambda a, b: a + b
14 |
15 | # example 2: to uppercase
16 | def to_upper(s):
17 | return s.upper()
18 |
19 | # is equivalent to:
20 | to_upper_lambda = lambda s: s.upper()
21 |
22 |
23 | if __name__ == "__main__":
24 |
25 | print(adder(3, 4))
26 | print(adder_lambda(3, 4))
27 |
28 | print(to_upper("Hello"))
29 | print(to_upper_lambda("Hello"))
30 |
--------------------------------------------------------------------------------
/ch3/discount.py:
--------------------------------------------------------------------------------
1 | from datetime import date, timedelta
2 |
3 | today = date.today()
4 | tomorrow = today + timedelta(days=1) # today + 1 day is tomorrow
5 | products = [
6 | {'sku': '1', 'expiration_date': today, 'price': 100.0},
7 | {'sku': '2', 'expiration_date': tomorrow, 'price': 50},
8 | {'sku': '3', 'expiration_date': today, 'price': 20},
9 | ]
10 |
11 | for product in products:
12 | if product['expiration_date'] != today:
13 | continue
14 | product['price'] *= 0.8 # equivalent to applying 20% discount
15 | print(
16 | 'Price for sku', product['sku'],
17 | 'is now', product['price'])
18 |
--------------------------------------------------------------------------------
/ch4/return.multiple.py:
--------------------------------------------------------------------------------
1 | def moddiv(a, b):
2 | return a // b, a % b
3 |
4 |
5 | def test(n=10**4):
6 | from random import choice, random, randint
7 | m = 10 ** 6
8 | for x in range(n):
9 | a = choice((randint(0, m), m * random()))
10 | b = 0
11 | while not b:
12 | b = choice((randint(1, m), m * random()))
13 |
14 | r = divmod(a, b)
15 | r2 = moddiv(a, b)
16 | if r != r2:
17 | print('Difference: ', a, b, r, r2)
18 |
19 |
20 | if __name__ == "__main__":
21 |
22 | test(10 ** 6)
23 | print('Done')
24 |
25 | print(moddiv(20, 7)) # prints (2, 6)
26 |
--------------------------------------------------------------------------------
/ch2/defaultdict.py:
--------------------------------------------------------------------------------
1 | # defaultdict.py
2 |
3 |
4 | >>> d = {}
5 | >>> d['age'] = d.get('age', 0) + 1 # age not there, we get 0 + 1
6 | >>> d
7 | {'age': 1}
8 | >>> d = {'age': 39}
9 | >>> d['age'] = d.get('age', 0) + 1 # age is there, we get 40
10 | >>> d
11 | {'age': 40}
12 |
13 |
14 | >>> from collections import defaultdict
15 | >>> dd = defaultdict(int) # int is the default type (0 the value)
16 | >>> dd['age'] += 1 # short for dd['age'] = dd['age'] + 1
17 | >>> dd
18 | defaultdict(, {'age': 1}) # 1, as expected
19 | >>> dd['age'] = 39
20 | >>> dd['age'] += 1
21 | >>> dd
22 | defaultdict(, {'age': 40}) # 40, as expected
23 |
--------------------------------------------------------------------------------
/ch5/pythagorean.triple.generation.for.py:
--------------------------------------------------------------------------------
1 | from functions import gcd
2 |
3 |
4 | def gen_triples(N):
5 | for m in range(1, int(N**.5) + 1): # 1
6 | for n in range(1, m): # 2
7 | if (m - n) % 2 and gcd(m, n) == 1: # 3
8 | c = m**2 + n**2 # 4
9 | if c <= N: # 5
10 | a = m**2 - n**2 # 6
11 | b = 2 * m * n # 7
12 | yield (a, b, c) # 8
13 |
14 |
15 | triples = sorted(
16 | gen_triples(50), key=lambda *triple: sum(*triple)) # 9
17 | print(triples)
18 |
--------------------------------------------------------------------------------
/ch7/exceptions/for.loop.py:
--------------------------------------------------------------------------------
1 | n = 100
2 | found = False
3 | for a in range(n):
4 | if found: break
5 | for b in range(n):
6 | if found: break
7 | for c in range(n):
8 | if 42 * a + 17 * b + c == 5096:
9 | found = True
10 | print(a, b, c) # 79 99 95
11 |
12 |
13 | class ExitLoopException(Exception):
14 | pass
15 |
16 | try:
17 | n = 100
18 | for a in range(n):
19 | for b in range(n):
20 | for c in range(n):
21 | if 42 * a + 17 * b + c == 5096:
22 | raise ExitLoopException(a, b, c)
23 | except ExitLoopException as ele:
24 | print(ele) # (79, 99, 95)
25 |
--------------------------------------------------------------------------------
/ch2/tuples.py:
--------------------------------------------------------------------------------
1 | # tuples.py
2 |
3 |
4 | >>> t = () # empty tuple
5 | >>> type(t)
6 |
7 | >>> one_element_tuple = (42, ) # you need the comma!
8 | >>> three_elements_tuple = (1, 3, 5) # braces are optional here
9 | >>> a, b, c = 1, 2, 3 # tuple for multiple assignment
10 | >>> a, b, c # implicit tuple to print with one instruction
11 | (1, 2, 3)
12 | >>> 3 in three_elements_tuple # membership test
13 | True
14 |
15 |
16 | # swap
17 | >>> a, b = 1, 2
18 | >>> c = a # we need three lines and a temporary var c
19 | >>> a = b
20 | >>> b = c
21 | >>> a, b # a and b have been swapped
22 | (2, 1)
23 | >>> a, b = b, a # this is the Pythonic way to do it
24 | >>> a, b
25 | (1, 2)
26 |
--------------------------------------------------------------------------------
/ch10/regex/entries/static/entries/css/main.css:
--------------------------------------------------------------------------------
1 | /* HTML tags */
2 | a { color: #333; }
3 | /* Classes */
4 | .footer { margin-top: 1em; color: #333; }
5 | .entries-table { border-spacing: 0; padding-top: 1em; }
6 | .entries-table thead { background-color: #333; color: #fff;
7 | padding: 2em; font-size: 1.4em; }
8 | .entries-table td { padding: 1em; vertical-align: top; }
9 | .light-gray { background-color: #eee; }
10 | .white { background-color: #fff; }
11 | .code { font-size: 1.1em; font-weight: bolder; color: #333; }
12 | .home-option { padding: .6em 0; }
13 | /* Messages */
14 | .success, .errorlist {font-size: 1.2em; font-weight: bold; }
15 | .success {color: #25B725; }
16 | .errorlist {color: #B12B2B; }
17 |
--------------------------------------------------------------------------------
/tests/test_ch7/test_filter_funcs_is_positive_correct.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from nose.tools import assert_equal, assert_list_equal
3 |
4 | from ch7.filter_funcs import (
5 | filter_ints, is_positive
6 | )
7 |
8 |
9 | class FilterIntsTestCase(TestCase):
10 |
11 | def test_filter_ints_return_value(self):
12 | v1 = [3, -4, 0, -2, 5, 0, 8, -1]
13 | v2 = [7, -3, 0, 0, 9, 1]
14 |
15 | assert_list_equal([3, 5, 8], filter_ints(v1))
16 | assert_list_equal([7, 9, 1], filter_ints(v2))
17 |
18 | def test_is_positive(self):
19 | assert_equal(False, is_positive(-1))
20 | assert_equal(False, is_positive(0))
21 | assert_equal(True, is_positive(1))
22 |
--------------------------------------------------------------------------------
/ch4/docstrings.py:
--------------------------------------------------------------------------------
1 | def square(n):
2 | """Return the square of a number n. """
3 | return n ** 2
4 |
5 | def get_username(userid):
6 | """Return the username of a user given their id. """
7 | return db.get(user_id=userid).username
8 |
9 |
10 | def connect(host, port, user, password):
11 | """Connect to a database.
12 |
13 | Connect to a PostgreSQL database directly, using the given
14 | parameters.
15 |
16 | :param host: The host IP.
17 | :param port: The desired port.
18 | :param user: The connection username.
19 | :param password: The connection password.
20 | :return: The connection object.
21 | """
22 | # body of the function here...
23 | return connection
24 |
--------------------------------------------------------------------------------
/ch10/regex/entries/templates/entries/insert.html:
--------------------------------------------------------------------------------
1 | {% extends "entries/base.html" %}
2 | {% block title%}Insert a new Entry{% endblock title %}
3 |
4 | {% block page-content %}
5 | {% if messages %}
6 | {% for message in messages %}
7 | {{ message }}
8 | {% endfor %}
9 | {% endif %}
10 |
11 | Insert a new Entry
12 |
16 | {% endblock page-content %}
17 |
18 | {% block footer %}
19 |
20 | {% include "entries/footer.html" %}
21 | {% endblock footer %}
22 |
--------------------------------------------------------------------------------
/ch6/oop/class.namespaces.py:
--------------------------------------------------------------------------------
1 | class Person():
2 | species = 'Human'
3 |
4 |
5 | print(Person.species) # Human
6 | Person.alive = True # Added dynamically!
7 | print(Person.alive) # True
8 |
9 | man = Person()
10 | print(man.species) # Human (inherited)
11 | print(man.alive) # True (inherited)
12 |
13 | Person.alive = False
14 | print(man.alive) # False (inherited)
15 |
16 | man.name = 'Darth'
17 | man.surname = 'Vader'
18 | print(man.name, man.surname) # Darth Vader
19 |
20 | print(Person.name)
21 | # This doesn't work. We try to access an instance attribute
22 | # from a class. Doing the opposite works, but this will give
23 | # the following error:
24 | # AttributeError: type object 'Person' has no attribute 'name'
25 |
--------------------------------------------------------------------------------
/ch6/oop/super.implicit.py:
--------------------------------------------------------------------------------
1 | class Book:
2 |
3 | def __init__(self, title, publisher, pages):
4 | self.title = title
5 | self.publisher = publisher
6 | self.pages = pages
7 |
8 |
9 | class Ebook(Book):
10 |
11 | def __init__(self, title, publisher, pages, format_):
12 | super().__init__(title, publisher, pages)
13 | # Another way to do the same thing is:
14 | # super(Ebook, self).__init__(title, publisher, pages)
15 | self.format_ = format_
16 |
17 |
18 | ebook = Ebook('Learning Python', 'Packt Publishing', 360, 'PDF')
19 | print(ebook.title) # Learning Python
20 | print(ebook.publisher) # Packt Publishing
21 | print(ebook.pages) # 360
22 | print(ebook.format_) # PDF
23 |
--------------------------------------------------------------------------------
/ch1/bike.py:
--------------------------------------------------------------------------------
1 | # bike.py
2 |
3 | # let's define the class Bike
4 | class Bike:
5 |
6 | def __init__(self, colour, frame_material):
7 | self.colour = colour
8 | self.frame_material = frame_material
9 |
10 | def brake(self):
11 | print("Braking!")
12 |
13 | # let's create a couple of instances
14 | red_bike = Bike('Red', 'Carbon fiber')
15 | blue_bike = Bike('Blue', 'Steel')
16 |
17 | # let's inspect the objects we have, instances of the Bike class.
18 | print(red_bike.colour) # prints: Red
19 | print(red_bike.frame_material) # prints: Carbon fiber
20 | print(blue_bike.colour) # prints: Blue
21 | print(blue_bike.frame_material) # prints: Steel
22 |
23 | # let's brake!
24 | red_bike.brake() # prints: Braking!
25 |
--------------------------------------------------------------------------------
/ch6/decorators/decorators.factory.py:
--------------------------------------------------------------------------------
1 | from functools import wraps
2 |
3 | def max_result(threshold):
4 | def decorator(func):
5 | @wraps(func)
6 | def wrapper(*args, **kwargs):
7 | result = func(*args, **kwargs)
8 | if result > threshold:
9 | print(
10 | 'Result is too big ({0}). Max allowed is {1}.'
11 | .format(result, threshold))
12 | return result
13 | return wrapper
14 | return decorator
15 |
16 | @max_result(75)
17 | def cube(n):
18 | return n ** 3
19 |
20 | @max_result(100)
21 | def square(n):
22 | return n ** 2
23 |
24 | @max_result(1000)
25 | def multiply(a, b):
26 | return a * b
27 |
28 | print(cube(5))
29 |
--------------------------------------------------------------------------------
/tests/test_ch7/test_filter_funcs_is_positive_better.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from nose.tools import assert_equal, assert_list_equal
3 |
4 | from ch7.filter_funcs import (
5 | filter_ints, is_positive
6 | )
7 |
8 |
9 | class FilterIntsTestCase(TestCase):
10 |
11 | def test_filter_ints_return_value(self):
12 | v1 = [3, -4, 0, -2, 5, 0, 8, -1]
13 | v2 = [7, -3, 0, 0, 9, 1]
14 |
15 | assert_list_equal([3, 5, 8], filter_ints(v1))
16 | assert_list_equal([7, 9, 1], filter_ints(v2))
17 |
18 | def test_is_positive(self):
19 | assert_equal(False, is_positive(0))
20 | for n in range(1, 10 ** 4):
21 | assert_equal(False, is_positive(-n))
22 | assert_equal(True, is_positive(n))
23 |
--------------------------------------------------------------------------------
/ch6/decorators/syntax.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | # ONE DECORATOR
4 | def func(arg1, arg2, ...):
5 | pass
6 |
7 | func = decorator(func)
8 |
9 | # is equivalent to the following:
10 |
11 | @decorator
12 | def func(arg1, arg2, ...):
13 | pass
14 |
15 |
16 | # TWO DECORATORS
17 | def func(arg1, arg2, ...):
18 | pass
19 |
20 | func = deco1(deco2(func))
21 |
22 | # is equivalent to the following:
23 |
24 | @deco1
25 | @deco2
26 | def func(arg1, arg2, ...):
27 | pass
28 |
29 | # DECORATOR WITH ARGUMENTS
30 | def func(arg1, arg2, ...):
31 | pass
32 |
33 | func = decoarg(arg_a, arg_b)(func)
34 |
35 | # is equivalent to the following:
36 |
37 | @decoarg(arg_a, arg_b)
38 | def func(arg1, arg2, ...):
39 | pass
40 |
--------------------------------------------------------------------------------
/tests/test_ch7/test_filter_funcs_is_positive_loose.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from nose.tools import assert_equal, assert_list_equal
3 |
4 | from ch7.filter_funcs import (
5 | filter_ints, is_positive
6 | )
7 |
8 |
9 | class FilterIntsTestCase(TestCase):
10 |
11 | def test_filter_ints_return_value(self):
12 | v1 = [3, -4, 0, -2, 5, 0, 8, -1]
13 | v2 = [7, -3, 0, 0, 9, 1]
14 |
15 | assert_list_equal([3, 5, 8], filter_ints(v1))
16 | assert_list_equal([7, 9, 1], filter_ints(v2))
17 |
18 | def test_is_positive(self):
19 | assert_equal(False, is_positive(-2)) # before boundary
20 | assert_equal(False, is_positive(0)) # on the boundary
21 | assert_equal(True, is_positive(2)) # after the boundary
22 |
--------------------------------------------------------------------------------
/ch3/coupons.dict.py:
--------------------------------------------------------------------------------
1 | customers = [
2 | dict(id=1, total=200, coupon_code='F20'), # F20: fixed, £20
3 | dict(id=2, total=150, coupon_code='P30'), # P30: percent, 30%
4 | dict(id=3, total=100, coupon_code='P50'), # P50: percent, 50%
5 | dict(id=4, total=110, coupon_code='F15'), # F15: fixed, £15
6 | ]
7 | discounts = {
8 | 'F20': (0.0, 20.0), # each value is (percent, fixed)
9 | 'P30': (0.3, 0.0),
10 | 'P50': (0.5, 0.0),
11 | 'F15': (0.0, 15.0),
12 | }
13 | for customer in customers:
14 | code = customer['coupon_code']
15 | percent, fixed = discounts.get(code, (0.0, 0.0))
16 | customer['discount'] = percent * customer['total'] + fixed
17 |
18 | for customer in customers:
19 | print(customer['id'], customer['total'], customer['discount'])
20 |
--------------------------------------------------------------------------------
/ch6/decorators/two.decorators.py:
--------------------------------------------------------------------------------
1 | from time import sleep, time
2 | from functools import wraps
3 |
4 | def measure(func):
5 | @wraps(func)
6 | def wrapper(*args, **kwargs):
7 | t = time()
8 | result = func(*args, **kwargs)
9 | print(func.__name__, 'took:', time() - t)
10 | return result
11 | return wrapper
12 |
13 | def max_result(func):
14 | @wraps(func)
15 | def wrapper(*args, **kwargs):
16 | result = func(*args, **kwargs)
17 | if result > 100:
18 | print('Result is too big ({0}). Max allowed is 100.'
19 | .format(result))
20 | return result
21 | return wrapper
22 |
23 | @measure
24 | @max_result
25 | def cube(n):
26 | return n ** 3
27 |
28 | print(cube(2))
29 | print(cube(5))
30 |
--------------------------------------------------------------------------------
/ch10/regex/entries/templates/entries/home.html:
--------------------------------------------------------------------------------
1 | {% extends "entries/base.html" %}
2 | {% block title%}Welcome to the Entry website.{% endblock title %}
3 |
4 | {% block page-content %}
5 | Welcome {{ user.first_name }}!
6 |
7 | To see the list of your entries
8 | please click
here.
9 |
10 | To insert a new entry please click
11 |
here.
12 |
13 | To login as another user please click
14 |
here.
15 |
16 | To go to the admin panel
17 | please click
here.
18 |
19 | {% endblock page-content %}
20 |
--------------------------------------------------------------------------------
/ch3/errorsalert.py:
--------------------------------------------------------------------------------
1 | # this example won't work unless you define a send_email function.
2 | # so I'm defining it here as a trick, please pretend you didn't
3 | # see it. ;)
4 | def send_email(*a):
5 | print (*a)
6 |
7 | alert_system = 'console' # other value can be 'email'
8 | error_severity = 'critical' # other values: 'medium' or 'low'
9 | error_message = 'OMG! Something terrible happened!'
10 |
11 | if alert_system == 'console':
12 | print(error_message) #1
13 | elif alert_system == 'email':
14 | if error_severity == 'critical':
15 | send_email('admin@example.com', error_message) #2
16 | elif error_severity == 'medium':
17 | send_email('support.1@example.com', error_message) #3
18 | else:
19 | send_email('support.2@example.com', error_message) #4
20 |
--------------------------------------------------------------------------------
/ch12/pwdweb/records/templates/records/base.html:
--------------------------------------------------------------------------------
1 | {% load static from staticfiles %}
2 |
3 |
4 |
5 |
6 |
8 |
10 | {% block title %}Title{% endblock title %}
11 |
12 |
13 |
14 |
15 | {% block page-content %}{% endblock page-content %}
16 |
17 |
18 | {% block scripts %}
19 |
22 | {% endblock scripts %}
23 |
24 |
25 |
--------------------------------------------------------------------------------
/ch10/regex/entries/templates/entries/base.html:
--------------------------------------------------------------------------------
1 | {% load static from staticfiles %}
2 |
3 |
4 |
5 | {% block meta %}
6 |
7 |
9 | {% endblock meta %}
10 |
11 | {% block styles %}
12 |
14 | {% endblock styles %}
15 |
16 | {% block title %}Title{% endblock title %}
17 |
18 |
19 |
20 |
21 | {% block page-content %}
22 | {% endblock page-content %}
23 |
24 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/ch3/coupons.py:
--------------------------------------------------------------------------------
1 | customers = [
2 | dict(id=1, total=200, coupon_code='F20'), # F20: fixed, £20
3 | dict(id=2, total=150, coupon_code='P30'), # P30: percent, 30%
4 | dict(id=3, total=100, coupon_code='P50'), # P50: percent, 50%
5 | dict(id=4, total=110, coupon_code='F15'), # F15: fixed, £15
6 | ]
7 | for customer in customers:
8 | code = customer['coupon_code']
9 | if code == 'F20':
10 | customer['discount'] = 20.0
11 | elif code == 'F15':
12 | customer['discount'] = 15.0
13 | elif code == 'P30':
14 | customer['discount'] = customer['total'] * 0.3
15 | elif code == 'P50':
16 | customer['discount'] = customer['total'] * 0.5
17 | else:
18 | customer['discount'] = 0.0
19 |
20 | for customer in customers:
21 | print(customer['id'], customer['total'], customer['discount'])
22 |
--------------------------------------------------------------------------------
/ch5/map.example.py:
--------------------------------------------------------------------------------
1 | # This is not a valid Python module - Don't run it.
2 |
3 | >>> map(lambda *a: a, range(3)) # without wrapping in list...
4 |