How to get wrapped func.__code__.co_filename with decorator?

  python-3.x, python-decorators

I want to get the wrapped func source file location correctly.
Can anyone help?

The folder structure look like this, and all the functions in test.py have keyword decorator on it.

    lib
     |--- keyword.py
    main
     |--- test.py

Keyword.py

    from functools import wraps
    def keyword(name=None, tags=(), types=()):

        def _method_wrapper(func):

            @wraps(func)
            def _passargs(self, *args, **kwargs):  
                .. some codes ..
                return func(self, *args, **kwargs)
                
            return pass_argument

        return _method_wrapper 

However, the function’s __code__ attribute had been overwritten by the decorator, and I failed to get the correct source file location.

func.__code__.co_filename = '..libkeyword.py'

The expectation

func.__code__.co_filename = '..maintest.py'

Python version = 3.8.10

Source: Python-3x Questions

LEAVE A COMMENT