Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a quick way to get the R equivalent of ls() in Python?

Tags:

python

r

I'm new to Python and normally use R, and regularly use ls() to get a vector of all the objects in my current environment, is there something that does the same thing quickly in Python?

like image 200
h.l.m Avatar asked Dec 18 '13 22:12

h.l.m


1 Answers

You're probably looking for dir:

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.

This may not be entirely obvious at first, but when you're at global scope (as you usually are at the command-line interpreter), the "current local scope" is the global scope (in this case, of the __main__ module). So, this will return all the variables and functions you've defined, all the modules you've imported, and a few things that get attached to every module or just to __main__. For example:

$ python3.3
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__']
>>> import sys
>>> i = 2+3
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__', 'i', 'sys']

This is always the same thing as sorted(locals().keys()), but dir() is a lot easier to type. And of course it's nicely parallel with dir(sys) to get the things defined by the sys module, dir(i) to get the attributes of that integer object 5, etc.

like image 100
abarnert Avatar answered Sep 29 '22 05:09

abarnert