import inspect
from pathlib import Path


def versioned(func):
    """Automatically infer version string from calling filename.

    When the caller's filename is formatted ``'v{version}.py'``, extract
    ``{version}`` from that filename and set the ``"version"`` key in the result.

    For example, in the file ``v1.0.0.py``::

        @versioned
        def specialize():
            return {}

        data = specialize()
        assert data['version'] == '1.0.0'
    """

    # get the calling frame's filename; extract the version
    frame = inspect.stack()[1]
    file = frame[0].f_code.co_filename
    version = Path(file).stem.lstrip('v')

    def wrap(*arg, **kwarg):
        data = func(*arg, **kwarg)
        data['version'] = version
        return data

    return wrap