Home > other >  Python hinting: is it possible that using typing.cast will cause to lose data
Python hinting: is it possible that using typing.cast will cause to lose data

Time:07-14

I observed a very strange behavior when using typing.cast method on dataclasses.

I created these dataclasses:

@dataclass(eq=False)
class NodeData:
    ...

@dataclass(eq=False)
class InventoryNodeData(NodeData):
    uid: str = None

@dataclass(eq=False)
class VmNodeData(InventoryNodeData)
   ...

I have a node which is an instance of InventoryNodeData, with a 'uid' member:

node.uid
Out[25]: 'vm_1'
type(node)
Out[26]: VmNodeData
node.asset_unique_id
Out[25]: 'vm_1'

So far so good. However, once I invoke cast function on this object, this member disappears.

str(cast(node, InventoryNodeData).asset_unique_id)
Out[28]: 'None' 

How does it make sense???

CodePudding user response:

cast signature is cast(typ, val). Easy fix:

str(cast(InventoryNodeData, node).asset_unique_id)
  • Related