简体   繁体   中英

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

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'

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.

/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.

I agree with Thomas K. Essentially, the author wants a fall back when someone doesn't define a translation for doc, if they did, N_ from builtin dict is overridden by the one which does the translation. and if the translator has skipped something for translation, there is N_ function in the builtin, which is fallback which is imported, since builtin is the last scope to be checked for a function or var, the N_ will be found there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM