On 04/08/2023 15.34, Jason Friedman via Python-list wrote:
import inspect

def my_example(arg1, arg2):
print(inspect.stack()[0][3])
my_frame = inspect.currentframe()
args,_,_,values = inspect.getargvalues(my_frame)
args_rendered = [f"{x}: {values[x]}" for x in args]
print(args_rendered)

my_example("a", 1)


The above "works" in the sense it prints what I want, namely the method
name (my_example) and the arguments it was called with.

The above didn't 'work' - please copy-paste and ensure that the email-client is respecting indentation.


My question is: let's say I wanted to add a type hint for my_frame.

my_frame: some_class_name = inspect.currentframe()

What would I put for some_class_name?
"frame" (without quotations) is not recognized,
Nor is inspect.frame.

We know Python code is executed in an execution frame. (https://docs.python.org/3/reference/executionmodel.html?highlight=frame)

We are told "Frame objects Frame objects represent execution frames." (https://docs.python.org/3/reference/datamodel.html?highlight=frame). The word "represent" conflicts with the idea of "are".

'Under the hood' inspect calls sys._current_frames() (https://docs.python.org/3/library/sys.html?highlight=frame). That code is:

def _getframe(*args, **kwargs): # real signature unknown
    """
    Return a frame object from the call stack.

    If optional integer depth is given, return the frame object that many
    calls below the top of the stack.  If that is deeper than the call
    stack, ValueError is raised.  The default for depth is zero, returning
    the frame at the top of the call stack.

    This function should be used for internal and specialized purposes
    only.
    """
    pass

Which rather suggests that if the sys library doesn't know the signature, then neither typing nor we mere-mortals are going to do so, either.


Theory: the concept of a frame does not really exist at the Python-level (remember "represents"). Frames (must) exist at the C-level (https://docs.python.org/3/c-api/frame.html?highlight=frame#c.PyFrameObject) of the virtual-machine - where typing is not a 'thing'.


It's an interesting question. Perhaps a better mind than mine can give a better answer?
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to