Skip to content

Latest commit

 

History

History
32 lines (21 loc) · 839 Bytes

20220905101227.md

File metadata and controls

32 lines (21 loc) · 839 Bytes

Enforce keyword arguments

Sometimes it can be more readable to have keyword-only arguments. 😍🐍

Did you know you can force them in Python by adding a * in the function signature like so: 💡

from sqlmodel import Field, SQLModel


class Hero(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: int | None = None


def create_hero(*, name: str, secret_name: str, age: int | None = None) -> Hero:
    hero = Hero(name=name, secret_name=secret_name, age=age)
    return hero


# hero = create_hero("Spider-Boy", "Pedro Parqueador")
# gives:
# TypeError: create_hero() takes 0 positional arguments but 2 were given
#
# with * all args that follow it are keyword only:
hero = create_hero(name="Spider-Boy", secret_name="Pedro Parqueador")

#functions