[Python-ideas] exception based conditional expression, similar to if-else conditional expression

Masklinn masklinn at masklinn.net
Thu Aug 20 16:54:13 CEST 2009


On 20 Aug 2009, at 16:25 , Steven D'Aprano wrote:
>
> A better way of writing that would be:
>
> x = y.evaluate(locals()) if hasattr(y, 'evaluate') else y
>
> which have the bonus of working correctly even if y gets its  
> evaluate()
> method via inheritance.
>
> Another way, two lines instead of one:
>
> try: x = y.evaluate(locals())
> except AttributeError: x = y
>
>
> A third method: make sure all objects you pass have an evaluate()
> method, even if they are a null-operation that just return self.
>
Fourth method: x = getattr(y, 'evaluate', lambda _: y)(locals())




More information about the Python-ideas mailing list