How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?

Viewed 70173

I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often:

my_object = session.query(SomeObject).filter(some_fiter).first()
if my_object: # Mostly in databases...
    # Juchee it exists
    # process
else:
    # It does not exist. :-(
    my_object = SomeObject()
    # process

What I am dreaming of would be something like:

if my_object = session.query(someObject).blabla.first():
    # if my_object is None this scope is left alone
    # if my_object is not None I can work with my_object here...

I know, that this syntax is wrong, but I wanted to explain, what I mean by this example. Any equivalent way would make me happy.

Is there an elegant python approach for this pattern? This question aims not only at SQLAlchemy, but to each equivalent scenario.

closing my eyes hitting "Post your question" and waiting for the smart people and pythonistas by heart to hunt me down for asking something mayhaps inappropriate ;-)

9 Answers

Here is the function to check the existence of an object using SQLalchemy.

def exists(obj, **kwargs):
    """" if obj filtered by kwargs exist return it otherwise return None
        obj : is the sql alchemy model object which existence is being checked here.
        **kwargs : (username = user_name, email=user_email)
    """
    db_obj = obj.query.filter_by(**kwargs).first()
    if db_obj is not None:
        return True
    else:
        return False
Related