A while back I decided to try and learn Python for the hell of it as it seems like an interesting language and has some of the most concise and user-friendly syntax. Having spent some time going through a number of different learning sources and materials (like the official site python.org which has a very helpful tutorial section) I have put together a set of notes I made as I was learning and hopefully they can be useful to you as a quick list of how-to code snippets.
All the code snapshots I’m showing here are taken from the IDLE Python shell.
Input and Output
The repr() function generates representations that can be read by the interpreter, str() function generates a human-readable of the value:
If an object doesn’t have a particular representation for human consumption, str() will return the same value as repr(), e.g. lists and dictionaries:
You can use the string.rjust(), string.ljust() or string.center() function to left-justify, right-justify or center a string of given width by padding it with spaces:
You can use the string.zfill() function to pad a numeric string on the left with zeros:
You can use string.format() method to format the string output of your code:
You can also use named arguments:
An optional ‘:‘ and format specifier can follow the field name to allow greater control over how the value is formatted:
Passing an integer after the ‘:‘ will cause that field to be a minimum number of characters wide:
For a very long string, you could even reference variables to be formatted by name using a dictionary:
Or you could unpack the dictionary first:
You can use the open() function to get a file object, to open a file for writing:
The first parameter being the file name, the second the mode which can be one of the following:
To open a file and read its contents:
To read one line at a time
To read the lines in the file as an array of strings:
You can also read x number of bytes at a time:
But remember, you always read starting from the position where your last read finished:
To write to a file:
You can only write string contents to a file, which means you’d need to convert other objects to string first:
To flush the file buffer and actually write them to the file, use the close() function, after which you’ll need to open the file again:
You can use the tell() function to find out your current position in the file:
You can use the seek() function to change the file object’s current position, seek(offset, from_what):
from_what can be one of three values:
- 0 – beginning of file (default)
- 1 – current position
- 2 – end of the file
It’s good practice to use the with keyword when dealing with file objects, which ensures that the file is closed after its suite finishes. (this works like the using keyword in C#).
To deal with complex types (or indeed any non-string types like int) you can use the pickle module to convert it to and from string.
The process of converting a complex type to string is called pickling.
The process of constructing a complex type from string is called unpickling.
You can handle more than one exception if you name them in a tuple:
You can handle a list of exceptions in a certain priority list and if you don’t specify a particular exception type it’ll serve as a wildcard:
You can also specify a else clause which follows all except clauses, it’s useful for code that must be executed if the try clause does not raise an exception:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try-except statement.
There’s also the optional finally clause which is intended to define clean-up actions that must be executed under all circumstances:
You can get more information about the instance of the exceptions:
To throw an exception:
To re-throw an exception:
To define a custom exception:
The __str__() function ensures that you can print the exception instance directly:
When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:
Some objects define standard clean-up actions, for instance, the with statement always closes the file after the statement is executed:
(the same as the using statement in C#)
I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.
Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.
Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- Lambda optimization tip – enable HTTP keep-alive
- You are thinking about serverless costs all wrong
- Many faced threats to Serverless security
- We can do better than percentile latencies
- I’m afraid you’re thinking about AWS Lambda cold starts all wrong
- Yubl’s road to Serverless
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- AWS Lambda – compare coldstart time with different languages, memory and code sizes
- Guys, we’re doing pagination wrong