What is the point of type hinting when Python doesn't even respect it!?
is it a good practice to use type annotation on nearly everything that is a variable ?
How am I supposed to do type annotation in Python when it's all Any type?
How many Python core developers use type annotations?
So infuriating because I feel like my function is lying to me when it ends up letting other objects through the parameter.
Now every function I created needs an instance check which is unintuitive, verbose, and easily forgotten.
def wtf(string: str, integer:int): return 'TYPE HINT DOESNT DO ANYTHING' print( wtf( 123, 'wtf') ) >> 'TYPE HINT DOESNT DO ANYTHING'
EDIT:
Turns out it is a noob mistake. Type hint only functions as a signal for IDE, but developers get to do whatever they want to your parameter.
If you really must enforce it, you got to have the line
if not isinstance(string, str): raise TypeError()
Still, I don't like that this behavior isn't taught until it happens. So much time wasted on debugging production code when you take for granted your function is accepting only restricted data when it doesn't.
is this for ex considered a good practice or not "list[tuple[Callable[[str], str],Callable[[str], str]]]" ?
So for example, I am using BeautifulSoup library. And unlike other statically typed languages, no one seems to care about types in Python so the documentation does not tell me what's the return type of a function.
from bs4 import BeautifulSoup
soup = BeautifulSoup(self.driver.page_source, "html.parser")
result = soup.find("pre").text
I use VSCode as my IDE, and when I hover over variables soup and result, it says unknown. So how am I supposed to annotate those types?
Starting with Python 3.9, you can use list[str] as a type annotation, which doesn't require importing anything, as documented in PEP 585.
Python 3.5 standardizes the way function annotations are used for type hinting, as documented in PEP 484. To annotate a list of strings, you use List[str], where List is imported from the typing module. You can also use Sequence[str] if your function accepts any list-like sequence, or Iterable[str] for any iterable.
Python 3.4 and earlier doesn't specify a format for its function annotations, it merely provides a mechanism that allows you to use any expression as the annotation. How the annotations are interpreted is up to you and the libraries you use.
In Python 3.9+, list (with a lowercase l) can be used in type annotations and your code should work as is. On older versions of Python you need to import typing.List and use it instead
from typing import List
to_addresses: List[str]
Note the capital L.
You might want to consider something more specific, e.g.
import typing
Address = typing.NewType("Address")
See NewType docs
The static type checker will treat the new type as if it were a subclass of the original type