Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint for a "char" / "character" type

There is no built-in, primitive type for "char" or "character" so obviously a string of length 1 will have to be used. But to connote this and to connote it should be treated as if it was a character how can this be achieved through a type hint?

grade: chr = 'A'

One approach may be to use the built-in 'chr' function to connote this.

grade: "char" = 'A'
grade: "character" = 'A'

Another approach may be to use a string type hint to connote this.

To my understanding there is no object connoting a char type in the 'typing' module.

Other posts I have searched for either state why certain type-hints (like using the 'chr' built in function to connote a character) are simply wrong: Is there a PEP484 type hint for 'character'?

However, none have given an answer as to what should be used to connote a char. Using a 'str' typehint and documenting it should be treated as if it were a character is not an answer I am looking for.

grade: str = 'A'  # Treat as if it were a character

I would like to know what should I use to connote a "char" / "character" type in python?

Edit for clarity: I am asking for a type-hint not additional computation or anything more... If I was asking for a string length check or some sort of variation of that I would not have asked this question.

like image 706
Magmurrr Avatar asked Dec 17 '25 23:12

Magmurrr


1 Answers

Your first approach is simply wrong. chr is a built-in function, it's not a type ! So you can't use it in type hints.

In my opinion it is enough to say it's a str.Type hint is for third-parties, type-checkers... When Python doesn't differentiate between char and string, why do you want to do that? You can then implement a logic to raise error in your function or methods or whatever if that string has more than one item.

If you insist, you can have your custom type although I don't think it is super useful:

class Onechar(str):
    def __new__(cls, s):
        if len(s) > 1:
            raise ValueError("Only one character")
        return super(Onechar, cls).__new__(cls, s)

obj: Onechar
obj = "hiii"       # mypy complains
obj = Onechar("h") # fine
like image 183
SorousH Bakhtiary Avatar answered Dec 20 '25 15:12

SorousH Bakhtiary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!