Domanda

I'm trying to create a module in Python that allows me to write a valid sentence like map(_ + 2, range(10)), just for fun, but there's a weird behavior I don't know how to deal with. My current implementation is:

class EasyLambda(object):
    def __add__(self, other):
        return lambda val: val + other

_ = EasyLambda()

Each operator has its own function like that. This is the dumb implementation, I'll improve it later to make things like _.lower() + '.html' possible. The problem is, everytime I call a magic method, Python seems to replace self by the new returned value, which is a lambda in this case.

>>> from mymodule import _
>>> print _
<func.EasyLambda object at 0x2e4ae90>

>>> add2 = _ + 2
>>> print add2, _
<function <lambda> at 0x2e551b8> <func.EasyLambda object at 0x2e13e90>

>>> add2(4)
6

>>> print add2, _
<function <lambda> at 0x2e551b8> 6    # WTF?

>>> print _, type(_)
6 <type 'int'>

>>> _ + 4
10

>>> _
10    # WTF??

>>> 2 + 2
4

>>> _
6    # WTF???

I have no idea what's going on here, really. How can I solve this problem and make my _ object behave as expected?

È stato utile?

Soluzione

_ is used by the interactive interpreter to store the last evaluated result. Everytime you're trying to do something, you're inadvertently having your _ over-written. Also note that _ is quite often used as a shortcut for uggettext and similar. Simplest solution is to avoid _ for now...

Thanks to thefourtheye for pointing out the relevant section from the Python documentation which states:

The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the __builtin__ module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement.

Note The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top