Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python usage of lambda to define a __builtin__ - but why?

Tags:

python

I stumbled upon this python:

__builtin__.__dict__['N_'] = lambda x: x
class X:
    doc = N_('some doc for class X')

I know conceptually what this does, but what I don't know is why? More precisely, what is the difference between that code and this:

class X:
    doc = 'some doc for class X'
like image 972
qneill Avatar asked Jan 20 '23 20:01

qneill


2 Answers

Looks to me like the N_ function needs to be defined (it's probably supposed to look up translations), so he's creating it at the start of the process for anything else that happens in that process.

I'd assume that another piece of code, perhaps the code for non-English localisation, can replace the N_ function with one that looks up the appropriate translated string.

like image 143
Thomas K Avatar answered Jan 22 '23 09:01

Thomas K


/agree with Thomas. It's the same as:

def N_(x): return x
__builtin__.__dict__['N_'] = N_

Why put it in __builtin__? Perhaps other modules need to use it as well.

Looking at the link KennyTM provides, there are some lines like:

... import config ...

after that. The config could change the built-in N_ function.

like image 45
Claudiu Avatar answered Jan 22 '23 10:01

Claudiu