how python dir works

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Apr 18 20:44:21 EDT 2012


On Wed, 18 Apr 2012 08:56:24 -0700, cheung wrote:

> how does the function  "dir" works, where can I get the python-c  source
> of dir in py2.7 project.

Look for the function builtin_dir in Python/bltinmodule.c of the source 
code.


> I looked the python_c source for hours, can't find how dir works.
> 
> for example:
>    if a user input a *.py source file like foo.py, i wanna parse the
>    file, and find all the functions and all the classes in the foo.py.

dir() will not help you parse a Python source code file. Read the Fine 
Manual: dir() takes as argument an object, not source code or a file name.

http://docs.python.org/library/functions.html#dir


In general, you cannot find all the functions and classes created by 
module foo unless you actually execute the code in foo. The best way to 
do that is to use import or __import__.

The second-best way is to use some variation of exec or execfile on the 
source code. Be sure to pass your own namespace to ensure you don't 
overwrite code your own functions with those from the foo file.

To analyse the source code without executing it, use the tokenize module:

http://docs.python.org/library/tokenize.html



-- 
Steven



More information about the Python-list mailing list