“Secret” use of annotations in Python!

Hunter
2 min readSep 27, 2021

So, I was just playing around with Python when I realized, Python evaluates the type annotations you provide!

For those, who don’t know what are annotations, these are just some typehints which make your life easier. The syntax for the same is something like

a: int = 1

So, int is an annotation, which tells the IDE that the variable a is of type int . This way, when you try to work with the variable a , your IDE would provide you with the list of operations, which can be done only on the instances of int class!

Anyways, back to the topic. So, one day I was messing with disnake, when I found out that there is another way, except doing the usual bot.run(TOKEN) to run your bot! (Warning, this method can mess with people’s brains when they try to comprehend how the bot is running :D)

So, you all know that we run the bot with bot.run , which is kinda old now. So a new way to run the bot would be something like this →

def run(_: bot.run(TOKEN)):_ or pass

So, here we have just made a simple function and added bot.run() as an annotation. the _ or pass just completes the function body so that it doesn’t raise a SyntaxError!

Of course this is not supported by Python itself and is just a workaround to mess with people.
Sadly, type checkers like PyLance hates my work around (cz this is not supported by Python itself) and it would just show an error like this →

You can always ignore the error by typing in # type: ignore in that line!

So this will be it for today’s blog. Also, if you try to print anything or add logic in the function, that would not be executed since bot.run() is a blocking call.

Be sure to post your implementations and ideas in the comment section! I would LOVE to see them :D

Contact me →

--

--

Hunter

I am Hunter. Nice to meet you! I am a student and also a Python Coder. Stay away from me, I got a fetish for Python codes 😉