how python dir works

C

cheung

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

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.

i wanna use the python-c source or python Lan. to solve this problem, I've tried to view the python-c project, and ask google for help, but doesn't work.

can anyone help me?
 
S

Steven D'Aprano

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top