34

I know that the dir() function gives you back either the names defined in the current scope or the names defined in an object. But why is it called dir()? Is it some mysterious acronyms like LISP's CAR and CDR?

Y.H Wong
  • 7,151
  • 3
  • 33
  • 35

4 Answers4

33

It gives you an alphabetical listing of valid names (attributes) in the scope (object). This is pretty much the meaning of the word directory in english.

wim
  • 338,267
  • 99
  • 616
  • 750
3

It's probably just an analogy to directory listing. list() is used for creating a lists, so dir() is used for listing elements object which has a similar tree-like structure to file system.

Just a guess.

Michał Šrajer
  • 30,364
  • 7
  • 62
  • 85
  • Did I just ask a stupid question? Is it really simple like this? – Y.H Wong Oct 08 '11 at 10:37
  • kinda.. but maybe english is not your first language? – wim Oct 08 '11 at 10:59
  • @wim: You are right. English is not my first language. I see you have over 2000 reputation. You can edit my answer. :-) – Michał Šrajer Oct 08 '11 at 19:33
  • @Y.HWong: It's human nature to be curious. I looked at the python source code and there is no comments except for docstring for the `dir()`. I'm sure if there would be some magic about it, it will be described there. It wasn't, so I guess it's that simple. – Michał Šrajer Oct 08 '11 at 19:43
  • @wim English is not my first language, but I think I've been in the states long enough to be my second :) I guess I just can't wrap my head around having a "directory" of any "object". What does a directory of a class mean? I got some mind blockage there. – Y.H Wong Oct 13 '11 at 09:23
  • I think the MS-DOS analogy is a red herring. The directory of a class would just be a common-sense usage of the meaning of directory in plain english, like I wrote in my answer below. – wim Oct 13 '11 at 11:41
2

Most likely it's a reference to the DIR command of MSDOS. DIR does directory listings, like the Unix command ls.

Petr Viktorin
  • 65,510
  • 9
  • 81
  • 81
1

I know that without arguments, it returns a list of names in the current local scope. For example:

>>>z = 3
>>>def f1():
...    x = 1
...    y = 2
...    print dir()
...
>>>f1()
['x','y']
>>>print dir()
['z',something else]

With arguments, it returns a sorted dictionary keys of all the attributes of that object. for example:

>>>import sys
>>>dir(sys)
[a bunch of attributes of sys]
zleung
  • 57
  • 4