Skip to content

Make GCP Objects Hashable for Reference (Ex. Compute Instance, Compute Project, Secrets Secret) #13045

Open
@WebbinRoot

Description

@WebbinRoot

Determine this is the right repository

  • I determined this is the correct repository in which to report this feature request.

Summary of the feature request

Wasn't seeing anything in current issues, but would it be possible to start converting existing Objects to hashable types where it make sense (output only unique IDs)? . For example, trying to use the Compute Project object (https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.Project) as a key in a dictionary returns

    project_metadata[compute_project_get] = []
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'Project'

But, per the project object definition above, there is a field called "_id" that is unique and otuput only that could be used as a hash.To fix the problem I just made a wrapper class with the following:

class HashableProject:
    def __init__(self, project):
        self._project = project

    def __hash__(self):
        # Hash based on the name or any other combination of unique attributes
        return hash(self._project.id)

    def __eq__(self, other):
        # Compare based on the name or any other combination of unique attributes
        return isinstance(other, HashableProject) and self._project.id == other._project.id

    def __getattr__(self, attr):
        # Delegate attribute access to the original secret object
        return getattr(self._project, attr)

    def __repr__(self):
        # Optional: Make it easier to read the wrapped object
        return f"HashableProject({self._project.id})"

Same for the "instance" object for general compute with the _id field: https://cloud.google.com/python/docs/reference/compute/latest/google.cloud.compute_v1.types.Instance

Or the "name" field for Secrets objects:https://cloud.google.com/python/docs/reference/secretmanager/latest/google.cloud.secretmanager_v1.types.Secret

The ask is basically to make objects hashable based off output-only unique IDs if those are present in the object themselves.

Desired code experience

# Successfully executes as "Project object" is hashable
> project_metadata[compute_project_get] = []

Expected results

e.g. my_new_feature() should return FOO

API client name and version

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: p2Moderately-important priority. Fix may not be included in next release.type: feature request‘Nice-to-have’ improvement, new feature or different behavior or design.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions