Can the Asset element “class” be renamed to something different? It’s a python keyword and problematic in my code. It gives me an error when I try to access it. Code snippet and error indicated below:
I wrote the following function to convert Asset instance into a dict:
def assettodict (asset):
# Asset is a nonserializable object that contains an innaccessible
# attribute (class). The problem is that "class" is a python
# keyword, and cannot be accessed directly (asset.class).
#
# Since it's not iterable or serializable, it cannot be directly
# type converted into a python dict, nor can it be converted
# into json directly. So, we have to jump through a few gyrations -
# hence utilizing jsonpickle as an interim step.
jsonpicklestring = jsonpickle.encode (asset)
assetpickle = json.loads(jsonpicklestring)
assetdict = assetpickle["_raw"]
return (assetdict)
Using ‘class’ for the type of an asset is a bit unfortunate. It conflicts with the python reserved word ‘class’. I get around it by using the python getattr function. Like this
As mentioned above by pkdenver, an asset (or any object) could also be turned into a python dict. That way the attributes become keys and can be fetched using bracket notation. There’s the built in python vars function just for the purpose of turning objects into dicts. Like this.
Yes, you can rename the class attribute to something else to avoid conflicts with the Python keyword. You can use the getattr() function to access attributes dynamically. Here’s how you can do it: