Exception Handling

One of the most important features of Python is its ability to handle exceptions gracefully. Exception handling is the process of detecting and dealing with errors that occur during the execution of a program. In Python, exception handling is implemented using a combination of try, except, else, and finally blocks. Exception Handling The try block The try block is the section of code where you put the code that may raise an exception. It is essentially a “sandbox” where you can test your code for potential errors. If an exception occurs in the try block, the code execution jumps to the corresponding except block. ...

April 21, 2023 Â· 4 min Â· 656 words

Finding element with partial id in Selenium

I am currently automating some tasks with selenium and I faced a challenge where an element would render each time with a slightly different ID - the first part would be the same, but the ending would be different, such as id=navbarTop_13123. Part navbarTop_ would always be the same, but the ending different. Partial ID Selectors Partial ID selectors are a powerful feature of CSS selectors that allow you to select elements based on a partial match of their id attribute. This can be useful when the id attribute of an element contains a dynamic or changing value, and you need to select the element based on only part of the id attribute. ...

April 4, 2023 Â· 2 min Â· 237 words

Lambda functions

Python’s lambda function is a powerful tool for creating small, anonymous functions on the fly. Lambda functions are known as anonymous functions, because: they don’t have a name, are created and used at the same time. I have used the lambda function numerous times, especially when I needed to sort something on a specific key. Some benefits of using lambda functions: Concise code - no need to create new named functions if we are using it only once, Cleaner code - lambda functions are easy to read (with good naming practices), Flexibility - can be used in various situations - as an argument to another function, in a list comprehension or as the key function for sorting, No side effects - lambda functions are pure. This is very important when working with data that needs to be kept in its original state. Lambda functions, as mentioned above, are very handy when sorting more complex iterables. ...

March 28, 2023 Â· 2 min Â· 237 words

Pattern Matching

What is Pattern Matching Pattern matching is a newer feature that came with Python 3.10. Using pattern matching simplifies the code and improves readability. The other option is to write multiple if-else statements, but this can quickly become very unreadable. Example Consider these 2 examples. The first one using multiple if-else statements, the second one pattern matching - match/case. Which one is more readable? 1 2 3 4 5 6 7 8 9 10 # if-else statements if x == 'red': print("The color is red") elif x == 'blue': print("The color is blue") elif x == 'green': print("The color is green") else: print("Unknown color") 1 2 3 4 5 6 7 8 9 10 11 # Pattern matching match x: case 'red': print("The color is red") case 'blue': print("The color is blue") case 'green': print("The color is green") case _: print("Unknown color") This is a very simple example, and pattern matching can be also used in more complex situations where more conditions need to be met. ...

March 12, 2023 Â· 2 min Â· 249 words

Python Tricks: A Buffet of Awesome Python Features

No need to know everything Sometimes the most important skills for a programmer are “pattern recognition” and knowing where to look things up. Patterns for Cleaner Python Avoid currency rounding issues by using an int and set price in cents Assert Statement Internal self-checks for your program proper use of assertions is to inform developers about unrecoverable errors in program they are not intended to signal expected error (FileNotFound) from which a user can recover excellent debugging tool - if you reach assertion, you have a bug Common Pitfalls security risks possibility to write useless assertions 1. Don’t use asserts for data validation assert can be globally disabled (-0 -00 commands) validate data with regular if-else statements and raise exceptions on errors 2. Asserts that never fail passing a tuple as first argument always evaluates to true - remember truthy values this will never fail: 1 assert(1 == 2, 'This should fail.') Always make sure your tests can actually fail Comma Placement list/dict/set - end all of your lines with a comma 1 names = ['Peter', 'Alice', 'John',] splitting it into new lines is an excellent method for seeing what was changed (git) 1 2 3 4 5 names = [ 'Peter', 'Alice', 'John', ] leaving a comma avoids strings from getting merged Context Managers & the with statement with statement - write cleaner and more readable code simplify common resource management patterns encapsulates standard try/finally statements Context Managers protocol, that your objects needs to follow in order to support the with statement add __enter__ and __exit__ methods to an object if you want it to function as a context manager - these methods will be called in resource management cycle 1 2 3 4 5 6 7 8 9 10 11 class ManagedFile: def __init__(self, name): self.name = name def __enter__(self): self.file = open(self.name, 'w') return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() now we can use 1 2 3 with ManagedFile('hello.txt') as f: f.write('hello, word') f.write('bye now') you can also use @contextmanager decorator for this purpose Underscores, Dunders & More 1 2 3 4 5 6 # These are conventions, Python Interpreter doesn't check them _var # var meant for internal use var_ # next most fitting var name (first is taken) - class_ __var # Here Interpreter actualle steps in (name mangling) - it rewrites attribute name to avoid naming conflicts in subclasses __var__ # Interpreter doesn't care - these are used for special/magic methods _ # temporary or insignificant variable (for _ in range(10)...) _ is also good for unpacking when there are values in the middle for which you don’t care 1 2 car = ('red', 'auto', 12, 3812.4) color, _, _, mileage = car _ is also handy when constructing objects on the fly and assigning values without naming them first 1 2 3 4 5 6 >>> list() >>> _.append(1) >>> _.append(2) >>> _.append(3) >>> _ [1, 2, 3] Truth About String Formatting Python offers 4-ways to format strings 1 2 3 4 errno = 50159747054 name = 'Bob' # We want to output: 'Hey Bob, there is a 0xbadc.ffee error!' Old-style formatting: 'Hello, %s' % name - %s replace this as string; '%x' % errno - %x as int New-style formatting format() function 1 2 >>> 'Hello, {}'.format(name) 'Hello, Bob' Literal String Interpolation f-Strings f'Hello, {name}!' supports also expressions Template Strings simpler and less powerful, but in some cases very useful useful when it comes to safety 1 2 3 4 from string import Template t = Template('Hey, $name!') t.substitute(name=name) 'Hey, Bob!' When to use which method? If your format strings are user-supplied, use Template Strings to avoid security issues. Otherwise, use f-Strings. ...

February 18, 2023 Â· 19 min Â· 3991 words Â· Dan Bader

Useful One-Liners

There are a lot of tricks one can use in Python. So-called Python one-liners are one of them. It’s a nice way of shortening the length of the code. However, it’s good to know that sometimes, using the longer version might be the better choice when it comes to readability. Swapping two variables 1 2 3 4 a = 10 b = 20 a, b = b, a List comprehension 1 squares = [i*i for i in range(20)] Ternary operator 1 my_value = 30 if 5>3 else 50 Print only elements (unpacking) 1 2 numbers = [1, 2, 3, 4, 5] print(*numbers) Days remaining in a year 1 import datetime;print((datetime.date(2023,12,31)-datetime.date.today()).days) Reversing a list/string 1 2 letters = ['a', 'b', 'c', 'd', 'e'] print(letter[::-1]) Multiple variable assignments 1 age, city, position = 25, 'London', 'Python developer' Convert number strings into ints 1 2 strs = '1 2 3 4 5 6' ints = list(map(int, strs.split())) Read all lines of a file to a list 1 values = [line.strip() for line in open('document.txt', 'r')] Start an HTTP server in a terminal python -m http.server ...

February 18, 2023 Â· 1 min Â· 182 words

Small details that matter a lot

Each programming language has its own peculiarities - knowing these will make your code more reliable, and you will avoid unexpected behaviors and/or bugs. In Python, one such peculiarity, that I learned recently, is that you should not use mutable objects as default arguments. Let’s see why. Example You want a function that appends a number to a list. If the list is not passed, it appends data to a newly created list. ...

February 12, 2023 Â· 2 min Â· 255 words

The help() function

I am currently exploring the topic of objects a little more. Once you go a bit deeper into the topic, it can get quite complex and confusing (at least at first). What is pretty cool though is realizing that in Python, everything is an object. Basically, every value or data type is an instance of a class. For example, creating a new string like my_name = 'Peter' actually creates an object of the class str. That’s why we can also use methods such as upper() (and many others) as these come with the class. ...

January 23, 2023 Â· 2 min Â· 415 words

Asynchronous tasks with Celery & RabbitMQ

The Challenge I’m currently working on an application in Django which I hope to deploy in the upcoming weeks, it’s just that I fix one bug and another one appears, then tests pass, I add something new, suddenly nothing is working so I have to redesign the whole thing again. This has also prompted me to explore the topic of debugging a bit more recently. I guess that’s how we learn. ...

January 18, 2023 Â· 3 min Â· 525 words

Write better For-Loops

Looping through an iterable is the most basic and fundamental ability of any programming language. Python’s for loop is at a first glance very straightforward, but just like with any other tool it can be used in multiple ways - these become handy when you start taking performance into account. Here are 6 things to consider when you need to loop over something. 1. Maybe I don’t actually need a for-loop For loops can be slow. There are many built-in methods optimized for specific tasks. Perhaps a better approach would be to simply use a built-in function. Let’s say you need to sum up a list of numbers. ...

January 15, 2023 Â· 4 min Â· 746 words