Marty Marty - 11 months ago 28
Python Question

How do I optimize this code to be more pythonic?

This is a code snippet I wrote, which I consider is not Pythonic basically because of the if condition ladder.

This snippet is of a custom class that is used for backend processing,

def _get_item(self, **kwargs):
""" returns an object if object exists else None"""
return self.model.objects.get_object_or_none(**kwargs)

def get_object(self, info=None):
""" gets an object with given info """
if info:
name = self._info.get('name', '')
slug = self._info.get('slug', '')
if slug:
obj = self._get_item(slug=slug)
elif name:
obj = self._get_item(name=name)
obj = self._get_item(name=name, slug=slug)
if obj:
return obj

here I need to optimize
method. the
validates the given
which basically checks and stores the required values in
which is a dictionary, later retrieved with

How do I make this code Pythonic and less mess?


Assuming that self._info only contains name and slug data, you could write something like:

def get_object(self, info=None):
    return self._get_item(**self._info)

To explain a bit more:

if obj:
    return obj
# end of function

is equivalent to:

if obj:
    return obj
    return None

And that is the same as just doing return obj with no if test (assuming obj is only falsy if it's None).