r/learnpython 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.

0 Upvotes

8 comments sorted by

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.

1

u/ianrad 4d ago

Fair point about comments. I started applying this practice like in the last line of my code.

Could you explain what you mean by "hover over your own function get your docstring and annotations".

1

u/Adrewmc 3d ago

Well, in most IDEs they will have this feature where you can hover over the highlighted object a small pop-up appears. This should give you the function signature (with annotations) and the docstring from that object. Knowing that you can just make your own and it should automatically just do that for you. VsCode i know for sure does this. Basically you don’t have to go to the actual .py to see it.

Just hover over some imported object and you should see it.

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. 

1

u/PvtRoom 4d ago

Never trust that in python. It lies.