Order of initialization of attributes is confusing - python-attrs

I've been using attrs the following way:
#attr.mutable
class Foo:
x: int = attr.ib(validator=attr.validators.instance_of(int))
#attr.mutable
class Bar:
x: int = attr.ib(validator=attr.validators.instance_of(int))
foo: Foo = attr.ib(
default=attr.Factory(factory=lambda self: Foo(self.x), takes_self=True),
validator=attr.validators.instance_of(Foo),
)
if __name__ == "__main__":
Bar("5")
When I ran the code, I obviously got an error.
But, the not intuitive part for me was that the validator of the Foo class raised the error.
I may be wrong but according to this I assume that validator of the x attribute of the Bar comes after Foo's.
Why is that? Would not it make more sense to validate Bar's x attribute before passing it as an argument to Foo's init method?
Thanks in advance!

When instantiating, defaults are filled before the validators run.
The __init__ method doesn't know anything about the fact that Foo has a validator and Foo doesn't know, that Bar hasn't fully instantiated itself.
From the perspective of Bar, it calls the factory with the value of x that hasn't been validated yet ("5").
From the perspective of Foo, it gets instantiated with a str and fails validation.

Related

Dart multiple upper bounds

I need to implement a solution using generics that implements 3 interfaces, but as far as I can tell, generics in dart only supports 1 upper bound?
I have a model that looks like this:
abstract class Category implements Built<Category, CategoryBuilder>, Identifiable, Mapable {
...
}
The contents of the 3 interfaces is not really relevant, and what I'm trying to do, is construct a class that can process this in generic form.
What I want is something like this:
abstract class BaseDB<T extends Built<T, R> & Identifiable & Mapable, R extends Builder<T, R>> {
process(T entity) {
print(entity.id); // From Identifiable
entity.toMap(); // From Mapable
// ... etc
}
}
I know this is possible in both Typescript and Java, but I'm fairly new at Dart. Anyone know?
This is not possible in Dart. You can only put one bound on a type variable.
The bound of a Dart type variable is used to check which operations you can do on an object of the type parameter type. Example:
String something<T extends num>(T value) {
return value.abs().toString();
}
You are allowed to call abs() on value because we know that all instances of value are numbers, and num has an abs method.
If you can write <T extends Foo & Bar>, then there is no simple type in the Dart type system that can describe objects of type T. Dart does not have intersection types (the intersection type Foo & Bar would be a supertype of all types that are subtypes of both Foo and Bar, and a subtype of both Foo and Bar).
If Foo declares Baz method(), Bar declares Qux method(), and value has type T, what is the type of value.method()?
(It would either be disallowed, or the type would be Baz & Qux). This shows that allowing & in type variable bounds leaks intersection types into the remaining type system, and since Dart does not have intersection types, it also does not have multiple bounds on type variables.
When you declare a class, FooBar, implementing both Foo and Bar, you have the same issue: You need to figure out what method returns. However, the language requires you to write that solution into your class, to find some valid return type for FooBar.method, because otherwise the FooBar class declaration is not valid. It requires a user to find a solution to "find a subclass of both Baz and Qux".

vala: convenient way of getting properties

I know that one can set a property of a GLib.Object-based class by name using the following simple syntax
obj["foo"] = bar;
Is there a way to get the property's value in the similar way? The following construction doesn't seem to work:
Bar bar = obj["foo"];
Vala returns error: invocation of void method not allowed as expression
I know it can be done as in the example below, but I'm looking for something conciser.
Bar bar;
obj.get("foo", out bar);
Bar bar = obj.foo;
You should use similar code to set properties, too, instead of what you wrote above:
obj.foo = bar;
It's not usually a big deal, but that form tends to be a bit more efficient than going through GObject properties. And it's shorter. IMHO it looks better, too.

Get type of variable at run-time without having it assigned to an instance of an object and without mirrors

Is it possible to get the type of a variable in Dart at run-time, without having it assigned to an instance of an object and without using mirrors?
I know I can do this without mirrors (which is great!):
Foo foo;
foo = new Foo();
var fooType = foo.runTimeType; // This will give me a type of "Foo"
But I want to know the type of the variable before it is assigned to an object:
Foo foo;
var fooType = foo.runTimeType; // This will not give me a type of "Foo"
I am guessing it is not possible since the typing info is lost in run-time but would like to have it confirmed.
(My actual scenario is that I am doing dependency injection into a Polymer Element using Custom Events. I would like to put as much of this code as possible in an element base-class and have as little code as possible in each derived element class. One thing that I need to do this is to know the type of variables that are to be injected).

Groovy Closures and Params

In groovy you got closure which I kinda get, (similar to js, and ruby blocks) but I came across this code and I would like some clarification.
def bar = {
-1
}
..
..
.
getResults foo, bar , params, Foo.class.simpleName
Which get getResults is a method that takes a closure bar as a parameter. What I don't get is that in the method it has this:
public int getResults ( foo, bar , params, classSimpleName) {
def totalCount = bar(params)
..
..
.
Now bar(params) returns -1 which is the value of it. But I dont get how it works.
is params a predefined word?
I am working in Grails and I know that my params passed to to controller, have no bar variable in them, and I dont know how they are related to this.
bar is a closure. You are invoking the closure with params parameter. bar closure does not care about any parameters. It always returns -1. That's it.
params is a predefined variable in grails controllers.

overriding as_json for as_json(:includes => :association)

I have two classes, Foo and Bar. Foo has_many Bars. Bar is actually the superclass of several classes that are sharing a STI table.
I want to make a dump of my Foo records including their associated Bars. To do this I call
Foo.all.to_json(:incude => :bars)
The initial problem is that I want to be able to distinguish between the different kinds of Bar classes. Rails makes this distinction via the type column in the Bar table, but that column isn't included in the json serialization of the Ber records.
So, I overrode to_json in the Bar class to include the type attribute. when I call to_json on an instance of Bar, I get the new results, but when I call to_json on Foo and include its Bars, I get the old to_json (i.e. without the type attribute included).
I've since given up on this and am going with a different approach, but I'm still curious about what's going on here. Maybe I should be using as_json instead of to_json? I still don't understand the different between those two methods.
I can't replicate this. It behaves properly in my test class.
Let's call class #1 Foo and Foo is included as an argument to Bar. In the Bar.to_json(foo), add this:
foo.class.ancestors.each do |c|
has_json = c.instance_methods.include?(:to_json)
p "#{c} has to_json: #{has_json}"
if has_json
p "Owner: #{c.instance_method(:to_json).owner}"
end
end
It might shed some light on the call hierarchy and also whether your instance variable is getting to_json from the right class.

Resources