How to find file where function is defined from Python command line

3.1k Views Asked by At

Let's say I want to explore import statements in Python. How, from the Python command line, can I find the file in which import is defined? Note I am working in Python 2.7.6 (iPython) in Windows 7.

For most objects, just entering the object name is enough. For instance:

import os
os

Yields the following:

<module 'os' from 'C:\Anaconda\lib\os.pyc'>

But you cannot do the same with basic commands like import.

I have tried searching my Python folder but unsurprisingly don't get something as simple as C:\Anaconda\lib\import.py. Is there a simple way to find out where such statements are defined (I realize much of the time it will be in c-code, but that is what I am after)?

Update (5/27/14)

It seems people think it cannot be done in any simple way with a built-in command. However, if your life depended on it, you could write up some inelegant grep-type function in Python, no?

2

There are 2 best solutions below

5
On

import isn't a module the way that os is. Instead, it's a statement.

https://docs.python.org/2/reference/simple_stmts.html#import

1
On

When you call os after importing, it prints the path to the file because it is a module. Instead, import is a statement:

>>> import math
>>> math
<module 'math' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/math.so'>
>>> import
  File "<stdin>", line 1
    import
         ^
SyntaxError: invalid syntax
>>> 

Just in case you feel like you needed to know, here are the other statements that do similar things when called blank:

>>> with
  File "<stdin>", line 1
    with
       ^
SyntaxError: invalid syntax
>>> yield
  File "<stdin>", line 1
SyntaxError: 'yield' outside function
>>> return
  File "<stdin>", line 1
SyntaxError: 'return' outside function
>>> continue
  File "<stdin>", line 1
SyntaxError: 'continue' not properly in loop
>>> import
  File "<stdin>", line 1
    import
         ^
SyntaxError: invalid syntax
>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
>>> assert
  File "<stdin>", line 1
    assert
         ^
SyntaxError: invalid syntax
>>> del
  File "<stdin>", line 1
    del
      ^
SyntaxError: invalid syntax
>>> break
  File "<stdin>", line 1
SyntaxError: 'break' outside loop
>>>