i just wanted to try out the pony orm mapper for a small personal web application. Everything works fine except for defining a custom constructor for an entity.
In the following code i created a simple entity with a string field name
and defined a constructor which does nothing but redirect the arguments to the parent constructor (in my real app i change some of the arguments bevor passing them to the parent constructor). After that i create one User
and print its name.
from pony.orm import Database, Required, db_session, commit
db = Database("sqlite", ":memory:", create_db=True)
class User(db.Entity):
def __init__(self, *args, **kwargs):
super(User, self).__init__(*args, **kwargs)
name = Required(str)
db.generate_mapping(create_tables=True)
with db_session:
u = User(name="Admin")
commit()
print(u, u.name)
The error message is TypeError: object.__init__() takes no parameters
in the same line as the super()
call.
It looks like the keyword arguments are sent to object
instead of db.Entity
.
When i remove the constructor everything works
So why doesn't it work. Shouldn't a constructor like the one in my example just always work (and do nothing of course)? Is there something in ponyorm that prevents it from working or am i missing something here?
For completeness sake my entity definition actually looks like this
class User(db.Entity):
def __init__(self, *args, **kwargs):
if "password" not in kwargs:
raise ValueError("password is required")
kwargs["password"] = werkzeug.security.generate_password_hash(kwargs["password"])
super().__init__(*args, **kwargs)
name = Required(str)
password = Required(str)
It produces the same results.
Also in the official documentation it says that method creation in entities is allowed at least. http://doc.ponyorm.com/entities.html#adding-custom-methods-to-entities . But it doesn't say anything about constructors.
Until that moment the Entity
class did not have the __init__
method at all. For historical reasons, initialization of entity instance took place in the __new__
method. Because of this, when you call super(User, self).__init__
you actually call the object.__init__
method. While in Python 2 the object.__init__
method silently accepted any arguments, in Python 3 that method raises the error (the one that you've got) when you pass any argument to it.
After looking at your question we changed the initialization logic of entity instances and now we use __init__
method in a traditional way. If you take the last version of PonyORM from GitHub your code should work fine. This change will be part of the next release PonyORM 0.6.2.
Thanks for pointing out to this!