Python, With ... as ... AST/Symbol access
Disclaimer: Sensible semantics do dictate that the LHS of as behaving differently depending on the RHS lexeme is ludicrous. But I am curious nont开发者_如何转开发heless.
Hi guys,
Simple question, but one that somone may be able to answer better than my hack. I'm currently messing with metaclasses etc and working out a comfortable syntax for some things.
Given the Python with ... as ...:
statement, can I access in the context manager what name(s) are given on the right of as
:
with foo('fido') as Dog:
...
Can foo.__enter__()
find out the lexeme where Dog
is?
Super bonus credit: Keep it implementation agnostic, supporting Python 3.x too.
No, just like (say) in Dog = foo('fido')
there is no "serious" way in which foo
can know its result is about to be bound to name Dog
in the caller. (By "serious" I'm excluding rummaging in the stack to find out the calling bytecode and disassembling it, &c -- basically the stuff that you know you'd never do if you knew your code was going to be maintained by a well-muscled maintainer who knows where you live;-).
精彩评论