On Jul 14, 2019, at 13:13, Serhiy Storchaka <[email protected]> wrote:
>
>
> The more interesting problem is that in general case you have not simple
> `price < 1`, but `price < x` where x is a variable or more complex expression.
I don’t think this one is a problem. (I mean, it does demonstrate the problem I
was talking about, that price<1 is a useful, refactorable, etc. value but
`price<1` is not, but you don’t need x for that.) I think this is exactly the
kind of case the OP was referring to with “eval in a modified environment”, and
it works fine.
> price should be evaluated at the callee context
It’s actually not even the callee context, but a custom one, maybe something
like self.columns. But that isn’t a problem.
> while x should be evaluated at the caller context. And how Python can know
> what is what?
I think the benefit of this proposal is that Python doesn’t _need_ to know what
is what; that’s up to the person implementing pandas.DataFrame.__getitem__, and
it should be not just possible but easy to implement that as desired.
As far as Python is concerned, `price < x` just gets compiled to an AST and the
caller context gets bound to that AST. The callee code then gets to decide how
to eval it. The OP didn’t explain exactly how this would be done, but it seems
like it should be easy:
def __ getitem__(self, key):
if isinstance(key, BoundExpression):
localcontext = ChainMap(self.columns, key.locals)
key = eval(key, localcontext, key.globals)
# … existing __getitem__ code from here on
Since price is in columns and x is in key.locals, they’re both in localcontext,
and everything works.
And if you (the author of pandas) want locals to take precedence over columns,
or want to flag it as an error to use something that’s ambiguous like that, or…
any more complicated thing I can come up with, they’re all just as easy to
write.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/HKKTUNF2OROIQC6I3EW6FDDA2FEZACPM/
Code of Conduct: http://python.org/psf/codeofconduct/