Search code examples
sqlalchemy

Check if object is an sqlalchemy model instance


I want to know how to know, given an object, if it is an instance of an sqlalchemy mapped model.

Normally, I would use isinstance(obj, DeclarativeBase). However, in this scenario, I do not have the DeclarativeBase class used available (since it is in a dependency project).

I would like to know what is the best practice in this case.

class Person(DeclarativeBase):
      __tablename__ = "Persons"

p = Person()

print isinstance(p, DeclarativeBase)
#prints True

#However in my scenario, I do not have the DeclarativeBase available
#since the DeclarativeBase will be constructed in the depending web app
#while my code will act as a library that will be imported into the web app
#what are my alternatives?

Solution

  • You can use class_mapper() and catch the exception.
    Or you could use _is_mapped_class, but ideally you should not as it is not a public method.

    from sqlalchemy.orm.util import class_mapper
    def _is_sa_mapped(cls):
        try:
            class_mapper(cls)
            return True
        except:
            return False
    print _is_sa_mapped(MyClass)
        
    # @note: use this at your own risk as might be removed/renamed in the future
    from sqlalchemy.orm.util import _is_mapped_class
    print bool(_is_mapped_class(MyClass))