Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type hint specific format of string? [duplicate]

Is it possible to type a what a string literal should look like? For example, a string must be prefixed like "id=123456" where "123456" is a user supplied id, but the string must be prefix by "id=" for the method to work. Is it possible to show that in a type hint?

like image 419
Jasonca1 Avatar asked Oct 31 '25 11:10

Jasonca1


2 Answers

The way that I typically type-hint a string in a particular format is to create a NewType for it:

from typing import NewType

IdString = NewType('IdString', str)  # string in 'id=123456' format

def validate_idstring(idstring: str) -> IdString:
    assert idstring.startswith("id=") and idstring[3:].isdecimal()
    return IdString(idstring)

At runtime an IdString is just a regular str, but you can use IdString in type annotations and the type checker will error if you pass a str in place of the more specific IdString type.

For this particular case I might be inclined to make the userid a class, e.g.:

class UserId:
    def __init__(self, id: int):
        self._id = id

    def __str__(self) -> str:
        return f"id={self._id}"

or, if you wanted the option of being able to construct it from either the string representation or the raw int:

from typing import Union, overload

class UserId:
    @overload
    def __init__(self, id: str):
        pass

    @overload
    def __init__(self, id: int):
        pass

    def __init__(self, id: Union[int, str]):
        if isinstance(id, int):
            self._id = id
        else:
            assert id.startswith("id=")
            self._id = int(id[3:])

    def __str__(self) -> str:
        return f"id={self._id}"
like image 180
Samwise Avatar answered Nov 02 '25 02:11

Samwise


I think that is beyond the scope of type-hinting. As the name suggest, type-hinting is only to provide developers the means to know what type the argument is.

But if you want to provide additional information as to the format of the string such as prefix. You can consider looking at Docstring, these is where you document more information about the function as well as its arguments.

*Also note to check the inputs and raise if it doesn't fulfil the desired format.

like image 27
A. Teng Huat Avatar answered Nov 02 '25 00:11

A. Teng Huat