A Simple Method for checking parameter types in Python

Source: Internet
Author: User

A Simple Method for checking parameter types in Python

This article mainly introduces a simple method for checking the parameter type in Python. This article describes how to use the decorator to check the parameter type and provides code examples. For more information, see

Python is a weak type language, and many friends who transfer from C/C ++ are not very comfortable at first. For example, you cannot specify the parameter type when declaring a function. Using C for analogy, that is, all parameters are of the void * type! Forced conversion of the void type is widely regarded as a bad habit in C ++.

Python naturally has no type forced conversion because it is a dynamic language. First, all objects are inherited from objects. Second, they have powerful introspection. If a method that does not exist is called, an exception is thrown. In most cases, we do not need to perform parameter type check except for some special cases. For example, if a function accepts a str type, unicode is input in the result during the actual call, and no code is overwritten during the test, the problem is serious. The solution is also very simple. With the help of Python's introspection, it is easy to determine the parameter type. However, writing and checking code everywhere is cumbersome, and the actual value it brings is not high. A good solution is to use the decorator.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

'''

>>> NONE, MEDIUM, STRONG = 0, 1, 2

>>>

>>> @ Accepts (int, int, int)

... Def average (x, y, z ):

... Return (x + y + z)/2

...

>>> Average (5.5, 10, 15.0)

TypeWarning: 'average' method accepts (int, int, int), but was given

(Float, int, float)

15.25

'''

Def accepts (* types, ** kw ):

"Function decorator. Checks that inputs given to decorated function

Are of the expected type.

 

Parameters:

Types -- The expected types of the inputs to the decorated function.

Must specify type for each parameter.

Kw -- Optional specification of 'debug' level (this is the only valid

Keyword argument, no other shoshould be given ).

Debug = (0 | 1 | 2)

 

"""

If not kw:

# Default level: MEDIUM

Debug = 1

Else:

Debug = kw ['debug']

Try:

Def decorator (f ):

Def newf (* args ):

If debug = 0:

Return f (* args)

Assert len (args) = len (types)

Argtypes = tuple (map (type, args ))

If argtypes! = Types:

Msg = info (f. _ name __, types, argtypes, 0)

If debug = 1:

Print> sys. stderr, 'typewarning: ', msg

Elif debug = 2:

Raise TypeError, msg

Return f (* args)

Newf. _ name _ = f. _ name __

Return newf

Return decorator

Failed t KeyError, key:

Raise KeyError, key + "is not a valid keyword argument"

Failed t TypeError, msg:

Raise TypeError, msg

 

Def info (fname, expected, actual, flag ):

"" Convenience function returns nicely formatted error/warning msg ."""

Format = lambda types: ','. join ([str (t). split ("'") [1] for t in types])

Expected, actual = format (expected), format (actual)

Msg = "'% s' method" % fname \

+ ("Accepts", "returns") [flag] + "(% s), but" % expected \

+ ("Was given", "result is") [flag] + "(% s)" % actual

Return msg

In essence, this is also a runtime check, but the effect is already good.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.