How can I type-check variables in Python?

后端 未结 9 1589
南旧
南旧 2020-12-15 03:59

I have a Python function that takes a numeric argument that must be an integer in order for it behave correctly. What is the preferred way of verifying this

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-15 04:19

    Programming in Python and performing typechecking as you might in other languages does seem like choosing a screwdriver to bang a nail in with. It is more elegant to use Python's exception handling features.

    From an interactive command line, you can run a statement like:

    int('sometext')
    

    That will generate an error - ipython tells me:

    : invalid literal for int() with base 10: 'sometext'
    

    Now you can write some code like:

    try:
       int(myvar) + 50
    except ValueError:
       print "Not a number"
    

    That can be customised to perform whatever operations are required AND to catch any errors that are expected. It looks a bit convoluted but fits the syntax and idioms of Python and results in very readable code (once you become used to speaking Python).

提交回复
热议问题