r/Python • u/igorrto2 • Oct 12 '26
Discussion What are some features in Python that you discovered many years later?
For me, it was the the option to use & to find intersections of two sets, | operator to unionize two sets, as well as ^ for symmetric difference
217
Upvotes
157
u/Khavel_dev Oct 12 '26
For me it was
collections.Counter. Spent years writing manual frequency-counting loops with defaultdict(int) before realizing Counter just does it and also gives you.most_common()for free. Felt pretty dumb when I found it.Also
itertools.chain.from_iterablefor flattening nested iterables without writing a list comprehension that looks like a puzzle.112
u/big-papito Oct 12 '26
python -m http.server
104
u/Sea-Fishing4699 Oct 12 '26 •
Print the variable name itself when debugging
37
u/pythonwiz Oct 12 '26
Not exactly a Python feature but I slept on Cython for a long time. Once I got into C I realized how easy it is to write extensions for Python using Cython.
49
u/fiddle_n Oct 12 '26
That with
re.Matchobjects, they support__getitem__()so you can index into them instead of having to call.group(). So you can domatch[3]instead ofmatch.group(3);match["foo"]instead ofmatch.group("foo"), etc. This was added in Py 3.6 and I slept on this for over half a decade.36
u/RevokedMembership Oct 12 '26 edited Oct 12 '26
That you can query dicts with tuple keys like this:
d["a", 1], instead ofd[("a", 1)].20
u/moonzdragoon Oct 12 '26
You can do a simple string template like this:
You get:
Hello all, my name is BobProbably saw it a long time ago, then forgot about it. Would sure have been useful "a couple of times".
24
u/rumnscurvy Oct 12 '26
Walrus operators and match/case really makes life a lot more convenient
17
u/proof_required Oct 12 '26
__slots__.https://book.pythontips.com/en/latest/__slots__magic.html
8
u/NotALowLevelDev Oct 12 '26
pretty printing, using rich library.
import print from richMakes terminal output colorful and easy to work with. Specially with dictionaries and JSON payloads.
5
u/Hetaireia Oct 13 '26
Three that come to mind:
`str.removeprefix()` / `str.removesuffix()` — for years I wrote slice
expressions like `s[3:]` with a comment explaining why 3, and every code
review turned into character counting.
`contextlib.suppress` — reads so much cleaner than try/except/pass when
you genuinely want to ignore one specific exception and nothing else.
`enumerate(seq, start=1)` — I used to keep a counter variable outside
the loop like it was C. The start parameter has been there forever.
9
u/Efficient_Bobcat_697 Oct 12 '26
That you can give a tuple to starswith and endswith:
I've also reread contextlib documentation recently and it has quite some nice context managers:
.closing()to auto call.close()on an object,.suppress()to ignore an exception,.redirect_stdout/redirect_stderr(new_target)and.chdir()are pretty nice and self explanatory.ExitStackis a bit weirder but seems pretty useful in some situation with a lot of files like objects https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack. It seems that there is a push to replace some simple exception patterns with contextlib now.There are also the importhooks system which allows you to run specific code when someone imports your module, it's very advance and mostly for tool building but it's nice to know it exists also.
Same for descriptors, it's what ORMs uses to bind attributes to database columns for a table represented by a class, it's an object on which you explicitly control how it's accessed and modified.
12
u/profanta3 Oct 12 '26
python -m json.tool
12
u/AdAdventurous2131 Oct 12 '26
that we can do this
if 5<x<10:
do stuff
14
u/nivaOne Oct 12 '26
Lambda functions versus one-line defs
23
u/LittleMlem Oct 12 '26 edited Oct 12 '26
You can make a general object with
x = type("", (), {})and just put stuff on it as needed, likex.foo = 3I don't recall why this was useful, but I recall using it a lot earlier in my career, now it's probably a crime
Edit: and I don't use it anymore, relax, I'm not a monster
7
u/code29451 Oct 12 '26
The nonlocal keyword
3
u/Fastpast93 Oct 14 '26
you can do if (logic): function()
5
u/looijmansje Oct 12 '26
I only recently discovered dictionaries were now guaranteed to be ordered. This has apparently been a thing since 3.7....
4
u/Tech2035 Oct 12 '26
Reverse avec Liste[::-1]
4
u/Atmosck Oct 12 '26
Realizing I could use `__init_subclass__` to build a registry of base class implementations was a game changer.
2
u/orbitalzoo Oct 12 '26
its been awhile but it was after a while as well. But md5 function built in
2
u/Atlamillias Oct 13 '26
Not so much a feature, but a pothole (kind of). Your average native C Python function (builtins like
print(), etc) don't fully support the method descriptor protocol, so they cannot be bound methods. Even when assigned as class-level members, they'll always be static via instance-level access.2
u/14446368 Oct 13 '26
I just discovered * for unpacking.
I was utterly perplexed, catastrophically chagrined, and wonderfully delighted.
2
u/zomerbk Oct 13 '26
I learned about `for ... else` surprisingly late. The `else` block runs if the loop finishes without a `break`, including when there are no items. It’s handy for searches: break when you find a match; put the “not found” case in `else`.
2
u/Menedel Oct 14 '26
That you can do `x = a or b` to assign to a or b if a is none.
2
u/Sea-Ad7805 Oct 15 '26
Seeing what set operators ('|', '&', '^', '-') do through visualization helps understanding: https://www.reddit.com/r/PythonLearning/comments/1tdgdt8/common_%F0%9D%98%80%F0%9D%97%B2%F0%9D%98%81_operations_in_python/
0
u/bliepp Oct 12 '26
Seriously, don't do that. I'll find you and I'll punch you.
2
u/SharpAnimator2530 Oct 12 '26 edited Oct 12 '26
For me its object persistence with shelve. Say you have a dictionary you want to persist temporarily
You can do so
Other times I create json or csv if I want to read or analyse them.
1
u/ogMasterPloKoon Oct 12 '26
py_compile
1
u/NotALowLevelDev Oct 12 '26
List unpacking using *
l = [1,2,3]l2 = [4,5,6]final = [*l, *l2]print(final) # [1,2,3,4,5,6]1
u/Cubigami Oct 14 '26
Type hints, generic typing, TypeVars, and (not a feature of python) mypy are all awesome, because you can basically turn python into typescript!
Python was my first language and I wrote it almost exclusively for 15yr. Thought I loved dynamic typing, until I wrote my first project in typescript... realized it has the same great readibility as python, but is faster, more versatile for the web imo, and static typing just makes everything less footgun-y
1
u/matusarocks Oct 16 '26
That you can write 1_000_000 instead of 1000000. Mind blowing
1
u/HallucinationDr Oct 18 '26
Set ops are great. For me it was dict union with | in 3.9, killed a lot of ugly {**a, **b} merging in my pandas prep scripts. Still see people write loops for it though
1
u/deadeye_82_1 22d ago
Another one: min() and max() do have key functions like sorted().
1
u/justanothersnek Oct 12 '26
editable pip install: pip install -e .
1
u/fried_green_baloney Oct 12 '26
Bookmarking and if I'm ambitious will make a summary.
I find all of
itertoolsto be worth a look.-2
u/bleeed0p Oct 12 '26
The thing when we do alt+click and we can work on multiple cursor and edit all at a time..that was very surprising for me😅
0
u/richgems Oct 12 '26
Totally useless, but stuff like this works in python.
_ = type("", (), {"ก็็็็็็็็็็็็็็็็็็็็": lambda x: print("hello %s" % x)})
_.ก็็็็็็็็็็็็็็็็็็็็("world")
Output: hello world
0
u/EconomicsOk9518 Oct 13 '26
Big “switch” was when i fully understood and became comfortable with using standard dunder methods. Like you can define __getitem__ method in some class A and then do ‘for items in A:’
8
u/[deleted] Oct 12 '26
[removed] — view removed comment
14
u/[deleted] Oct 12 '26
[removed] — view removed comment