Hello everyone I hope you are doing well , I am tr...
# python
a
Hello everyone I hope you are doing well , I am trying to write some helper functions to use in my pulumi kubernetes repo, I came across this problem sometimes we define resources as pulumi objects and sometimes we define them as python dictionaries, and both work well, but now I am trying to use these resources (arg specifically), by other functions: so I am doing this
Copy code
def get_attribute_or_key(obj, key):
    "obj.key"
    if isinstance(obj, dict):
        return obj[key]

    return getattr(obj, key)

def get_nested_value(obj, key_list):
    "obj.key1.key2..."

    sub_obj = obj
    for key in key_list:
        sub_obj = get_attribute_or_key(sub_obj, key)

    return sub_obj

# for usage 
get_atrribute_or_key(configmap, "metadata")
get_nested_value(configmap, ["metadata", "name"])
..
as far as I checked pulumi objects don't have the get method so I can't just do:
Copy code
configmap.get("metadata").get("name")
is there a better way to achieve this ? any tips or ideas that might help? thanks alot
d
Pulumi objects support the getitem interface too, so you can treat everything as a dict
Not in a pulumi project, but we used to use Munch to normalise dicts into objects
a
u mean like this?
Copy code
obj.__dict__[key]
for context I am creating a lib for developers in my organization to create/ manage k8s resources, so sometimes they will use a dict and sometimes pulumi_kubernetes objects (as both work in the case of k8s), the reason I don't wanna cast everything to a dictionary is because I don't want people to lose autocompletion/type hinting in their code editor (pylance/jedi), and doing everything as pulumi objects isn't really feasible in this scenario.
d
I stand corrected, I thought
obj[key]
was supported in pulumi resources, but that's only for certain input/Output objects
You could use Munch instead of dict, which provides a getattr interface for user usage, and a dict interface that pulumi should be able to work with. However I'm unsure on how well it'll handle autocompletion compared to dicts
a
hmmm, munch looks nice, but since all I wanted was to avoid using this syntax, I think it might add another layer of pain as I would have to ask people to use it, and then explain why, ...,
Copy code
get_nested_value(configmap, ["metadata", "name"])
also one thing to note is that these functions usage will mostly be hidden behind the ci/cd tools/ wrappers that only few people will have to deal with, so I'm not sure tbh