4

I'm using Flask-SQLAlchemy in python 3.6.5 and -- so far -- have not been able to extend a model with a call to __init__(). My code looks like this:

'''
file: models.py
'''
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

class Network(db.Model):
    __tablename__ = 'network'

    id = db.Column(db.Integer, primary_key=True)
    baud_rate = db.Column(db.Integer)

    def __init__(**kwargs):
        super(Network, self).__init__(**kwargs)  # see note

Attempting to instantiate a Network object results in an error:

>>> n = Network(baud_rate=300)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: __init__() takes 0 positional arguments but 1 was given

This is a bit surprising, since I'm using the recipe given in the Flask-SQLAlchemy documentation:

If you decide to override the constructor for any reason, make sure to keep accepting **kwargs and call the super constructor with those **kwargs to preserve this behavior: class Foo(db.Model): # ... def __init__(**kwargs): super(Foo, self).__init__(**kwargs) # do custom stuff

Since I'm using python 3.6, I thought maybe I should upgrade the call to super(), as in :

def __init__(**kwargs):
    super().__init__(**kwargs)

... but that didn't make any difference.

1 Answer 1

6

Sounds like the doc forgets to mention the self attribute in __init__ (A pull request was accepted in may) :

class Network(db.Model):
    __tablename__ = 'network'

    id = db.Column(db.Integer, primary_key=True)
    baud_rate = db.Column(db.Integer)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
Sign up to request clarification or add additional context in comments.

1 Comment

Yep - that did the trick. Not quite what I expected, though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.