Asset class keyword causing error in Python

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:

asset = api.get_asset('AAPL')
asset_class = asset.class
                    ^

SyntaxError: invalid syntax

Every other element can be accessed with no problem (e.g. asset_name = asset.name).

Thanks

1 Like

A suggestion… Maybe add a new class attribute of a different name, with the duplicate data from “class”. e.g. asset_class

1 Like

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)
1 Like

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

asset = api.get_asset('AAPL')
asset_class = getattr(asset, 'class')

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.

asset = api.get_asset('AAPL')
asset_dict = vars(asset)['_raw']
asset_class = asset_dict['class']

But yes, it would have been better to name the attribute something else and not need to do these workarounds.

1 Like

What assets classes are even possible? There is no list in the documentation so why do you even what this?

2 Likes

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:

asset = api.get_asset(‘AAPL’)
asset_class = getattr(asset, ‘class’)