Background: I'm using this guide; Pony Orm. It tells me to create an object (db = Database()), then create a class that inherits from db (class Person(db.Entity)....). As far as I can tell, Person is inheriting from an instance - I didn't even know that was possible. If it is possible, I don't know how to put the Person class in another file, since all entities would need the same db object, but I don't instantiate the db object until runtime (yet I'm creating them at design time). I feel like I'm missing something fundamental here.
db = Database()
class Person(db.Entity):
name = Required(str)
age = Required(int)
cars = Set('Car')
Questions: (1st) In the example given, is Person really inheriting from an instance(db) or is something else going on? (2nd) How would I put the Person (and other classes) in its own file and share the db instance?
Note: I'm running Python 3.4.
[EDITs]
print(type(db.Entity)) # yields: <class 'pony.orm.core.EntityMeta'>
Of course it's not possible to inherit from an instance. db
may be an instance of Database
, but db.Entity
(which you're inheriting from) is very much a class. If you take a look at the source code you can see that it's a dynamically created class:
self.Entity = type.__new__(EntityMeta, 'Entity', (Entity,), {})
If you don't instantiate the db
variable until runtime, this is tricky. You have to choose: either instantiate db
at program startup and define your Person
class as usual, or postpone the class definition until the db
instance is created. Generally speaking it's never a good idea to create classes during runtime, so I would recommend instantiating db
right away.
Splitting this into multiple files however is easy. In file A.py you instantiate the db
:
db = Database()
And in B.py you simply import A:
from A import db
class Person(db.Entity):