Reputation: 1627
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?
Upvotes: 6
Views: 1088
Reputation: 1121584
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.
Upvotes: 11