My latest TILs about Python
After so long, I still find basic stuff in Python that I didn't know about. Here are some of my most recent TILs.
- You can use underscores to separate digits in a number and they'll be ignored by the interpreter:
>>> 1000000 # confusing
1000000
>>> 1e6 # not confusing but creates a float
1000000.0
>>> 1_000_000 # great!
1000000
- The
sum
method accepts a second parameter that is the initial value of the sum:
>>> base = 20
>>> sum([1, 2, 3], base)
26
- With f-strings you can use the
=
modifier for including the code of the variable interpolation:
>>> a = 1.6
>>> print(f'We have {a=} and {int(a)=}.')
We have a=1.6 and int(a)=1.
- You can use classes to define decorators instead of functions:
>>> class show_time:
... def __init__(self, func):
... self.func = func
... def __call__(self, *args, **kwargs):
... start = time()
... result = self.func(*args, **kwargs)
... print(f'It took {time() - start:.4f}s')
... return result
...
>>> @show_time
... def test():
... return sum(n**2 for n in range(1000000))
...
>>> test()
It took 0.1054s
333332833333500000
- The
mode
attribute foropen
is'r'
by default:
>>> with open('test.txt') as f:
... print(f.read())
It works!
Replying to Baudneo:
The font for the body text is "Spline Sans Mono" (https://fonts.google.com/specimen/Spline+Sans+Mono).The font for the headings is Adesso (https://www.myfonts.com/collections/adesso-font-presence-typo).
One small bug I note:
When i scroll down the page, the table of contents on the left side of the page disappears, and reappears when I scroll up!
Replying to Siôn:
Hi Sion, thanks for the appreciation :) I started making it into a blog template long ago but it has way too much janky customizations on the editor side. The left side disappearing is a way to make reading more immersive