Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How might I give a variable custom metadata?

Other than declaring the variable as a new object, is there a way I could apply extra information to a python variable that I could later refer back to?

someVar = ... # any variable type
someVar.timeCreated = "dd/mm/yy"
# or
someVar.highestValue = someValue
# then later
if someVar.timeCreated == x:
    ...
# or 
if someVar == someVar.highestValue:
    ...

I see that this is essentially just an object, but is there a neat way I could do this without declaring an object separate to the python variable object itself?

like image 339
Regulation Headgear Avatar asked Oct 26 '25 15:10

Regulation Headgear


1 Answers

Instances of user-defined classes (classes defined in Python source code) allow you to add whatever attributes you want (unless they have __slots__). Most built-in types such as str, int, list, dict, don't. But you can subclass them and then be able to add attributes, and everything else will behave normally.

class AttributeInt(int):
    pass

x = AttributeInt(3)

x.thing = 'hello'

print(x)  # 3
print(x.thing)  # hello
print(x + 2)  # 5 (this is no longer an AttributeInt)
like image 90
Alex Hall Avatar answered Oct 28 '25 05:10

Alex Hall