1

For fun/to practice python, I am trying to create a program that displays the contents of a module. Looks like this:

import sys
print "Here are all the functions in the sys module: "
print dir(sys)
function = raw_input("Pick a function to see: ")

cnt = True

while cnt:
        if function in dir(sys):
                print "You chose:", function
                cnt = False
        else:
                print "Invalid choice, please select again."
                cnt = True
print dir("sys." + function)

But every time, no matter what string the variable function is set to, the dir("sys." + function) call always defaults to the same output as dir(string) (or so I think!)

What is happening and is there a way for me to do this properly and get the output I really want (for example, the variable function is set to stdin and I get the output for dir(sys.stdin))?

1
  • 1
    use while cnt: instead of while cnt == True: Commented Feb 12, 2013 at 14:44

3 Answers 3

4

You want to retrieve the actual object from the module; use the getattr() function for that:

print dir(getattr(sys, function))

dir() does not interpret the contents of the objects you pass to it; a string that happens to contain a value that corresponds to the name of a function in a module is not dereferenced for you.

Sign up to request clarification or add additional context in comments.

7 Comments

@Pieters What senses have the words string and value in your sentence please ?
@eyquem: String: the str type in python. Value: the contents (characters) of the string.
@Pieters You mean, for string: an object of type 'str' ?
@eyquem So you meant: "an object of type 'str' that happens to contain a value that corresponds..." , am I right ?
Yes. Where is this going? We usually talk about strings, not about "an object of type str", because that's cumbersome and overly verbose.
|
2
f = getattr(sys, function) # get function object
help(f) # display help for the function

Note: dir(f) would return the same info for all functions with the same type.

Comments

1

As dir works on objects, you need to get the object somehow from the name.

First option is to use getattr:

print dir(getattr(sys, function))

If you want to be more flexible (and are ready to take security risk), you can use eval:

print dir(eval('sys.' + function))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.