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.

  1. 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
  1. The sum method accepts a second parameter that is the initial value of the sum:
>>> base = 20
>>> sum([1, 2, 3], base)
26
  1. 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.
  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
  1. The mode attribute for open is 'r' by default:
>>> with open('test.txt') as f:
...     print(f.read())
It works!

Comentarios

Baudneo Reply
What font is this site shown in?.I really like it.
Muhammad Khan Reply

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).
Jackie Reply
Decorator using class is really clean
Siôn Reply
This is a super nice website, and love this article. Lots of TILs! Is your site open-source? Would love to experiment with the template!

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!
Juan C. Roldán Reply

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

Leave a comment

Get a mail
4d8cd43bbbfbbd2b7aed08d9a2b0ef251cebfd3e2603b74b710a2d38b7f8ec39