Skip to content

Instantly share code, notes, and snippets.

@dannysepler
Created February 24, 2023 21:00
Show Gist options
  • Save dannysepler/a0456709283a1a4115a019571ad38c08 to your computer and use it in GitHub Desktop.
Save dannysepler/a0456709283a1a4115a019571ad38c08 to your computer and use it in GitHub Desktop.
New python syntax

What's new in Python?

Fancy debugging print statements (py3.8)

You can now print out a variable even easier!

# Before
my_var = "hi"
print(f"my_var={my_var}")

# After
my_var = "hi"
print(f"{my_var=}")

Dictionary union operator (py3.9)

You can now combine two dictionaries with the | operator

# Before
dct = dict(a=1)
dct = {**dct, {"b": 2}}

# After
dct = dict(a=1)
dct = dct | {"b": 2}

# After, even better
dct = dict(a=1)
dct |= {"b": 2}

Dictionaries are ordered

Relevant article.

  • In python 3.6, dictionaries were ordered by accident.
  • From python 3.7 onwards, dictionaries are ordered by design and will stay that way.
  • In python 3.8, the csv.DictReader now returns a dict type and not an OrderedDict type

Built-in type annotations (py3.9)

Before python 3.9, to type many builtin objects you had to import those classes from the typing module. Now, you can type the generic data type.

# Before
from typing import List, Dict
def my_func(*, a: List, b: Dict) -> bool:
  return True
my_func(a=[], b={})

# After
def my_func(*, a: list, b: dict) -> bool:
  return True
my_func(a=[], b={})

Typing union operator (py3.10)

When doing type annotations, there is a new union operator.

# Before
from typing import Union, Optional
def a() -> Union[str, int]:
  return 'abc' if True else 1
def b() -> Optional[str]:
  return 'abc' if True else None

# After
def a() -> str | int:
  return 'abc' if True else 1
def b() -> str | None:
  return 'abc' if True else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment