1

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
Rui Martins
  • 3,337
  • 5
  • 35
  • 40
  • 1
    This might be useful: https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python – George Aug 25 '20 at 12:42
  • @George I don't think that this is useful – bb1950328 Aug 25 '20 at 12:49
  • Do you mean "not sure what this will be in the final design" or "not sure what this will be at runtime"? In both cases, I'd just create a dedicated ID class wrapping an int, str, and/or uuid. – tobias_k Aug 25 '20 at 12:50
  • 1
    @tobias_k "not sure what this will be in the final design" :) – Rui Martins Aug 25 '20 at 12:55

1 Answers1

3

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)
balderman
  • 22,927
  • 7
  • 34
  • 52