2

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
4
  • 1
    This might be useful: stackoverflow.com/questions/152580/… Commented Aug 25, 2020 at 12:42
  • @George I don't think that this is useful Commented Aug 25, 2020 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. Commented Aug 25, 2020 at 12:50
  • 1
    @tobias_k "not sure what this will be in the final design" :) Commented Aug 25, 2020 at 12:55

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.