Skip to content
Juha-Matti Santala - Community Builder. Dreamer. Adventurer.

Juha-Matti Santala - Community Builder. Dreamer. Adventurer.

The home of a developer community specialist.

hamatti.org
BLOCKCHAIN AND DISTRIBUTED LEDGERS

G is for get_or_create - Python A to Z

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month. Let’s take our first journey into the wonders of Django, my favourite web backend. One of the reasons I love it is its ORM which we’ll talk a bit more when we reach the midway of the month and letter O. Today, I want to show my appreciation for one of the methods in QuerySet: get_or_create which allows you to create new items in the database but if one already exists, it returns it instead. python from .models import Bread, BreadType # (here, Bread.bread_type is a ForeignKey to BreadType) breads_input = [{ 'id': 1, 'breadType': 'bun' } , ... ] for bread_data in breads: bread_type, type_created = BreadType.objects.get_or_create(type=bread_data['breadType']) bread, bread_created = Bread.objects.get_or_create(id=bread_data['id'], bread_type=bread_type) Here we process through some list of dictionaries (imagine it’s read from a JSON file or queried from a REST API). First, we try to create a new BreadType but if one already exists, we return a reference to it rather than creating a new one every time. Then we create a bread, using the previous reference. If we’d already have that specific bread inputted (maybe we ran the command twice), we want to get the existing one rather than creating new ones every time. I especially love using it in my data entry scripts / custom Django commands. Many of my applications operate on a model where I periodically input new data through these commands: for example in PokĆ©mon TCG app, when a new set is released. PokĆ©mon TCG is a great example. Right now, when my script reads in data for new cards, there are 13 such relationships between my Card model and other models. The codebase looks so much neater and easier to follow thanks to get_or_create. Edit later on Aug 8th: I rewrote the entire post to better explain what get_or_create does.
INTERNET OF THINGS AND SMART DEVICES

D is for dictionaries - Python A to Z

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month. Dictionary is a data structure in Python that in other contexts and languages is called an associative array, akey-value store or a map. It’s a handy and efficient data structure for when you need to store and retrieve a value based on a key. This is a 101 level introduction to dictionaries. ## Dictionary ### Creating a dictionary The basic form of dictionary can be created in couple of ways: python # dict constructor with keyword arguments scores = dict(Charlie=10, Patty=25, Snoopy=30) # dict constructor with tuples scores = dict(('Charlie', 10), ('Patty', 25), ('Snoopy', 30)) # key: value pairs scores = { 'Charlie': 10, 'Patty': 25, 'Snoopy': 30 } # dict comprehension data = [('Charlie', 10), ('Patty', 25), ('Snoopy', 30)] scores = { key: value for key, value in data } In each of these cases, the names are keys and numbers are values. There’s one big restriction to the keys of dictionaries: they need to be hashable: > An object is hashable if it has a hash value which never changes during its > lifetime (it needs a __hash__() method), > and can be compared to other objects (it needs an __eq__() method). Hashable objects which > compare equal must have the same hash value. So you can’t use a list as a key for example because it’s a mutable one. ### Accessing values Regardless of what was used to create it, we can access the values in a couple of ways: python scores = { 'Charlie': 10, 'Patty': 25, 'Snoopy': 30 } # With brackets scores['Charlie'] # == 10 # With .get() scores.get('Charlie') # == 10 The difference between these two is what happens when a key does not exist. python scores['Linus'] # raises KeyError: 'Linus' scores.get('Linus') # is None # We can give .get() a default value scores.get('Linus', 0) # == 0 ### Changing values Dictionaries are mutable data structures which means you can change their data. python # Set new value scores['Charlie'] = 15 # Modify a value scores['Charlie'] += 5 # Delete a key del scores['Charlie'] Since there is a direct ā€œone key to one valueā€ relationship, dictionaries are very handy in collecting data for or counting values belonging to this key. Let’s say we have a dataset where each time someone scores a point, their name is listed. We then want to count how may points each has: python marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = {} # Creating an empty dict for person in marks: # Go through every mark if person not in scores: # If it's not in the dict yet, scores[person] = 0 # create an entry with starting value 0 scores[person] += 1 # Add 1 point to this person print(scores) # {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} We’ll look a bit later how we can improve this with some of the special dictionaries but this basic structure of turning data into a dictionary is a fundamental basic to learn in Python. While the key needs to be hashable, the values can be anything. So instead of just increasing a number from zero upwards, we could store data as a list or another dictionary or whatever. ### Looping over python # By default, loops over keys in for-in for person in scores: print(person, scores[person]) # Loop over values for score in scores.values(): print(score) # Loop over both for person, score in scores.items(): print(person, score) ### Sorting a dictionary On a concept level, basic mapping does not have an order. In Python, dictionaries maintain the order the keys are inserted in and there are ways to force an order (like OrderedDict) but it’s a good baseline to base your knowledge of dictionaries on. However, when looping over a dictionary, you often want the data to be in some sort of order. In the earlier example when we counted marks to a dictionary, we might want to print it in an order of most points to least. For this, we can use sorted function: python # Let's recreate our dictionary scores = {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} for person in sorted(scores, key=scores.get, reverse=True): print(f'{person}: {scores[person]}') # Snoopy: 4 # Charlie: 3 # Patty: 1 The first argument to sorted is in this case our dictionary. The second key, key= is a single argument function that defines what is used for sorting (in this case, scores.get tells the function we want the values corresponding to the keys) and reverse= can be used to reverse the order from ascending to descending. It’s important to note that nothing internally in the dictionary changes when using sorted. It returns a new list with the keys sorted based on the sorting criteria. ### You’ll do just fine with dictionary for a long time Next, I’ll introduce some specialised dictionaries that are included in the standard library because developers have found these cases very useful. If you’re a new developer, I do recommend focusing on using and understanding the basic dictionary. There’s nothing in the following dictionaries that you can’t do in the basic one. Brian Holt once said this in one of his containers course: > When I don’t know how my tools work, I tend to resent them because they add > complexity to my life. > > When I understand what they are doing for me > and what I no longer have to do because the tool is doing it for me, I tend to > really like my tools. Jumping into the more advanced use cases before understanding the basics really well can be detrimental. Finish this blog post to see what’s out there but don’t be afraid to manually write the code they would let you skip over and over again so that you’ll gain a deeper understanding. ## defaultdict In the earlier example of creating and populating a dictionary, we had to check if a key existed before we could interact with it: python marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = {} # Creating an empty dict for person in marks: # Go through every mark if person not in scores: # If it's not in the dict yet, scores[person] = 0 # create an entry with starting value 0 scores[person] += 1 # Add 1 point to this person print(scores) # {'Charlie': 3, 'Patty': 1, 'Snoopy': 4} There’s a way to shortcut this by using a defaultdict: python from collections import defaultdict marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] # Create a new dictionary with # default value of 0 for each key scores = defaultdict(int) for person in marks: scores[person] += 1 print(scores) # defaultdict(<class 'int'>, {'Charlie': 3, 'Patty': 1, 'Snoopy': 4}) Passing int to defaultdict tells the dictionary to start from a default value of 0. You could also pass list and the default would be an empty list. As you can see comparing the two examples above, the code becomes way easier to read and comprehend. ## Counter Our example of counting things is such a common operation that there’s a special Counter dictionary for it. python from collections import Counter marks = [ 'Charlie', 'Charlie', 'Patty', 'Snoopy', 'Snoopy', 'Charlie', 'Snoopy', 'Snoopy' ] scores = Counter(marks) print(scores) # Counter({'Snoopy': 4, 'Charlie': 3, 'Patty': 1}) Not only does Counter help us in creation of it but it has a couple of really handy methods. I have written about Counter before and rather than repeating myself here, I recommend reading through that post.
CHARLIE
BLOCKCHAIN AND DISTRIBUTED LEDGERS

B is for batteries included - Python A to Z

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month. Python is often described as having batteries included > The Python source distribution has long maintained the philosophy of > ā€œbatteries includedā€ – having a rich and versatile standard library which is > immediately available, without making the user download separate packages. > This gives the Python language a head start in many projects. - from withdrawn PEP 206 I love Python’s batteries included philosophy and its standard library so much that I dedicated an entire Blaugust in 2024 writing about it: - Parsing nginx server logs with regular expressions - Reading and writing CSV with Python - Improve your code with namedtuples - Count ā€˜em - help() me Obi-Wan Kenobi, you’re my only hope - Improved print readability with pprint - Document intended usage through tests with doctest - Debug with pdb and breakpoint - Rotating turn order with deque - Data classes in Python with dataclasses - Combinatoric iterators from itertools - Write more pythonic code with context managers - Random number chosen by fair dice roll - Combine iterables with zip - map and filter with list comprehensions - Memoize with functools.cache - Keep track of happenings with logging - Bring your custom toolkit to REPL sessions - Serve local HTML and CSS files with http.server - Branch out with pattern matching - Test your codebase with unittest - Pretty print and validate JSON on command line with json.tool - Parse command line arguments with argparse - Quick prototyping with sqlite3 At PyCon Finland 2025, we got this cool LEGO Python logo that had batteries included:
BLOCKCHAIN AND DISTRIBUTED LEDGERS

On blogging, Blaugust and challenging yourself

## on blogging Why do we blog? There are a ton of reasons and everyone who blogs have their own motivations and reasons. You could ask every blogger you follow and probably get as many answers as you ask people. I write this blog because I have ideas rummaging in my head and I need to write them down to process them. Like Fran eloquently puts it: > Putting your words on paper, even if digitally, forces you to deal with the > core of the topic at hand. Writing ideas down in tangible form helps you discover gaps and structure those ideas in a way that helps me think them further and to have discussions about them with other people. None of that requires me to publish those writings though, so it only covers half of the picture. My motivation for publishing is that if I already worked through my ideas and wrote them down in a (hopefully coherent) form, why not publish. I enjoy sharing my ideas so they can be read, challenged and discussed by other people. That’s who I learn more. Sometimes I write and share to spread joy. Just this Monday, I wrote about a scene from a movie that I enjoyed. Maybe someone else will enjoy that, watch the movie and find joy in it. Yay. A lot of my technical blogging has to do with documenting what I’ve tried and learned. I write them down to my notes so I can discover them later when I inevitably run into the same or similar issue again. I share them because I’ve gotten a lot of help and ideas from other blogs in the internet and want to contribute to that pool of resources. At times of my career, I’ve also written about a lot of technical stuff to build a body of work to increase my chances of finding interesting work. ## on Blaugust Every August — for over a decade already —, a group of bloggers gather together in the blogosphere to celebrate blogging, to learn from each other, to encourage each other and to challenge themselves. That community and the month-long festival of blogging is called Blaugust and I’ve been participating since 2023. > For anyone arriving here for the very first time Blaugust is a month-long > event that takes place each August which focuses on blogging primarily and has > started to include other forms of serialized content over the last several > years. The goal is to stoke the fires of creativity and allow bloggers and > other content creators to mingle in a shared community while pushing each > other to post more regularly. Above all the goal of Blaugust has always been > to prove to folks that they can in fact sit down every day and create > something fresh and then share it with the world. / Belghast, https://aggronaut.com/2024/07/12/blaugust-2024-is-coming/ Last year, over 150 people participated in the challenge. (And some people say blogging is dead.) One of the original goals of Blaugust was to publish 31 blog posts in 31 days of August. Over the years, different alternative goals have been added to make it more serving for all sorts of bloggers. 31 in 31 is kinda hardcore but the positive effects appear on much lower amount of posts as well and the main goal is to encourage people to write. If you want to be one of those people this year, - Check out the info post by Nerd Girl Krikket - sign up - optionally join our lovely Discord community where you can share your ideas, your posts, ask for help or inspiration and get mental support for writing. The other challenges or goals are - Newbie Blogger Award – You did it! You joined Blaugust for the very first time and we are extremely happy to welcome you into this raucous community. As a result, we are going to recognize your efforts just for signing up. - Bronze Award – You made at least 5 posts during the month of August 2026. - Silver Award – You made at least 15 posts during the month of August 2026. - Gold Award – You made at least 25 posts during the month of August 2026. - Rainbow Diamond Award – You beat the original challenge and posted 31 times or more during the month of August 2026. ## on challenging yourself Let’s be clear: you don’t need to participate in any kind of online writing challenge or event to enjoy blogging or to write daily/weekly/monthly or to write thoughtful replies to other people’s posts. I find these events wonderful for the community that gathers around them. I’ve met so many wonderful people from around the world through things like Blaugust, IndieWeb Carnival, Junited or NaNoWriMo. The social accountability in these events helps me a lot. Publishing daily on the blog is tough. I’m proud I’ve managed to succeed in that already three Blaugusts in the running, I can’t imagine right now doing that for a longer period than one month a year. (Well, kinda twice because I do Advent of Code in December) There are no real stakes: if I don’t manage to get my 31 posts done, nothing happens. I’m not beholden to any contract or even a promise to finish and succeed in my goal. Even then, making that commitment to join and aim for a goal gives me a lot of will power to achieve it. I find that kind of stubbornness one of my biggest strengths in getting stuff done in general. Here’s my hot take on all of these, based on discussions I often have with people when I share the month’s Carnival theme or Blaugust or something else: you don’t have to follow any rules. Of course, that might mean that you’re not eligible to be part of the challenge or the event but none of these events are the point in themselves. Writing is. If an event like this gives you ideas and encouragement to write more, go ahead. We are all publishing in our own blogs and we are the ultimate arbiters of what goes into our blogs. Don’t let the ā€œcan I do X?ā€ questions in your head limit you from exploring ideas and topics in your blog just because they might not exactly match the rules of someone else’s challenge. For example, with IndieWeb Carnival, I always use the theme selected by the host and their introduction to it as a starting point but I give myself pretty much unlimited creative freedom on how much I follow it. If at the time of publishing that blog post, I feel I can justify its participation in that theme, I send it to the host. Sometimes I feel I’ve travelled too far from the original path for it to make sense but the Carnival has done its positive thing already. I then leave it up to the host to decide if they consider it an acceptable entry. Whether you have a blog already or not, I recommend joining Blaugust this year. In the community, we often repeat the mantra of ā€œthe only way to lose is not to participateā€. Every post you make is a win, even if you only publish one in August.
nik.artSylvia plays with wordsThe Ancient Gaming Noob

House rules are great

PleasantKenobi published a clickbaity video titled ā€œHouse Rules Don’t Work For Magicā€ in which he argues that people should not do house rules. It’s clickbaity because in the video he lists some house rules that he actually likes. More about that later. I commented on the video with ā€œMy hot take on house rules: if you don't like them, don't use them.ā€ I wanted to expand on my thoughts and comment on a bunch of points he made in his video. ## House rules in tabletop gaming Let’s start by talking about house rules in tabletop games in general and then touch on the topic of Magic. House rule is a rule that’s not part of the official rules of a game but that a group playing a game has agreed to introduce — usually to increase their enjoyment of the game. Some games, like UNO, are taught through tradition and are so riddled with house rules that you usually need to have a discussion every time before you start playing to make sure everyone’s on the same page with how the game works this time. UNO even encourages house rules by often introducing a few options in the rule book. House rules can be problematic if players are not careful. If you don’t know that some rule is a house rule and learn it thinking it’s the actual rules, it can be difficult to play with other groups. I think house rules are essentially a wonderful tool: if you like playing a game but there are some bits that make the game way less enjoyable to you and your friends, don’t waste your limited time worrying about it and come up with rules that make it better for you. There are two crucially important parts to house rules: clarity and consent. Everyone in the group should understand the house rules and they should agree to them before hand. Nobody else’s opinion matters but those who are playing at that game with those rules. Different people enjoy different things and if you own a game that with small changes can become even better for you and your group, please do so! ## House rules in Magic the Gathering PleasantKenobi is very clear in his video that not only does he not like house rules but he thinks nobody should play with them. His main argument is that Magic the Gathering is designed by good game designers and players making changes to the rules and balances of the game are worse. I don’t disagree on that. He says > The other problem I have with house rules is that a lot of them are fucking > shit and they kind of fuck the game up. I do disagree on that though: even if a house rule would ā€œobjectivelyā€ (in quotes because I’m not sure if it’s possible to measure) worse or less balanced but it creates a better gaming experience for people at the kitchen table, it does make it better. Of course bad house rules are bad, I don’t think anyone argues against that. The point of house rules is that they are for the group that is playing with them and if they work for them, then they are good. He also argues that problem with house rules in Magic the Gathering is that you might play with players outside of your house rule group in local game stores or tournaments. I’d argue it’s not a problem as long as you don’t try to enforce your own rules to others. One house rule he mentions that our Commander play group occasionally follows is a ā€œdraw 10, put 3 backā€ rule. A casual bracket 3 game of Commander usually takes around 60-90 minutes in our group. We play to have a good time and I think it’s great if everyone gets an opportunity to participate in a game that long. Having house rules on mulligans is not good for competitive gaming for sure but for a casual, ā€œlet’s hang out with friends and play a game or twoā€, I don’t think it’s worthy of one player missing out a full game because they bricked early on. Another argument of his is that you just need to ā€œget goodā€. He makes a good point — which I agree on — that some things you might want to house rule become less of an issue once you become better at the game: building decks, understanding complex interactions, making better decisions. However, that’s not a good reason to tell other people, who might just play in their casual kitchen table environment and never plan to play competitively, that changes they make that make the game more enjoyable to them is wrong or bad. ### A big part of Magic the Gathering is house rules One house rule that PleasantKenobi agrees on is playing custom formats but I think he makes the general mistake of ā€œwhat I like is good and doesn’t countā€. Commander is one of the most popular Magic the Gathering formats and even though it has rules of its own, it’s a massive house rule to the original official sanctioned rules of the game. It turns two player 60 card duels into 4 player multiplayer singleton 100 card battles. So are the other community made formats. Cubes, DandĆ¢n, Battle box and Party box are all house rules. They prove that house rules indeed do work in Magic the Gathering and often create the most enjoyable experiences to many players. At the end — after 15 minutes of bashing people for making house rules — he says > And I'm not saying you can't change the rules of magic to create a new thing > that you and your play group really enjoy. Once again, he actually argues that ā€œhouse rules I enjoy are good but ones that others enjoy are not if I don’t like themā€. Maybe it’s because Youtube rewards clickbait and ragebait content over good discussion but I’m holding people accountable for participating in that and make my comments based on what I see and hear. I’ll finish off by saying that PleasantKenobi’s videos are great and if you’re into Magic, I recommend checking his channel out.
MAGICPLEASANT KENOBI