Topics: collections.defaultdict Updated 2020-10-06 The collections module The collections module in Python contains several useful classes. One of them is especially helpful for our Magical Universe: collections.defaultdict. When defining our CastleKilmereMember class we specified self.traits to be an empty dictionary. New positive and negative traits can be added to a person using the add_trait() function. We can check whether a person possesses a certain trait using the exhibits_trait() function. The relevant parts of the class look as follows:
functools.wraps - avoiding losing metdata when applying decorators
Topics: functools.wraps We have discussed decorators on day 5, day 6 and day 20 already. Therefore, we know that decorators allow us to extend or modify the behavior of a function without permanently modifying the function itself. In our example we modified the says() function of our CastleKilmereMember class to be whispering instead of talking normally: class CastleKilmereMember: """ Creates a member of the Castle Kilmere School of Magic """ def __init__(self, name: str, birthyear: int, sex: str): self.
Custom exception classes
Topics: Custom exception classes Errors and Exceptions First of all, what is an exception? As outlined in the Python docs there are two big kinds of errors: syntax errors and exceptions. Syntax Error: A syntax error is an error that makes it impossible to parse a program. That’s why it’s also called a parsing error. Whenever we made a mistake in the syntax of our code (for example, we might forgot a ‘:’ somewhere) the parser will complain with a Syntax Error: invalid syntax, pointing us to the offending line.
Extending the Magical Universe
Topics: Extending the Magical Universe with classmethods for Charm, Hex, Curse, etc. Today I added classmethods to the different Spell subclasses. Speficially, I added one classmethod for each spell type: Charm, Transfiguration, Jinx, Hex, Curse, CounterSpell, HealingSpell such that at least one charm, hex, jinx, … exists in our universe. Tomorrow I will write test code for the entire abstract base class Spell.
Topics: Multisets, collections.Counter Counting objects Today I want to present a very useful class in Python: collections.Counter. You might wonder what is so great about this class: it allows us to count all kinds of objects! And who doesn’t love counting? For example, consider all the potion ingredients Cleon, Flynn and Cassidy need to buy for a school year. We can easily create a shopping list for them using collections.Counter.
Topics: Iterators, iterables and iteration Iterators Although we need to create more test functions for the other Magical Universe classes, I want to spend a few days on iterators. First of all, what is meant by the term iteration? Iteration describes the process of taking an item and looking at each of its components one by one. Any time we use a loop like for component in item: print(component) we use iteration.
Testing code with pytest
Topics: Testing code with pytest Updated 2020-10-05 Writing test functions for our code is extremely important. Since I have been lazy writing test code myself, I want to spend a little more time on this topic. My favorite testing framework is pytest. I’m not an expert on testing, so please consider this post an introduction to testing rather than a thorough guide. Why pytest? Using pytest has several advantages. First of all, pytest makes testing very easy because its syntax is simple and easy to understand.
Context managers and the `with` statement
Topics: with statement and context managers Updated 2020-10-05 Context managers and the with statement Similar to decorators, context managers are a concept many people use but only few understand. If you haven’t heard of the term ‘context manager’ before: you probably encountered them already while reading or writing from/to a file using the with statement. The most common use of context managers is the proper management of resources. In simple terms this means that we want to make sure that we open, read, write and close files correctly.
The mysterious `if __name__ == "__main__"`
Topics: What is if __name__ == "__main__" doing? I always wanted to dig into the statement if __name__ == "__main__" that is used in so many programs. I have used it for a long time already but until recently I had no idea what exactly it is doing. To make the topic as understandable as possible, I will divide the explanation into three steps. Step 1: Two ways of running code We saved our Magical Universe in a file named magical_universe.
Decorators within classes
Topics: Decorators within a class Updated 2020-10-05 After having talked about decorators already on day 5 and day 6 I would like to revisit the topic to discuss how decorators can be used within classes. Let’s put ourselves in the position of a Castle Kilmere member during the time the school is in war with Master Odon and his Dark Army. So these are dark, scary times. People at Castle Kilmere are constantly scared that something might happen to them, their family or their friends.
Immutable data classes
Topics: Immutable data classes Updated 2020-10-05 We have talked a lot about data classes in the last post. There is one further characteristic of data classes that I would like to study - immutability. We can make a dataclass immutable such that it fulfills the same purpose as typing.NamedTuple. To make a dataclass immutable we have to set frozen=True when creating the class. Let’s see how we can change our DarkArmyMember class from typing.
Topics: Data classes Updated 2020-10-05 Data classes are a feature that is new in Python 3.7. And taking a look at them is definitely worth it! Data classes According to the PEP on data classes, they are basically “mutable namedtuples with defaults”. We already looked at namedtuples on day 10 and 11. Namedtuples allow us to create an immutable class that primarily stores values (i.e. attributes). We used namedtuples for our DarkArmyMember class (because once you become a member of the dark army there is no way back.