I think the following should work: class MyObject: def __classcall__(cls, arg): if isinstance(arg, special): return typecall(MyObject_specific_case, arg) else: return typecall(MyObject, arg)
plus the same __init__ you had before. I haven't checked it though.... David On Fri, May 13, 2022 at 11:38 AM Antoine Leudière < antoine.leudi...@gmail.com> wrote: > Hi, > > I have a class `MyObject` and a class `MyObject_specific_case` that > inherits `MyObject`: > > ``` > class MyObject: > def __init__(self, arg): > # Do stuff > > class MyObject_specific_case: > def __init__(self, arg): > # Do stuff > super().__init__(arg) > ``` > > It is easy to decide if the object is a 'specific case' by looking at `arg`. > Therefore, I would like some sort of mechanism that autonomously decides to > instantiate `MyObject` or `MyObject_specific_case` depending on the value > of `arg`. The ideal interface would be: > > ``` > sage: my_object = MyObject(gen) > sage: # Assume arg corresponds to the specific case: > sage: isinstance(my_object, MyObject_specific_case) > True > sage: isinstance(my_object, MyObject) > True > sage: # Assume arg does not correspond to the specific case: > sage: isinstance(my_object, MyObject_specific_case) > False > sage: isinstance(my_object, MyObject) > True > ``` > > My question is: what is the idiomatic way to do this? > > Naively, one could use a function that takes `arg` as argument, but we > would want both the function and the class to be named `MyObject`, so > there is a collision. From what I understand, Sage typically uses a class > along the lines of `UniqueRepresentation` or `UniqueFactory`. However, > those seem to do way more than what I ask ( > https://doc.sagemath.org/html/en/reference/structure/sage/structure/unique_representation.html, > > https://doc.sagemath.org/html/en/reference/structure/sage/structure/factory.html), > and I am a bit lost. > > P.-S. : In real life, `MyObject` is `FiniteDrinfeldModule` and ` > MyObject_specific_case` is `FiniteDrinfeldModule_rank_two` (see > https://trac.sagemath.org/ticket/33713). > > -- > You received this message because you are subscribed to the Google Groups > "sage-devel" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sage-devel+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sage-devel/92c5b512-f235-474b-ab18-6f4e26dacbf9n%40googlegroups.com > <https://groups.google.com/d/msgid/sage-devel/92c5b512-f235-474b-ab18-6f4e26dacbf9n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "sage-devel" group. To unsubscribe from this group and stop receiving emails from it, send an email to sage-devel+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sage-devel/CAChs6_kdkdHDMj0EZ-mKwLVi42%2ByRv_Ns7u%3Dbh0Ghw3X3vFK7A%40mail.gmail.com.