Marty Marty - 7 months ago 10
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:
self._validate_info(info=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)
else:
obj = self._get_item(name=name, slug=slug)
if obj:
return obj


here I need to optimize
get_object()
method. the
._validate_info()
validates the given
info
which basically checks and stores the required values in
self._info
which is a dictionary, later retrieved with
.get()
method.

How do I make this code Pythonic and less mess?

Answer

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

def get_object(self, info=None):
    self._validate_info(info)
    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
else:
    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).

Comments