Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dir inside function

Tags:

python

scope

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?

like image 624
Hovestar Avatar asked Jan 13 '15 21:01

Hovestar


People also ask

What is dir () function?

The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.

What is __ DIR __ in python?

Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be called and must return the list of attributes. It takes a single object type argument. The signature of the function is given below.

What is HELP () and dir ()?

Help on built-in function append: append(...) method of builtins.list instance L.append(object) -> None -- append object to end. In python, dir() shows a list of attributes for the object passed in as argument , without an argument it returns the list of names in the current local namespace (similar to locals().

What is the usage of HELP () and dir () function in python Mcq?

help() – it is built in function python which when executed, returns docstring along with module name, filename, function name and constant of the module passed as argument. dir()- it is built in function in python which is used to display properties and methods of object passed as an argument in it.


1 Answers

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.

like image 94
Martijn Pieters Avatar answered Sep 21 '22 00:09

Martijn Pieters