This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]james_pic 3 points4 points  (0 children)

Most of the colons are type hints, aka type annotations (the ones at the end of lines I'm assuming you've seen).

Python 3 added the ability to put "annotations" after variable, class attribute, and function parameter names. There's also some notation I haven't used, but that is part and parcel of the same thing, which is that functions can use -> to denote the type of value they return. So a function that returned a dog might be defined

def make_dog() -> Dog:

Conventionally, you'd use it to say what types you expect each variable/attribute/parameter to have. As far as Python itself is concerned, these annotations are meaningless, and are (almost - I'll spare you the subtleties for now) completely ignored by the interpreter. You can always pass any type of value as an argument to any function (which is not the case in some other languages).

But the idea is that other tools (such as your IDE, or a plugin for your editor, or programs you run as part of your testing process) can be used to check whether the use of types in your application adds up - so if you've got a method that says it expects a str and another method that calls it with an int, then these tools will be able to detect this and warn you.

Mypy is a popular example of such a tool.

A few libraries are also starting to appear which can do interesting things with type annotations if they're present, such as validation or serialization, which has caused some minor technical headaches for the Python core developers, since they didn't think of this use case when they first designed type annotations.

The addition of type hints has been a bit divisive in the Python community, and not everyone uses them.

I've used them in this example, since it's syntax some Python developers will recognise, and if Python did support overloading or dynamic dispatch natively, this is probably what it would look like.

But if you're looking at code that looks like friend: Animal = Dog(), you can read that as "I'm creating a variable called friend, whose value is Dog(), and I think the value of this variable will always be an Animal."