Is Python type safe?

后端 未结 8 1526
猫巷女王i
猫巷女王i 2021-01-30 17:14

According to Wikipedia

Computer scientists consider a language \"type-safe\" if it does not allow operations or conversions that violate the rules of the

8条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 17:27

    Because nobody has said it yet, it's also worth pointing out that Python is a strongly typed language, which should not be confused with dynamically typed. Python defers type checking until the last possible moment, and usually results in an exception being thrown. This explains the behavior Mureinik mentions. That having been said, Python also does automatic conversion often. Meaning that it will attempt to convert an int to a float for a arithmetic operation, for example.

    You can enforce type safety in your programs manually by checking types of inputs. Because everything is an object, you can always create classes that derive from base classes, and use the isinstance function to verify the type (at runtime of course). Python 3 has added type hints, but this is not enforced. And mypy has added static type checking to the language if you care to use it, but this does not guarantee type safety.

提交回复
热议问题