6

Python has a nice feature that gives the contents of an object, like all of it's methods and existing variables, called dir(). However when dir is called in a function it only looks at the scope of the function. So then calling dir() in a function has a different value than calling it outside of one. For example:

dir()
> ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
def d():
  return dir()
d()
> []

Is there a way I can change the scope of the dir in d?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Hovestar
  • 1,544
  • 4
  • 18
  • 26

1 Answers1

11

dir() without an argument defaults to the current scope (the keys of locals(), but sorted). If you wanted a different scope, you'd have to pass in an object. From the documentation:

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

For the global scope, use sorted(globals()); it's the exact same result as calling dir() at the module level.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343