Is Python type safe?

后端 未结 8 1530
猫巷女王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:41

    Not in your wildest dreams.

    #!/usr/bin/python
    
    counter = 100          # An integer assignment
    miles   = 1000.0       # A floating point
    name    = "John"       # A string
    
    print counter
    print miles
    print name
    
    counter = "Mary had a little lamb"
    
    print counter
    

    When you run that you see:

    python p1.py
    100
    1000.0
    John
    Mary had a little lamb
    

    You cannot consider any language "type safe" by any stretch of the imagination when it allows you to switch a variable's content from integer to string without any significant effort.

    In the real world of professional software development what we mean by "type safe" is that the compiler will catch the stupid stuff. Yes, in C/C++ you can take extraordinary measures to circumvent type safety. You can declare something like this

    union BAD_UNION
    {
       long number;
       char str[4];
    } data;
    

    But the programmer has to go the extra mile to do that. We didn't have to go extra inches to butcher the counter variable in python.

    A programmer can do nasty things with casting in C/C++ but they have to deliberately do it; not accidentally.

    The one place that will really burn you is class casting. When you declare a function/method with a base class parameter then pass in the pointer to a derived class, you don't always get the methods and variables you want because the method/function expects the base type. If you overrode any of that in your derived class you have to account for it in the method/function.

    In the real world a "type safe" language helps protect a programmer from accidentally doing stupid things. It also protects the human species from fatalities.

    Consider an insulin or infusion pump. Something that pumps limited amounts of life saving/prolonging chemicals into the human body at a desired rate/interval.

    Now consider what happens when there is a logic path that has the pump stepper control logic trying to interpret the string "insulin" as the integer amount to administer. The outcome will not be good. Most likely it will be fatal.

提交回复
热议问题