Is this possible in nim?
An example of what I mean:
type
test* = object
var t = test()
var t.name = "kek" #This would fail to compile
Afaik it is not. You could use a JSON Object for example or a Table and use "experimental" pragma for dot overloading (in devel) or better using your own operator like .? (which was already be planned to be as being part of the compiler to allow: foo.?bar being equal to foo[bar] afair :)
Similar to this:
template `.?`*[T](a: T, f: untyped): untyped = a[astToStr(f)]
So soemthing like Python's setattr() doesn't exist then?
I think when you want support for dynamic runtime attributes, you have to prepare for it in a compiled language. For example you can add a field of type seq or table to your object and a proc for adding data to this field. Of course in a typed language like Nim adding arbitrary data types like ints, strings, objects may not work. If that is necessary you may wrap your attributes in objects, maybe in variant types?
This is not possible by design.
type
test* = object
Here, you declare an object that has no fields.
var t = test()
Here, you instantiate this object. t has the type test.
var t.name = "kek"
The compiler now looks at t's type and sees that this type has no field name, and thus quits with an error at compile time. If you want to allow that, that means that every construct t.someFieldName would not be allowed to fail at compile time (because that field may be added dynamically). So the compiler can no longer guarantee that the field you try to access exists. That's the difference between static and dynamic typing systems.
The question is: Why do you think you need it?
@flyx I guess it's not NEEDED because I can just store it in a table but after using Python year after year it just seems like something natural.
The "solution" based on posts above is:
import tables
template `.?`*[T](a: T, f: untyped): untyped =
a[astToStr(f)]
var Thing = initTable[string, string]()
Thing.add("name", "value")
echo Thing.?name
Ok, I get the problem here. At first I thought you would need an interface object to interact with languages like Python, where you do not know the fields. But you what you actually want is to treat Nim like as if it is Python, and all I can tell you that is a bad idea, and don't do that. You should just get used to static types and when you need a field in an object, just add it to the type:
type
test* = object
name : string
var t = test()
t.name = "kek" #This now works pretty fine