Polymorphism using MapperExtension can lead to multiple instances backed by the same data

Issue #167 resolved
Former user created an issue

(I've also posted an e-mail about this to the mailing list).

Because the code in _instance() in mapper.py creates the identity_key value using "self", if you're using a polymorphic mapper (as in examples/polymorph/polymorph.py, for instance), you can create multiple instances of an object backed by the same data. For instance, in polymorph.py or polymorph2.py, you can easily create more than one instance of Engineer() for the same person_id.

This happens because initially the class part of the identity_key will be set to e.g. polymorph.Person rather than polymorph.Engineer. The identity map will always contain a correct identity_key, although the instance recorded in there for the key will be the most recently created instance only.

There are a few possible solutions:

  1. Add another method to MapperExtension to allow an extension to change the mapper used to generate the identity key.
  2. Add a method to MapperExtension specifically for polymorphism, and push the necessary shenanigans down into the Mapper class itself.
  3. Change Mapper so that it has support for polymorphism, for instance with syntax like:

    mapper(Person, person_join, type_selector=person_join.c.type, type_map={ 'engineer': Engineer, 'manager': Manager })

Since I want this functionality to work, I'm happy to do the code and submit a patch. But I need to know which is the preferred solution.

Comments (1)

  1. Mike Bayer repo owner

    this functionality has been implemented in the 0.2 branch (i.e. built in support for polymorphism in the mapper)

  2. Log in to comment