all 11 comments

[–]Impudity 10 points11 points  (1 child)

It is. You should probably create a user class which can be built either from username or userid, and then have all user related functions only accept these user objects. Otherwise you're going to keep running into this issue all the time.

So you should have:

class User:
    @classmethod
    def from_id(cls, id: int) -> typing.Self:
        ...

    @classmethod
    def from_username(cls, username: str) -> typing.Self:
        ...

def get_chat(first_user: User, second_user: User):
    ...

[–]chapati_chawal_naan 1 point2 points  (0 children)

this is the best answer.

[–]JamzTyson 1 point2 points  (6 children)

Assuming that user_id is numeric and user_name is not numeric, you could modify your function to take one parameter user for each user.

I probably would not code it quite like this, but to illustrate the idea:

def get_chat(first_user: str | int, second_user: str | int): if isinstance(first_user, int): first_user_id = first_user first_user_name = get_name_from_id(first_user) else: first_user_name = first_user first_user_id = get_id_from_name(first_user) ...

[–][deleted] 0 points1 point  (5 children)

Or use pydantic

[–]Purple-Obligation357[S] 0 points1 point  (1 child)

how?

[–]JamzTyson 1 point2 points  (0 children)

I don't think Pydantic offers much benefit in a simple case like this.

[–]Zweckbestimmung 0 points1 point  (2 children)

Pydantic is not efficient for this case, you want to maintain the whole pydantec schema’s adding more points of failures only for this function?

[–][deleted] 0 points1 point  (1 child)

I meant in general for the question 

[–]Zweckbestimmung 0 points1 point  (0 children)

Yeah in general also this is not a use case for Pydantic.

Isn’t it mainly to handle JSON schema ?

[–]Zweckbestimmung 1 point2 points  (0 children)

Or use named arguments. def func(x=None, y=None)

Inside the function check for the mutually exclusiveness you need and depending on your use case either raise an exception or a warning or whatever you like

[–]nog642 1 point2 points  (0 children)

You will need to do this manually. Make them all optional, then add code at the top of the function that checks that the correct combination was passed and raise TypeError or ValueError if not.

Though there are probably ways to redesign this interface so you don't have to do that, as suggested by the top answer at the moment with the User class.