Proper way to assert type of variable in Python

后端 未结 3 1149
遇见更好的自我
遇见更好的自我 2021-01-31 01:13

In using a function, I wish to ensure that the type of the variables are as expected. How to do it right?

Here is an example fake function trying to do just this before

3条回答
  •  生来不讨喜
    2021-01-31 02:03

    The isinstance built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:

    def my_print(text, begin, end):
        "Print 'text' in UPPER between 'begin' and 'end' in lower"
        try:
          print begin.lower() + text.upper() + end.lower()
        except (AttributeError, TypeError):
          raise AssertionError('Input variables should be strings')
    

    This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)

提交回复
热议问题