Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

python - Avoid or delay evaluation of things which may not be used

How can lazy evaluation be achieved in Python? A couple of simple examples:

>>> def foo(x):
...     print(x)
...     return x
... 
>>> random.choice((foo('spam'), foo('eggs')))
spam
eggs
'eggs'

Above, we didn't really need to evaluate all the items of this tuple, in order to choose one. And below, the default foo() didn't really need to be computed unless the lookup key was actually missing from the dict:

>>> d = {1: "one"}
>>> d.get(2, foo("default"))
default
'default'
>>> d.get(1, foo("default"))
default
'one'

I'm looking for a Pythonic way to refactor examples like the above to evaluate lazily.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard way of doing lazy evaluation in Python is using generators.

def foo(x):
    print x
    yield x

random.choice((foo('spam'), foo('eggs'))).next()

BTW. Python also allows generator expressions, so below line will not pre-calculate anything:

g = (10**x for x in xrange(100000000))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...