Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new field to Julia type?

Tags:

julia

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?

like image 498
Mohamed Elsayed Avatar asked Mar 13 '17 21:03

Mohamed Elsayed


1 Answers

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.

like image 199
Isaiah Norton Avatar answered Nov 12 '22 19:11

Isaiah Norton