I understand this might not be a programming question, but I still wonder:

Why does Python return the memory of the function when the function handle is called for?

>>> my_func
<function my_func at 0x3ead488>

When / How is that useful? Why not display the actual contents of the function (while still holding the same functionality; a link to the function)?

有帮助吗?

解决方案

You are looking at the repr() representation of a Python object that doesn't have a literal representation. Such objects follow the default <type ... at 0xid> pattern most Python objects follow.

It's purpose is for you to be able to distinguish different function objects from one another, even if their names are the same; if you have two foo functions you'd want to be able to see if they are the same object or not; the id() value in the representation allows you to do so.

Quoting from the __repr__ method documenation:

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an “informal” string representation of instances of that class is required.

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

The contents of a function are a) potentially much larger, and b) require a source file to be available. The function object itself only references bytecode, the compiled code object. Even if the source files are available printing a container object full of functions would result in overly verbose output.

If you wanted to see the source code for a given function object, use inspect.getsource() on the object. This can raise an IOError exception if no source is available.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top