Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dir() function in commandline vs IDLE

Tags:

python

I've tried running the following code in IDLE:

import sys
dir(sys)

There is no result:

>>>

But when I run it in the command line, i get this:

>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']

Can someone explain the difference in what I did?

like image 472
dopatraman Avatar asked Dec 27 '11 19:12

dopatraman


1 Answers

The root of the problem is a misunderstanding of what dir() does. If you use it at the interactive Python prompt >>>, it is easy to think it means "print the names available in the given object." However, what it actually does is return the names available in the given object.

As a convenience, the interactive Python shell prints the result of the last statement, if any (None is assumed to mean that the statement did not produce a result). So when you do dir() at the >>> prompt, the result of dir() is printed. However, it is not dir() but the Python shell that does the printing.

So in your IDLE session, you are executing dir() but not doing anything with the result. Since you are not executing the statement interactively but as a script, Python doesn't automatically print it for you, since it doesn't know you want that (indeed, most of the time you don't). You could store it in a variable for later use:

sysdir = dir(sys)

Since it's a list, you could iterate over it:

for n in dir(sys):
    # do something

Or you could print it:

print dir(sys)    # Python 3 requires print(dir(sys))
like image 115
kindall Avatar answered Sep 21 '22 01:09

kindall