Rui Martins
Rui Martins

Reputation: 3848

Python define variable with type of other variable

Can I define the type of a variable from other variable type?

Example: I created USER:

class User(BaseModel):
    id: str  # Not sure if will be str, int or UUID
    tags: Optional[List[str]]
    name: str

Now, in other place, I have a function that uses User.id as parameter:

def print_user_id(user_id: str):  # If I change type of User.id, I need to update this!
    pass

How can I say that the type of user_id is type(User.id)?

Like:

def print_user_id(user_id: type(User.id)):  # But, If I change type of User.id, I DON`T NEED to update this :)
    pass

Upvotes: 2

Views: 171

Answers (1)

balderman
balderman

Reputation: 23815

Maybe you can define a new type and use it across the code. See below

With this you can change the actual type of UserId with no impact on the rest of the code.

from typing import NewType, Optional, List

UserId = NewType('UserId', int)


class BaseModel:
    pass


class User(BaseModel):
    id: UserId
    tags: Optional[List[str]]
    name: str


def print_user_id(user_id: UserId):
    print(user_id)

Upvotes: 4

Related Questions