r/Python • • May 30 '19

Dear python2 user

Post image
1.9k Upvotes

275 comments sorted by

View all comments

Show parent comments

0

u/cj81499 May 30 '19

runtime type checking doesn't sound to me like something that would take a lot of time. Care to explain why you think this?

2

u/alkasm github.com/alkasm May 30 '19

Not for single objects, no---but think of data structures. Is it going to check that every element in a list is an int? What if the list has a million elements?

1

u/cj81499 May 30 '19

Suppose we have an array of type T, wouldn't running something like

if (type(element_to_add) != T):
    throw TypeError

for each insertion be enough? I can't imagine that having a huge performance impact.

2

u/alkasm github.com/alkasm May 30 '19

But how does a function that you call know that your list is full of those types without checking? Sure, you can make your function only accept a TList object, which has elements of type T checked on appending. But you can get around that in Python, since we have no real safety around properties for the classes we write. If you have a wrapper class around a list, you could just obj.inner_list.append(not_type_T_val) for example. And any one way around this (in Python) has a workaround. So you can't guarantee that TList has type T elements. The only way you can guarantee it is to check. Every element. Every time you use the list. And if there's no guarantees, there's no point in having it check during runtime.

Edit: and it would be raise in Python :)

-1

u/billsil May 31 '19

What if the list has a million elements?

You should probably use a numpy array. Also, type checking doesn't actively check your types, so it's a moot point.

2

u/alkasm github.com/alkasm May 31 '19

? The person I'm responding to is suggesting type checking during runtime in pure Python. Numpy is a different discussion since the types are enforced in C.

1

u/billsil May 31 '19

It still has a type (e.g., int32, int64, float64, complex128, U8, S8, etc.). The PSF has stated that they're not going to implement type checking at runtime, so it's kinda irrelevant.

0

u/zardeh May 30 '19

It is, you're adding an extra function call (essentially, sometimes more) for every argument, for every function call, ini your program. Even if your type-checking function is very, very, very fast, go and look at profiling output of a simple program and see how many function calls happen. Its lots. Now imagine a isinstance checks, MRO resolutions, or worse, trying to resolve protocol or generic validity on every one of those calls.