Is there an equilivent to Linq.Expressions.Expression in python?
I would like to be able to get the expression out of a lambda function much like C# does and parse it into something else?
Example in C#:void Foo<T>(Expressi开发者_开发百科on<Func<T, bool>> expression
{
// ...
}
Foo<Baz>(someObj => someObj.HasBar);
The lambda operator will be traslated to an expression that could be inspected.
What's the equilivent in python?Python provides full access to the compiled form of code.
>>> f = lambda(x): 2*x
>>> f.func_code.co_code
'd\x00\x00|\x00\x00\x14S'
>>>
You can, in principle, reverse engineer this to figure out the expression, though it's no mean feat to do so. The dis module might give you a bit of a head-start:
>>> import dis
>>> dis.dis(f)
1 0 LOAD_CONST 0 (2)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 RETURN_VALUE
>>> dis.opname[ord(f.func_code.co_code[-2])]
'BINARY_MULTIPLY'
>>> dis.opname[ord(f.func_code.co_code[-1])]
'RETURN_VALUE'
>>>
精彩评论