Function argument type definition in python

There was a time when I wanted to define a type in python, so I wrote a function decorator for the time being If I was told to use cython, I wouldn't have any children, but ...

type_definiton.py


from inspect import getargspec, getcallargs


def type_definition(*types):
    def type_checker(func):
        argspec = getargspec(func)

        arg_length = len(argspec.args)

        kwargs_index = -1 if argspec.keywords else 0
        vargs_index = -1 + kwargs_index if argspec.varargs else 0

        arg_type = zip(argspec.args, types[:arg_length])
        vargs_type = types[vargs_index] if vargs_index else None
        kwargs_type = types[kwargs_index] if kwargs_index else None

        def new_func(*args, **kwargs):
            argdetail = getcallargs(func, *args, **kwargs)

            # check type of args
            for name, _type in arg_type:
                if name in argdetail:
                    if not type(argdetail[name]) == _type:
                        raise ValueError(
                           "Invalid Type: " + name + " is not " + str(_type)
                            )

            if vargs_type:
                for value in argdetail[argspec.varargs]:
                    if not type(value) == vargs_type:
                        raise ValueError(
                           "Invalid Type: " + argspec.varargs \
                             + " is not " + str(vargs_type)
                           )

            if kwargs_type:
                for value in argdetail[argspec.keywords].values():
                    if not type(value) == kwargs_type:
                        raise ValueError(
                           "Invalid Type: " + argspec.keywords \
                             + " is not " + str(kwargs_type)
                           )

            # do func
            return func(*args, **kwargs)

        return new_func
    return type_checker

I will write a usage example

example.py


@type_definition(int, int, str)
def foo(a, b, c=0):
    return a + b + int(c)

foo(1, 1)
# -> 2
foo(1, 1, 1)
# ValueError: Invalid Type: c is not <type 'str'>
foo(1, 1, "1")
# -> 3


Recommended Posts

Function argument type definition in python
Python function argument summary
First python (data type, control statement, function definition)
Create a function in Python
Use callback function in Python
ntile (decile) function in python
Nonlinear function modeling in Python
Draw implicit function in python
Immediate function in python (lie)
Convenient argument passing technique in Python (tuple, dictionary type)
[python] Callback function (pass function as argument)
Implement R's power.prop.test function in python
python function ①
Included notation in Python function arguments
[Python] function
Write AWS Lambda function in Python
Dynamically load json type in python
Measure function execution time in Python
Note: The meaning of specifying only * (asterisk) as an argument in the Python function definition.
Type specified in python. Throw exceptions
Function synthesis and application in Python
Basic Python operation 2nd: Function (argument)
python function ②
Check the argument type annotation when executing a function in Python and make an error
Specify your own class in class argument and return type annotation in Python
Precautions when pickling a function in python
[Introduction to Udemy Python3 + Application] 48. Function definition
OR the List in Python (zip function)
Type annotations for Python2 in stub files!
python generated csv-like definition single element type
Write a short property definition in Python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Python numeric type
python enumerate function
Meta-analysis in Python
Unittest in python
Python> function> Closure
Epoch in Python
Discord in Python
[Python] Generator function
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Python> function> Inner function
Csv in python
Disassemble in Python