Definition des Funktionsargumenttyps in Python

Es gab eine Zeit, in der ich einen Typ in Python definieren wollte, also schrieb ich vorerst einen Funktionsdekorateur Wenn mir gesagt würde, ich solle Cython verwenden, hätte ich keine Kinder, aber ...

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

Ich werde ein Anwendungsbeispiel schreiben

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

Definition des Funktionsargumenttyps in Python
Zusammenfassung der Python-Funktionsargumente
Erste Python (Datentyp, Steueranweisung, Funktionsdefinition)
Erstellen Sie eine Funktion in Python
Verwenden Sie die Rückruffunktion in Python
ntile (Dezil) -Funktion in Python
Nichtlineare Funktionsmodellierung in Python
Zeichne die Yin-Funktion in Python
Sofortige Funktion (Lüge) in Python
Praktische Technik zum Übergeben von Argumenten in Python (Taple, Wörterbuchtyp)
[Python] Rückruffunktion (Funktion als Argument übergeben)
Implementieren Sie die Funktion power.prop.test von R in Python
Python-Funktion ①
Inklusive Notation im Argument der Python-Funktion
[Python] -Funktion
Schreiben Sie die AWS Lambda-Funktion in Python
Laden Sie JSON-Typen dynamisch mit Python
Messen Sie die Ausführungszeit von Funktionen in Python
Hinweis: Bedeutung der Angabe von nur * (Sternchen) als Argument in der Funktionsdefinition von Python
Typ in Python angegeben. Ausnahmen auslösen
Funktionssynthese und Anwendung in Python
Python-Funktion ②
Vorsichtsmaßnahmen beim Beizen einer Funktion in Python
[Einführung in die Udemy Python3 + -Anwendung] 48. Funktionsdefinition
Nehmen Sie die logische Summe von List in Python (Zip-Funktion)
Geben Sie Anmerkungen für Python2 in Stub-Dateien ein!
Python-generierte CSV-ähnliche feste Elementform
Schreiben Sie eine kurze Eigenschaftsdefinition in Python
Quadtree in Python --2
Python in der Optimierung
CURL in Python
Geokodierung in Python
SendKeys in Python
Numerischer Python-Typ
Python-Aufzählungsfunktion
Metaanalyse in Python
Unittest in Python
Python> Funktion> Schließen
Epoche in Python
Zwietracht in Python
[Python] Generatorfunktion
Deutsch in Python
DCI in Python
Quicksort in Python
nCr in Python
N-Gramm in Python
Programmieren mit Python
Plink in Python
Konstante in Python
FizzBuzz in Python
SQLite in Python
Schritt AIC in Python
LINE-Bot [0] in Python
Python> Funktion> Innere Funktion
CSV in Python
Reverse Assembler mit Python