In Python one can use setattr
to add a new attribute to an object like the following code
class Foobar:
def __init__(self):
pass
foobar = Foobar()
setattr(foobar, 'foo', 123)
print(foobar.foo)
output
123
I know in Julia there is setfield!
but it doesn't allow to add a new field like setattr
in Python.
so my question is there is a way to add a new field to an object of a composite type?
is there is way to add a new field to an object of a composite type?
No. Julia is intentionally designed without this kind of local dynamic behavior. If you need to dynamically add and remove fields then you're really using the object as a dictionary with different syntax. In Julia, you would use an actual dictionary – Dict
or other associative collection – for that kind of usage. This has no worse performance than an object in a language like Python, although it will have worse performance than a statically defined type in Julia, but that is the inherent cost of objects with dynamic fields – which is precisely why objects don't work that way in Julia.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With