0

What is the most pythonic way to repeat an expression in Python.

Context : A function is getting passed a dictionary (with possibly 20 elements) and I need to extract and use values from this dictionary if they exist. Something like this :

x = dict_name['key1'] if dict_name['key1'] else ''

Now, instead of writing this logic 20 times for all 20 different keys, I would like to define this expression at one place and then use it repeatedly. It will be easier to maintain in future. In "C/C++" programming languages, it makes a good case of #define or inline functions. What would be Pythonic way to do this in Python?

As you would have guessed, I am novice in Python. So I appreciate your help on this or pointers to constructs for this in Python.

ayhan
  • 70,170
  • 20
  • 182
  • 203
ViFI
  • 971
  • 1
  • 11
  • 27
  • should this be a use case for lambda function ? – ViFI Sep 01 '16 at 07:16
  • 2
    get_val = lambda key: dict_name.get(key, '') – sisanared Sep 01 '16 at 07:16
  • 1
    That's what functions are for. – BrenBarn Sep 01 '16 at 07:21
  • @shravster If you are going to assign a lambda function to a name you might as well use `def` instead. – juanpa.arrivillaga Sep 01 '16 at 07:24
  • Why would `dict_name.get('key1', '')` not suffice? – juanpa.arrivillaga Sep 01 '16 at 07:27
  • @BrenBarn : Yes , perhaps lambda function, if there are really a function. – ViFI Sep 01 '16 at 07:28
  • @juanpa.arrivillaga : I would have to repeat that expression 20 times and now imagine if dict_name or default value has to change tomorrow for some reason. I will have to do that change at 20 places. Which can be avoided by using lambda functions as that will require change only at one place. – ViFI Sep 01 '16 at 07:31
  • @ViFI Sure, but no need for a lambda function. Just a normal function definition would work and is the standard approach. Lambda is exclusively a convenience for anonymous functions, say passing a quick, simple function as a parameter to another function. So something like `def extract(): dict_name.get('k1','')` would be the most Pythonic approach. – juanpa.arrivillaga Sep 01 '16 at 07:32

1 Answers1

0

Whether there is an "equivalent" to inline in Python depends on who you ask, and what you check.

For no equivalent, e.g.: https://stackoverflow.com/a/6442497/2707864

For equivalent, e.g.: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch07s06.html

From a practical point of view, lambda would do the trick (dict.get replaces your ternary conditional operator)

dict_get = lambda key : dict_name.get(key, '')

Or you can always define a one-line function.

def dict_get( key ) : dict_name.get( key, '' )

Pythonicity is quite often (always?) subjective.

Community
  • 1
  • 1
  • In the sense that assigning a lambda function to a name goes against [PEP8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) it is not Pythonic. – juanpa.arrivillaga Sep 01 '16 at 07:53