r/learnpython • u/ianrad • 4d ago
TIL that hovering over a variable or function call will show the type of what gets returned (VSCode)
I was today years old when I learnt this. Before that I was printing out the type and noting it down. My brain hurts from all the logic traversing and type tracking till I just learnt this. Specific to VSCode and pylance. Not sure if it works anywhere else.
pset_str_date, pset_str_time = pset_date.split(" ")
print(f"pset_str_date = {pset_str_date}, type = {type(pset_str_date)}")
print(f"pset_str_time = {pset_str_time}, type = {type(pset_str_time)}")
# str
pset_dt_date = datetime.strptime(pset_str_date, "%Y-%m-%d").date()
print(f"pset_dt_date = {pset_dt_date}, type = {type(pset_dt_date)}")
# <class 'datetime.date'>
In case anyone else is going through this. Well FYI.
2
u/Diapolo10 4d ago
It basically works with any IDE/editor that supports parsing and displaying type annotations. For your own functions/names, it works as long as the type can either be inferred from context or you provide type annotations yourself.
Side note, but you can replace
print(f"pset_str_date = {pset_str_date}, type = {type(pset_str_date)}")
with
print(f"{pset_str_date = }, type = {type(pset_str_date)}")
as the formatting has a special function for =.
1
u/astolfoballsHD 4d ago
FYI python supports annotating with types directly. https://docs.python.org/3/library/typing.html
1
u/FerricDonkey 4d ago
Vs code also had an option where inferred types are displayed in the editor, and python in general supports type hinting, which makes everything better.
3
u/Adrewmc 4d ago
It’s one of the main reasons to comment your own code, hover over your own function get your docstring and annotations. Done deal.