user2682863
user2682863

Reputation: 3218

Retrieve func_code from builtin_function_or_method

Is it possible to retrieve the func_code object from a builtin_function_or_method? ie from time.time()

import time
dir(time.time)

doesn't contain the function object

nor does

dir(time.time.__call__)

that just returns itself

time.time.__call__.__call__.__call__

..and so on.

Any ideas?

Upvotes: 5

Views: 5468

Answers (2)

nneonneo
nneonneo

Reputation: 179552

In CPython, built-in methods are implemented in C (or some other language, e.g. C++), so it is not possible to get a func_code (that attribute exists only for functions defined using Python).

You can find the source code of time.time here: http://hg.python.org/cpython/file/v2.7.5/Modules/timemodule.c#l126

Other Python implementations may make func_code available on built-in functions. For example, on PyPy:

$ pypy
Python 2.7.1 (7773f8fc4223, Nov 18 2011, 22:15:49)
[PyPy 1.7.0 with GCC 4.0.1] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>> import time
>>>> time.time
<built-in function time>
>>>> time.time.func_code
<builtin-code object at 0x00000001017422e0>
>>>> time.time.func_code.co_consts
('time() -> floating point number\n\n    Return the current time in seconds since the Epoch.\n    Fractions of a second may be present if the system clock provides them.',)

Upvotes: 2

ali_m
ali_m

Reputation: 74232

Pretty sure you can't. From the docs:

Built-in functions

A built-in function object is a wrapper around a C function. Examples of built-in functions are len() and math.sin() (math is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: __doc__ is the function’s documentation string, or None if unavailable; __name__ is the function’s name; __self__ is set to None (but see the next item); __module__ is the name of the module the function was defined in or None if unavailable.

These are compiled C code - there's no representation of the function body in Python code.

Upvotes: 1

Related Questions