Skip to content

Commit cbad767

Browse files
committed
Merge pull request yasoob#60 from Kwpolska/master
More Py3/PEP8 compliance + documentation for enum.Enum
2 parents 672c6f7 + 5f0e358 commit cbad767

6 files changed

Lines changed: 84 additions & 23 deletions

File tree

collections.rst

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ The ones which we will talk about are:
1111
- ``counter``
1212
- ``deque``
1313
- ``namedtuple``
14+
- ``enum.Enum`` (outside of the module; Python 3.4+)
1415

1516
1.\ ``defaultdict``
1617
^^^^^^^^^^^^^^^^^^^
@@ -277,7 +278,68 @@ Like this:
277278
from collections import namedtuple
278279
279280
Animal = namedtuple('Animal', 'name age type')
280-
perry = Animal(name="perry", age=31, type="cat")
281+
perry = Animal(name="Perry", age=31, type="cat")
281282
print(perry._asdict())
282-
# Output: OrderedDict([('name', 'perry'), ('age', 31), ...
283+
# Output: OrderedDict([('name', 'Perry'), ('age', 31), ...
284+
285+
5.\ ``enum.Enum`` (Python 3.4+)
286+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
287+
288+
Another useful collection is the enum object. It is available in the ``enum``
289+
module, in Python 3.4 and up (also available as a backport in PyPI named ``enum34``.)
290+
Enums (`enumerated type <https://en.wikipedia.org/wiki/Enumerated_type>`) are
291+
basically a way to organize various things.
292+
293+
Let’s consider the Animal namedtuple from the last example. It had a ``type``
294+
field. The problem is, the type was a string. This poses some problems for
295+
us. What if the user types in ``Cat`` because they held the Shift key? Or
296+
``CAT``? Or ``kitten``?
297+
298+
Enumerations can help us avoid this problem, by not using strings. Consider
299+
this example:
300+
301+
.. code:: python
302+
303+
from collections import namedtuple
304+
from enum import Enum
305+
306+
class Species(Enum):
307+
cat = 1
308+
dog = 2
309+
horse = 3
310+
aardvark = 4
311+
butterfly = 5
312+
owl = 6
313+
platypus = 7
314+
dragon = 8
315+
unicorn = 9
316+
# The list goes on and on...
317+
318+
# But we don't really care about age, so we can use an alias.
319+
kitten = 1
320+
puppy = 2
321+
322+
Animal = namedtuple('Animal', 'name age type')
323+
perry = Animal(name="Perry", age=31, type=Species.cat)
324+
drogon = Animal(name="Drogon", age=4, type=Species.dragon)
325+
tom = Animal(name="Tom", age=75, type=Species.cat)
326+
charlie = Animal(name="Charlie", age=2, type=Species.kitten)
327+
328+
# And now, some tests.
329+
>>> charlie.type == tom.type
330+
True
331+
>>> charlie.type
332+
<Species.cat: 1>
333+
334+
335+
This is much less error-prone. We have to be specific, and we should use only
336+
the enumeration to name types.
337+
338+
There are three ways to access enumeration members. For example, all three
339+
methods will get you the value for ``cat``:
340+
341+
.. code:: python
283342
343+
Species(1)
344+
Species['cat']
345+
Species.cat

context_managers.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ Let's try handling the exception in the ``__exit__`` method:
123123
def __enter__(self):
124124
return self.file_obj
125125
def __exit__(self, type, value, traceback):
126-
print "Exception has been handled"
126+
print("Exception has been handled")
127127
self.file_obj.close()
128128
return True
129129

coroutines.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ example would be a ``grep`` alternative in Python:
3434
.. code:: python
3535
3636
def grep(pattern):
37-
print "Searching for %s" % pattern
37+
print("Searching for", pattern)
3838
while True:
3939
line = (yield)
4040
if pattern in line:

decorators.rst

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ First of all let's understand functions in python:
3030
# We are not using parentheses here because we are not calling the function hi
3131
# instead we are just putting it into the greet variable. Let's try to run this
3232
33-
print greet()
33+
print(greet())
3434
# output: 'hi yasoob'
3535
3636
# Let's see what happens if we delete the old hi function!
@@ -51,7 +51,7 @@ other functions:
5151
.. code:: python
5252
5353
def hi(name="yasoob"):
54-
print "now you are inside the hi() function"
54+
print("now you are inside the hi() function")
5555
5656
def greet():
5757
return "now you are in the greet() function"
@@ -131,11 +131,11 @@ Giving a function as an argument to another function:
131131
return "hi yasoob!"
132132
133133
def doSomethingBeforeHi(func):
134-
print("I am doing some boring work before executing hi()")
134+
print("I am doing some boring work before executing hi()")
135135
print(func())
136136
137137
doSomethingBeforeHi(hi)
138-
#outputs:I am doing some boring work before executing hi()
138+
#outputs:I am doing some boring work before executing hi()
139139
# hi yasoob!
140140
141141
Now you have all the required knowledge to learn what decorators really
@@ -152,7 +152,7 @@ previous decorator and make a little bit more usable program:
152152
def a_new_decorator(a_func):
153153
154154
def wrapTheFunction():
155-
print "I am doing some boring work before executing a_func()"
155+
print("I am doing some boring work before executing a_func()")
156156
157157
a_func()
158158
@@ -170,7 +170,7 @@ previous decorator and make a little bit more usable program:
170170
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
171171
172172
a_function_requiring_decoration()
173-
#outputs:I am doing some boring work before executing a_function_requiring_decoration()
173+
#outputs:I am doing some boring work before executing a_function_requiring_decoration()
174174
# I am the function which needs some decoration to remove my foul smell
175175
# I am doing some boring work after executing a_function_requiring_decoration()
176176
@@ -185,12 +185,12 @@ run the previous code sample using @.
185185
186186
@a_new_decorator
187187
def a_function_requiring_decoration():
188-
"""Hey yo! Decorate me!"""
188+
"""Hey you! Decorate me!"""
189189
print("I am the function which needs some decoration to "
190-
" remove my foul smell")
190+
"remove my foul smell")
191191
192192
a_function_requiring_decoration()
193-
#outputs: I am doing some boring work before executing a_function_requiring_decoration()
193+
#outputs: I am doing some boring work before executing a_function_requiring_decoration()
194194
# I am the function which needs some decoration to remove my foul smell
195195
# I am doing some boring work after executing a_function_requiring_decoration()
196196
@@ -219,7 +219,7 @@ that is ``functools.wraps``. Let's modify our previous example to use
219219
def a_new_decorator(a_func):
220220
@wraps(a_func)
221221
def wrapTheFunction():
222-
print("I am doing some boring work before executing a_func()")
222+
print("I am doing some boring work before executing a_func()")
223223
a_func()
224224
print("I am doing some boring work after executing a_func()")
225225
return wrapTheFunction
@@ -236,7 +236,7 @@ that is ``functools.wraps``. Let's modify our previous example to use
236236
Now that is much better. Let's move on and learn some use-cases of
237237
decorators.
238238

239-
**Blueprint :**
239+
**Blueprint:**
240240

241241
.. code:: python
242242
@@ -313,7 +313,7 @@ Logging is another area where the decorators shine. Here is an example:
313313
314314
@logit
315315
def addition_func(x):
316-
"""does some math"""
316+
"""Do some math."""
317317
return x + x
318318
319319

for_-_else.rst

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ like this:
1313
1414
fruits = ['apple', 'banana', 'mango']
1515
for fruit in fruits:
16-
print fruit.capitalize()
16+
print(fruit.capitalize())
1717
1818
# Output: Apple
1919
# Banana
@@ -60,7 +60,7 @@ documentation:
6060
for n in range(2, 10):
6161
for x in range(2, n):
6262
if n % x == 0:
63-
print n, 'equals', x, '*', n/x
63+
print(n, 'equals', x, '*', n/x)
6464
break
6565
6666
It finds factors for numbers between 2 to 10. Now for the fun part. We
@@ -72,9 +72,8 @@ prime and tells us so:
7272
for n in range(2, 10):
7373
for x in range(2, n):
7474
if n % x == 0:
75-
print n, 'equals', x, '*', n/x
75+
prin( n, 'equals', x, '*', n/x)
7676
break
7777
else:
7878
# loop fell through without finding a factor
79-
print n, 'is a prime number'
80-
79+
print(n, 'is a prime number')

ternary_operators.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@ is some sample code:
3939
.. code:: python
4040
4141
fat = True
42-
fitness = ("skinny","fat")[fat]
43-
print("Ali is " + fitness)
42+
fitness = ("skinny", "fat")[fat]
43+
print("Ali is", fitness)
4444
# Output: Ali is fat
4545
4646
The above example is not widely used and is generally disliked by

0 commit comments

Comments
 (0)