I was facing an issue which is related to yours but, might help others for the same situation as I have faced.
What I was trying:
I was learning datetime
module in python and created an object of that. Now, to get the details from that object, I needed to manually you know, press the Tab key, get list of available methods/attributes and then type them and finally then after get the result. And needed to repeat for other times too!
What I needed:
Since there was a mixture of Methods (which are callable) and Attribute (which can't be called) I needed to automate all of them to be used or called (se) and see their result in just a single loop.
What I tried:
I just made a simple looking for loop which iterates over dir(datetimeobj)
... Let me show you how...
# Creating an Obj
date = datetime.datetime(2020,1,29,12,5)
# Printing (But won't work, discussing 'why' in a bit)
for method in dir(date):
if callable(method):
print(f"{method}() --> {date.method()}")
else:
print(f"{method} --> {date.method}")
Looks fine, right! It should work... but, no - it won't.
Executing this code will result in error...
##Error: 'datetime.datetime' object has no attribute 'method'
The Problem:
Aha! We are trying to call method
which is the string so, date.method()
/ date.method
is invalid.
Towards Solution:
I will try not to discuss so long here... as the code given is self-explanatory, but just see this...
dir_without_dunders = [method for method in dir(date) if not method.startswith('_')]
for method in dir_without_dunders:
RealMethod = eval(f'date.{method}')
try:
if callable(RealMethod):
print(f"{method}() --> {RealMethod()}")
else:
print(f"{method} --> {RealMethod}")
except:
continue
Code summary:
• Created dir_without_dunders
for you know...
• Took another variable RealMethod
because method
will be having the string (name) just to make printing more clear and sensible
• The main solution is with eval(f'date.{method}')
that is the hack.
• Why used try
block? - It is because not all methods can be called without any parameters and they needed different set and number of parameters, so I called only those which can be called simply!
That's it.
Works for this datetime object calls as it has majority of methods with empty set of parameters.