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

The Pragmatic Programmer: From Journeyman to Master

Pragmatic programmer Inquisitive - asks questions Critical thinker - checks the facts Realistic - tries to understand the underlying nature Jack of all trades - is familiar with a broad range of technologies A broken window 1 broken window left unrepaired instills a sense of abandonment leading to more broken windows etc. Don’t leave broken windows (bad design, wrong decisions, poor code..) unrepaired. Fix each one as soon as discovered. ...

December 17, 2022 · 10 min · 1940 words · Andy Hunt, Dave Thomas