zlacker

[parent] [thread] 2 comments
1. Doxin+(OP)[view] [source] 2024-06-06 08:38:14
It's assumed the input is an int. If not you can do len(str(int(x))) to make sure it is which strips leading zeroes off in the process.
replies(1): >>lelant+y
2. lelant+y[view] [source] 2024-06-06 08:43:44
>>Doxin+(OP)
That's really my beef with languages like Python - typing is an afterthought. I literally get more safety from C than I do from Python:

    def numDigits(num):
        return len(str(num))
    
    print (numDigits(1))      # Returns the correct answer
    print (numDigits("1"))    # Returns the correct answer
    print (numDigits("01"))   # Returns the incorrect answer
The "returns the wrong answer" is the problem. If the input is the wrong type, I expect there to be an error raised, not silently give me wrong answers.
replies(1): >>Doxin+Ea
◧◩
3. Doxin+Ea[view] [source] [discussion] 2024-06-06 10:11:22
>>lelant+y
Fair enough I suppose. Though I should mention that python is much better at these than a lot of dynamically typed languages. All of these give errors in python but return nonsense in e.g. javascript:

    1+"1"
    []+{}
    ({}).foo
    []/2
Of course there's the type checkers for python like mypy and pyright but in my experience the type systems these provide are wildly underpowered for statically typing even slightly more complex idiomatic python.

Re the num digits example: One way to go about this is to add asserts for checking the input types, though generally in python it's considered more idiomatic to check how an object behaves than what type it is.

In any case in practice I find that by far most type systems, bolted on or built in or otherwise, are more of a hassle than they are worth. One of the few exceptions I've found so far is D. When you rewrite the num digits function in D such that it accepts any type like the python example does, it should be of no surprise that it has the exact same bug as the python version:

    int numDigits(T)(T num){
        return num.to!string.length
    }
I'm not entirely sure what my point is other than to point out that typing in python isn't an afterthought. it just uses a different type system to what you're used to which allows for bugs you're not used to.
[go to top]