Reputation: 361
I have a problem I can't solve in Python. The question is hard to even put into words, so see the example below.
phoneBook = {"Joe":12, "Jason":13, "Johnny":14}
for i in range(0, len(dir(phoneBook))):
if "__" not in dir(phoneBook)[i]:
print(help(phoneBook.dir(phonebook)[i]) + "\n\n")
What I want to do is to print the help() method for each dir() entry that doesn't contain underscores. (i.e., calling dir(phoneBook) returns clear, copy, fromkeys, get, items, etc...). I want the help() method to then print each of the values that dir() returns, as seen in the for loop above. However, if I use the syntax as shown above, I get a syntax error. There are other applications of this principle, this is a quick example that I can think of off the top of my head.
Thanks in advance.
Upvotes: 1
Views: 46
Reputation: 23564
You mean smth like this? This will indeed print all non-dunder methods.
phoneBook = {"Joe":12, "Jason":13, "Johnny":14}
for method in dir(phoneBook):
if "__" not in method:
print(help(getattr(phoneBook, method)) + "\n\n")
From your title getting attribute from string is getattr(your_object, your_method_str)
But actually when you will try to help(getattr(phoneBook, method)) + "\n\n"
you will get TypeError
since help
don't return a thing. So you need to handle it accordingly, maybe just with help(getattr(phoneBook, method_name))
as @Alex Hall said
UPDATE:
if you want to use custom formatting of method description you can use .__doc__
print(getattr(phoneBook, method).__doc__, end='\n\n')
Upvotes: 1
Reputation: 36043
Here is a working version:
phoneBook = {"Joe": 12, "Jason": 13, "Johnny": 14}
for method_name in dir(phoneBook):
if "__" not in method_name:
help(getattr(phoneBook, method_name))
More details:
phonebook
instead of phoneBook
.phoneBook.dir
does not mean anything.help
does the printing and returns None
, so simply help(...)
is enough, while help(...) + '...'
will fail and print(help(...))
is not needed.dir(phonebook)[i]
appears twice, dir(phonebook)
three times. Use variables!for i in range(...)
, you can usually just iterate directly over things.print('\n\n')
.help(method)
does not work because for example if method
is 'clear'
then that will be help('clear')
and since there is no builtin function simply called clear
that doesn't give anything. In other words you want the help for phoneBook.clear
, not just clear
by itself. To dynamically get phoneBook.<method name here>
you use getattr(phoneBook, method)
.Upvotes: 2