1

Just a question out of interest in Python. How to get a function out of it storage slot? Here I have an example:

>>> def func():
    pass

>>> func
<function func at 0x00000280B1883288>

So then 0x00000280B1883288 is the place where it is stored in the RAM memory, right? But if I do this:

>>> eval('0x00000280B1883288')
2751757562504
>>> func
<function func at 0x00000280B1883288>
>>> 0x00000280B1883288
2751757562504

I only get an int back and if I try to call it I get the error that an int is not calleble. But is it possible to get a function out of its ram slot without calling func?

This is a question out of interest about how Python works, not that I don't know how to call a function, to make that clear.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Matthijs990
  • 637
  • 3
  • 26
  • No. Memory locations can not be accessed like that. – rdas Oct 11 '19 at 07:48
  • 1
    WIth cPython you may be able to use the `di()` function in my answer to the question [Is it possible to dereference variable id's?](https://stackoverflow.com/questions/15011674/is-it-possible-to-dereference-variable-ids) — I don't know if it would work for functions. – martineau Oct 11 '19 at 07:51

1 Answers1

1

This is CPython-specific, but it is possible to use _ctypes for this:

import _ctypes

def di(obj_id):
    """ Inverse of id() function. """
    return _ctypes.PyObj_FromPtr(obj_id)

def func():
    return 42

func_id = id(func)
print(func)
print(hex(func_id))
print(di(func_id)())

This is adapted from Is it possible to dereference variable id's?

P.S. I also briefly experimented with _ctypes.call_function() but didn't get very far.

NPE
  • 486,780
  • 108
  • 951
  • 1,012