Python Tip #288 (of 365):
Show a value's repr with "!r" in f-strings. π§΅
>>> name = "Trey"
>>> print(f"Name: {name}")
Name: Trey
>>> print(f"Name: {name!r}")
Name: 'Trey'

Python Tip #288 (of 365):
Show a value's repr with "!r" in f-strings. π§΅
>>> name = "Trey"
>>> print(f"Name: {name}")
Name: Trey
>>> print(f"Name: {name!r}")
Name: 'Trey'
Python Tip #287 (of 365):
Read tracebacks from the bottom up. π§΅
When Python encounters an exception that isn't handled in your code, it prints out a traceback.
Python Tip #286 (of 365):
Know your way around the Python docs. π§΅
The docs at docs.python.org/3/ have many different types of pages.
It's helpful to note which kind of page you're on and consider whether you're in the right place.
Python Tip #285 (of 365):
Learn to use the help function. π§΅
>>> help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
...
Python Tip #284 (of 365):
Import from another directory by adding it to sys.path. π§΅
sys.path.insert(0, str(Path(__file__).parent / "vendored_utils"))
This is a bit of a hack. It works great in your own project, but I wouldn't want to see it in an installable package.
Python Tip #282 (of 365):
Read your package's data files with importlib.resources. π§΅
>>> from importlib import resources
>>> resources.files("dinner").joinpath("recipes.json").read_text()
'{"tacos": ["tortillas", "beans", "salsa"]}\n'
Python Tip #281 (of 365):
Bundle your package into one runnable file with zipapp. π§΅
$ python3 -m zipapp src -m "greet.cli:main" -p "/usr/bin/env python3" -o greet.pyz
$ python3 greet.pyz
Hello from greet!
$ ./greet.pyz
Hello from greet!
Python Tip #280 (of 365):
Make your package runnable with a __main__β.py file. π§΅
greet
βββ cliβ.py
βββ __init__β.py
βββ __main__β.py
Python Tip #279 (of 365):
Simplify your package's interface with __init__β.py. π§΅
Yesterday's tip noted that an empty __init__β.py file is common and completely fine.
But that file doesn't HAVE to be empty.
Python Tip #278 (of 365):
Always include a __init__β.py file in your Python packages. Even an empty one. π§΅
food_utils
βββ fruitsβ.py
βββ __init__β.py
βββ non_fruitsβ.py
A package is a directory that Python treats like a module.
Python Tip #277 (of 365):
For substring checks, use the "in" operator. π§΅
Python has a special operator that's meant JUST for checking whether one thing is contained inside another:
>>> part = "Python"
>>> whole = "I enjoy writing Python code."
>>> part in whole
True
Python Tip #276 (of 365):
Make self positional-only when accepting "**kwargs". π§΅
This class accepts any keyword argument... except self:
class Namespace:
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
Python Tip #275 (of 365):
Pre-fill arguments with functools.partial. π§΅
>>> from functools import partial
>>> hex_to_int = partial(int, base=16)
>>> hex_to_int("CAFE")
51966
This is sometimes called "partially evaluating" a function.
Python Tip #274 (of 365):
Prefer to name your functions. π§΅
Instead of this:
sorted(items, key=lambda item: int(item.split()[0]))
Python Tip #272 (of 365):
Do something or return something, but not both. π§΅
The list sort method returns None:
>>> numbers = [4, 2, 7, 1, 5]
>>> x = numbers.sort()
>>> print(x)
None
>>> numbers
[1, 2, 4, 5, 7]
Python Tip #273 (of 365):
Avoid needless wrapper functions. π§΅
This lambda does nothing but call len:
sorted(words, key=lambda s: len(s))
So pass len itself:
sorted(words, key=len)
Python Tip #271 (of 365):
Return, don't print. π§΅
If your function only seems to "work" in the REPL, it may be printing when it should be RETURNING.
Python Tip #270 (of 365):
Move and copy files with pathlib. π§΅
In Python 3.14, Path objects gained move and copy methods, and copy works on whole directories:
>>> from pathlib import Path
>>> taxes = Path("taxes")
>>> taxes.copy("taxes-backup")
PosixPath('taxes-backup')
Python Tip #269 (of 365):
Walk directory trees with Path.walk. π§΅
The walk method (Python 3.12+) is the pathlib version of os.walk. For each directory in the tree, you get the directory's path, a list of its subdirectory names, and a list of its file names.