Around ten years ago, I published an article titled 30 Python Language Features And Tricks You May Not Know About. At the time Python 3.3 was the latest version. Since then, Python has grown quite a bit, with many new exciting features added. This article builds on the previous one, adding another 14 features and tricks new to Python since version 3.3.
Each feature is shown with examples only and no explanations, with links to further details for most items. Some of the features, like type hints and structural pattern matching, are merely introduced here through basic examples. Make sure you look at the PEPs and documentation for them to learn more.
Did I miss anything new to Python 3.4+ that you think should be in this article? Comment below and let me and future readers know!
- 1 Assignment Expressions := (Walrus Operator)
- 2 String removeprefix and removesuffix
- 3 Data Classes
- 4 Enums
- 5 Binary Flags
- 6 Formatting Strings With f-strings
- 7 Debug Output Using f-strings With =
- 8 Merging Dictionaries Using |
- 9 Structural Pattern Matching
- 10 Path Objects And pathlib
- 11 Underscores in Numeric Literals
- 12 Type Hints
- 13 Union Types
- 14 Enumerate With Start Index
1 Assignment Expressions := (Walrus Operator)
>>> print(a = 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'a' is an invalid keyword argument for print()
>>> print(a := 5)
5
>>> print(a)
5
Added in Python 3.8. More details in PEP 572.
2 String removeprefix and removesuffix
>>> "foobar".removeprefix("foo")
'bar'
>>> "foobar".removeprefix("boo")
'foobar'
>>> "foobar".removesuffix("bar")
'foo'
>>> "foobar".removesuffix("tar")
'foobar'
Added in Python 3.9. More details in PEP 616.
3 Data Classes
>>> from dataclasses import dataclass, asdict
>>> @dataclass
... class Person:
... name: str
... age: int
...
>>> alice = Person("Alice", 39)
>>> bob = Person("Bob", 27)
>>> print(alice)
Person(name='Alice', age=39)
>>> asdict(bob)
{'name': 'Bob', 'age': 27}
Added in Python 3.7. More details in PEP-557.
4 Enums
>>> from enum import Enum
>>> class Season(Enum):
... SPRING = 0
... SUMMER = 1
... FALL = 2
... WINTER = 3
...
>>> Season.SPRING
<Season.SPRING: 0>
>>> Season.WINTER.name
'WINTER'
>>> Season['FALL']
<Season.FALL: 2>
Added in Python 3.4. More details in PEP 435.
5 Binary Flags
>>> from enum import Flag, auto
>>> class Permission(Flag):
... READ = auto()
... WRITE = auto()
... DELETE = auto()
...
>>> my_permissions = Permission.READ | Permission.WRITE
>>> Permission.DELETE in my_permissions
False
>>> Permission.WRITE in my_permissions
True
Added in Python 3.6. More details in enum.Flag documentation.
6 Formatting Strings With f-strings
>>> f"2 + 2 = {2 + 2} and in binary it's {2 + 2:b}"
"2 + 2 = 4 and in binary it's 100"
>>>
>>> a, b = "foo", "bar"
>>> f"a is {a} and b capitalized is {b.upper()}"
'a is foo and b capitalized is BAR'
Added in Python 3.6. More details in PEP 498
7 Debug Output Using f-strings With =
>>> a, b = "foo", "bar"
>>> f"{a=}, {b=}"
"a='foo', b='bar'"
Added in Python 3.8.
8 Merging Dictionaries Using |
>>> cache_1 = {'a': 5, 'b': 3}
>>> cache_2 = {'b': 4, 'c': 7}
>>> cache_1 | cache_2
{'a': 5, 'b': 4, 'c': 7}
>>> cache_2 | cache_1
{'b': 3, 'c': 7, 'a': 5}
Added in Python 3.8. More details in PEP 584.
9 Structural Pattern Matching
>>> def process_input(input):
... match input.split():
... case ['add', name]:
... print(f'Adding {name}')
... case ['delete', *names]:
... print(f'Deleting {','.join(names)}')
... case ['quit'] | ['exit']:
... print('Quitting')
... case ['list', ('all' | 'last' | 'first') as items]:
... print(f'Listing {items}')
... case _:
... print('Invalid input')
...
>>> process_input('add Bob')
Adding Bob
>>> process_input('delete Alice Bob')
Deleting Alice,Bob
>>> process_input('quit')
Quitting
>>> process_input('exit')
Quitting
>>> process_input('list last')
Listing last
>>> process_input('list blah')
Invalid input
Added in Python 3.10. More details in PEP 636.
10 Path Objects And pathlib
>>> from pathlib import Path
>>> path = Path('/home/user/bob/.gitconfig')
>>> path.exists()
True
>>> print(path.read_text())
[user]
email = bob@gmail.com
name = Bob Smith
Added in Python 3.4. More details in PEP 428.
11 Underscores in Numeric Literals
>>> print(10_000_000)
10000000
Added in Python 3.6. More details in PEP 515
12 Type Hints
>>> def search(container: list[str], item: str) -> str:
... return container.index(item)
...
>>> search(['a', 'b'], 'b')
1
Added in Python 3.5. More details in PEP-484.
13 Union Types
>>> def pretty_print(object: str | int):
... if isinstance(object, int):
... print(f'{object:,}')
... else:
... print(object)
...
>>> pretty_print(10000)
10,000
>>> pretty_print('abc')
abc
Added in Python 3.10. More details in PEP-604 and union type documenation.
14 Enumerate With Start Index
>>> sections = ['Intro', 'Discussion', 'Summary']
>>> for number, section in enumerate(sections, start=1):
... print(f'{number}. {section}')
...
1. Intro
2. Discussion
3. Summary
Added in Python 2.6. (Yes, I know it's not Python 3.4+ but I missed this in the original article, so here it is!)
Comments