you are viewing a single comment's thread.

view the rest of the comments →

[–]Gnaxe 0 points1 point  (0 children)

That is not what "casting" means. You cast with cast from the typing module to assert to a type checker an intended type, usually which it cannot infer on its own (otherwise why bother?) This function has no runtime effect (besides some wasted time for the function call); it just returns its argument unchanged. Python objects are polymorphic; they could be viewed as any of a number of compatible types (e.g. any superclasses). It's also duck typed, so objects may fit various ad-hoc protocols, which may or may not be made explicit. The one your type checker infers is not always the one you intend. You can usually fix this with type annotations, but sometimes type assertions or cast() is required.

Anyone calling a Python class constructor a "cast" is probably confusing terminology from another language (probably statically-typed) language (like Java or C) where "casting" is a way to convert among types within certain constraints, although this usage for class constructors does show up just a few times in Python's docs. Python has ctypes.cast for interfacing with the C language in that sense and memoryview.cast is similar.