Change file extensions with with_suffix. 🧵
A ".rst" file path that needs to turn into a ".md" file path:
>>> from pathlib import Path
>>> old_path = Path("uvrs/readme.rst")
>>> old_path.with_suffix(".md")
PosixPath('uvrs/readme.md')
#Python #DailyPythonTip
Change file extensions with with_suffix. 🧵
A ".rst" file path that needs to turn into a ".md" file path:
>>> from pathlib import Path
>>> old_path = Path("uvrs/readme.rst")
>>> old_path.with_suffix(".md")
PosixPath('uvrs/readme.md')
#Python #DailyPythonTip
Don't use the file readlines method. 🧵
Do this:
lines = list(file)
Not this:
lines = file.readlines()
Both give the same list of lines. So why prefer list?
#Python #DailyPythonTip
Don't use the file readlines method. 🧵
Do this:
lines = list(file)
Not this:
lines = file.readlines()
Both give the same list of lines. So why prefer list?
#Python #DailyPythonTip
Reread a file with seek(0). 🧵
Try to .read() a file twice, and you'll get nothing the second time:
>>> f = open("my_file.txt")
>>> f.read()
'This is my file 👋\nThis is line 2\n'
>>> f.read()
''
#Python #DailyPythonTip
Reread a file with seek(0). 🧵
Try to .read() a file twice, and you'll get nothing the second time:
>>> f = open("my_file.txt")
>>> f.read()
'This is my file 👋\nThis is line 2\n'
>>> f.read()
''
#Python #DailyPythonTip
Don't remove string prefixes and suffixes manually. 🧵
Instead of this:
normalized = hex_value.lower()
if normalized.startswith("0x"):
normalized = normalized[2:]
Do this:
normalized = hex_value.lower().removeprefix("0x")
#Python #DailyPythonTip
Don't remove string prefixes and suffixes manually. 🧵
Instead of this:
normalized = hex_value.lower()
if normalized.startswith("0x"):
normalized = normalized[2:]
Do this:
normalized = hex_value.lower().removeprefix("0x")
#Python #DailyPythonTip
Use pathlib.Path(directory, filename) to join path strings
To join path strings together, instead of:
joined = Path(directory) / filename
Or:
joined = Path(directory).joinpath(filename)
You can do this:
joined = Path(directory, filename)
#Python #DailyPythonTip
Use pathlib.Path(directory, filename) to join path strings
To join path strings together, instead of:
joined = Path(directory) / filename
Or:
joined = Path(directory).joinpath(filename)
You can do this:
joined = Path(directory, filename)
#Python #DailyPythonTip
To flatten an iterable-of-iterables, use chain.from_iterable. 🧵
#Python #DailyPythonTip
To flatten an iterable-of-iterables, use chain.from_iterable. 🧵
#Python #DailyPythonTip
Use underscores to make large numbers more readable.
Compare this:
n = 1000000
To this:
n = 1_000_000
The underscores make it more readable, right?
#Python #DailyPythonTip
Use underscores to make large numbers more readable.
Compare this:
n = 1000000
To this:
n = 1_000_000
The underscores make it more readable, right?
#Python #DailyPythonTip
Don't sleep on Python's keyword arguments / named arguments. 🧵
When you have the choice between a positional argument or a keyword argument, choose a keyword argument if it clarifies the argument's purpose.
#Python #DailyPythonTip
Don't sleep on Python's keyword arguments / named arguments. 🧵
When you have the choice between a positional argument or a keyword argument, choose a keyword argument if it clarifies the argument's purpose.
#Python #DailyPythonTip
Don't overuse classes. 🧵
Writing Python code does NOT require writing classes.
#Python #DailyPythonTip
Don't overuse classes. 🧵
Writing Python code does NOT require writing classes.
#Python #DailyPythonTip
Instead of manually caching computed attribute values, use functools.cached_property. 🧵
#Python #DailyPythonTip
Instead of manually caching computed attribute values, use functools.cached_property. 🧵
#Python #DailyPythonTip
Merge iterables using asterisks, like this: "[*first, *second]" 🧵
To merge two iterables, first and second, into third don't do this:
third = list(first) + list(second)
Do this:
third = [*first, *second]
Why?...
#Python #DailyPythonTip
Merge iterables using asterisks, like this: "[*first, *second]" 🧵
To merge two iterables, first and second, into third don't do this:
third = list(first) + list(second)
Do this:
third = [*first, *second]
Why?...
#Python #DailyPythonTip
When it comes to modifications, think of lists as stack-like. 🧵
This week's tips are all about lists and data structures.
#Python #DailyPythonTip
When it comes to modifications, think of lists as stack-like. 🧵
This week's tips are all about lists and data structures.
#Python #DailyPythonTip
Avoid modifying a list while you're looping over it. 🧵
#Python #DailyPythonTip
Avoid modifying a list while you're looping over it. 🧵
#Python #DailyPythonTip
Don't use the __class__ attribute. 🧵
To get the name of any object's class, you can use:
type(my_obj).__name__
You might occasionally see this instead:
my_obj.__class__.__name__
I don't recommend that approach.
#Python #DailyPythonTip
Don't use the __class__ attribute. 🧵
To get the name of any object's class, you can use:
type(my_obj).__name__
You might occasionally see this instead:
my_obj.__class__.__name__
I don't recommend that approach.
#Python #DailyPythonTip
Parse dates with date.strptime. 🧵
In Python 3.14+, the date class got its own strptime class method:
>>> import datetime as dt
>>> dt.date.strptime("2026-08-19", "%Y-%m-%d")
datetime.date(2026, 8, 19)
#Python #DailyPythonTip
Parse dates with date.strptime. 🧵
In Python 3.14+, the date class got its own strptime class method:
>>> import datetime as dt
>>> dt.date.strptime("2026-08-19", "%Y-%m-%d")
datetime.date(2026, 8, 19)
#Python #DailyPythonTip
When processing potentially large untrusted files, don't iterate over them. 🧵
#Python #DailyPythonTip
When processing potentially large untrusted files, don't iterate over them. 🧵
#Python #DailyPythonTip
To suppress specific exceptions, use contextlib.suppress 🧵
You could suppress an exception like this:
try:
...
except ValueError:
pass
But I would recommend this:
from contextlib import suppress
with suppress(ValueError):
...
#Python #DailyPythonTip
To suppress specific exceptions, use contextlib.suppress 🧵
You could suppress an exception like this:
try:
...
except ValueError:
pass
But I would recommend this:
from contextlib import suppress
with suppress(ValueError):
...
#Python #DailyPythonTip
Sort by unbound method objects instead of using "lambda" 🧵
Say you're sorting mixed capitalization strings:
>>> frameworks = ["jQuery", "React", "Alpine", "htmx", "Svelte"]
>>> sorted(frameworks)
['Alpine', 'React', 'Svelte', 'htmx', 'jQuery']
#Python #DailyPythonTip
Sort by unbound method objects instead of using "lambda" 🧵
Say you're sorting mixed capitalization strings:
>>> frameworks = ["jQuery", "React", "Alpine", "htmx", "Svelte"]
>>> sorted(frameworks)
['Alpine', 'React', 'Svelte', 'htmx', 'jQuery']
#Python #DailyPythonTip
Chain method calls for readability's sake 🧵
When an object's methods return the same type of object, prefer to chain calls together instead of juggling extra variables.
#Python #DailyPythonTip
Chain method calls for readability's sake 🧵
When an object's methods return the same type of object, prefer to chain calls together instead of juggling extra variables.
#Python #DailyPythonTip
Be careful with mutable default values in function definitions. 🧵
This class is buggy:
class TodoList:
def __init__(self, tasks=[]):
self.tasks = tasks
def add_task(self, task):
self.tasks.append(task)
#Python #DailyPythonTip
Be careful with mutable default values in function definitions. 🧵
This class is buggy:
class TodoList:
def __init__(self, tasks=[]):
self.tasks = tasks
def add_task(self, task):
self.tasks.append(task)
#Python #DailyPythonTip
Use "[]" to create empty lists instead of calling "list()". 🧵
(This week's tips will all be related to lists)
#Python #DailyPythonTip
Use "[]" to create empty lists instead of calling "list()". 🧵
(This week's tips will all be related to lists)
#Python #DailyPythonTip
Don't write ordering methods by hand. 🧵
Want your objects to support <, >, <=, and >=?
You don't need to write them all!
#Python #DailyPythonTip
Don't write ordering methods by hand. 🧵
Want your objects to support <, >, <=, and >=?
You don't need to write them all!
#Python #DailyPythonTip
Don't use re.match(): it's confusing 🧵
I'm not sure I've ever seen re.match() used when it wasn't being used by mistake.
If you think you want re.match(), you probably want either re.search() or re.fullmatch() instead.
#Python #DailyPythonTip
Don't use re.match(): it's confusing 🧵
I'm not sure I've ever seen re.match() used when it wasn't being used by mistake.
If you think you want re.match(), you probably want either re.search() or re.fullmatch() instead.
#Python #DailyPythonTip