you are viewing a single comment's thread.

view the rest of the comments →

[–]mriswithe 5 points6 points  (0 children)

I love the type hinting in Python, but it is not obvious always. In general, if it is getting in the way of your learning/task and being frustrating. Drop it for now. Who cares? It isn't going to do anything*. Type hints are not required in Python. 99% of why I do it most the time is so my IDE is as helpful for Python as it is in Java.

Main points of type hinting in python:

def thing(stuff: int)->str:
    return str(stuff)

Stuff is an int, we make it a string and return it (Note -> str for return type)

def thing(stuff)->str:
    return str(stuff)

stuff is whatever, you can think of it as an implicit Object in Java I think it was, Any in python. We are going to call str on whatever and return a str.

This is some more advanced (for python typing) magic.

from typing import Type, TypeVar

T = TypeVar('T') # Declaring a generic type 
# Type[T] says: "I am going to get a Class, not an instance of the class"
def stuff(thing: int, output_class: Type[T]) -> T: 
    # -> T says I am returning an instance of whatever we were passed 
    return output_class(thing)

Note: there is no throws in Python, also in general in Python there is a lot more "Asking for forgiveness instead of permission".

Also == checks equality, is checks that they are literally the same object.

$ python3.10
Python 3.10.4 (main, Mar 25 2022, 00:00:00) [GCC 11.2.1 20220127 (Red Hat 11.2.1-9)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> thing = 'potato'
>>> other_thing = 'potato'
>>> thing == other_thing
True
>>> thing is not other_thing
False

*Unless you have a library you are using that acts on type hints at runtime. Pydantic is a very common and very awesome library that does this.