-
Hello! I'm looking for some advice on how to properly type functions via Getting on to def pad(text, width=None, align="c", fillchar=" "):
"""
Pads to a given width.
Args:
text (str): Text to pad.
width (int, optional): The width to pad to, in characters.
align (str, optional): This is one of 'c', 'l' or 'r' (center,
left or right).
fillchar (str, optional): The character to fill with.
Returns:
text (str): The padded text.
"""
width = width if width else settings.CLIENT_DEFAULT_WIDTH
align = align if align in ("c", "l", "r") else "c"
fillchar = fillchar[0] if fillchar else " "
if align == "l":
return text.ljust(width, fillchar)
elif align == "r":
return text.rjust(width, fillchar)
else:
return text.center(width, fillchar) And here is my current (probably naïve) typing for it. Explanations about my solution are baked into the queries below. def pad(
text: str, width: int | None = ..., align: Literal["c", "l", "r"] = ..., fillchar: str = ...
) -> str: ... Here are my queries about typing it: Should
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I have no experience with Evennia, so please take that in mind in my response. While passing something other than "c", "l", or "r" into I would expect the author of The example in the docs is not supposed to showcase a catch-all overload. Instead, it's just meant to show that while in the implementation you have one non-overload version of the signature (the one which contains the actual implementation), in the stubs you don't include it. Generally speaking, I would only include a catch-all overload if there are valid cases that can't be expressed with more specific overloads. Ideally, the stubs would only represent valid calls to the function. In practice, that is not always possible or practical, though. |
Beta Was this translation helpful? Give feedback.
-
It's not your primary question (@srittau already gave a great answer), but I want to react to this part of your post:
3.11 added a host of useful new features to |
Beta Was this translation helpful? Give feedback.
I have no experience with Evennia, so please take that in mind in my response.
While passing something other than "c", "l", or "r" into
align
is possible, this would most likely be unintended, i.e. a bug, and is exactly what type checking is supposed to catch. Personally I would use theLiteral
. One exception would be if passing anything else (for example an empty string) is a common idiom in existing code.I would expect the author of
foo()
to use the same literal type for align as you are using inpad()
. You could provide a type alias like_Alignment: TypeVar = Literal["c", "l", "r"]
and use that. This alias could then be used by the author offoo()
(although it requires a bit of an awk…