Skip to content

Make inspect.Parameter.__hash__ use _default instead of default #102302

Closed
@Gouvernathor

Description

@Gouvernathor

Feature or enhancement

Enable subclasses of Parameter to add a default property accessing hash(self) rather than having hash rely on the default property

Pitch

I wanted to make a subclass of Parameter which would store as _default the string eval-ing to the actual default value, and which would only eval it when accessed, and memorize it at that time.
So, I coded this :

class Parameter(inspect.Parameter):
    __slots__ = ()
    @property
    @functools.cache
    def default(self):
        return renpy.python.py_eval(super(Parameter, self).default)

(not using @cached_property because I want to keep the empty slots)
This doesn't work, because cache tries to hash self, and Parameter.__hash__ accesses self.default, rather than self._default (so it does an infinite recursion loop).

The last edit to the hash method was purportedly to "fix a discrepancy between eq and hash". However, the eq still accesses the raw _default, and hash did so too before the "fix".
Overall, apart from my selfish use-case, I think it makes more sense for an immutable class to hash relative to the actual value instead of the less-reliable propertied value.
And there's a minor performance bonus too.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions