Yuriy F
Yuriy F

Reputation: 361

Use a string in Python as a parameter for a function

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

Answers (2)

vishes_shell
vishes_shell

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

Alex Hall
Alex Hall

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:

  1. You code does not have a syntax error. Not every error is a syntax error.
  2. At the end you wrote phonebook instead of phoneBook.
  3. phoneBook.dir does not mean anything.
  4. help does the printing and returns None, so simply help(...) is enough, while help(...) + '...' will fail and print(help(...)) is not needed.
  5. dir(phonebook)[i] appears twice, dir(phonebook) three times. Use variables!
  6. Use a better for loop! You rarely need for i in range(...), you can usually just iterate directly over things.
  7. If you want to print blank lines or something else after the help for each method, simply print('\n\n').
  8. 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

Related Questions