kdmontero
kdmontero

Reputation: 5

In Python, how to make a custom type to describe a more specific type hints?

I am running a script using openpyxl and i have some function copy_value that shows like this:

from openpyxl.workbook.workbook import Workbook

def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    do something...

Now my concern is that the type hint for argument cell is a just a generic str. I want to have a custom and more specific typing, say Cell (which is also a str), so that the user will know that this argument will take not just any other string like 'abc' or '123worksheet', but must be a valid cell like 'D12' or 'AA345'.

Or how else to properly do this?

Upvotes: 0

Views: 1354

Answers (1)

Danial
Danial

Reputation: 432

If you want to have this validation with type hinting, You could do something like

class Cell(str):
    def __new__(cls, cell_identifier: str):
        if not cell_identifier.startswith('abc'):  # Add your string validation logic here
            raise ValueError('Cell identifier is not valid!')

        return str.__new__(cls, cell_identifier)

then your function would be like

def copy_value(source: Workbook, target: Workbook, cell: Cell) -> None:
    do something...

Note that type hinting is aimed to check the type of variables, not their runtime value. Type hinting does not ensure the parameters passed to your function are from the hinted type and therefore does not guarantee that they follow your desired string pattern. Inheriting from primitive types is not very common, and generally not needed.

If the validation is important, it's up to you to validate the data. Either when calling the function and passing the parameters, or even better in your function such as

def copy_value(source: Workbook, target: Workbook, cell: str) -> None:
    if cell.startswith('abc'):  # Your validation logic here
            raise ValueError('Cell identifier is not valid!')
    do something...

Upvotes: 2

Related Questions