Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python del() built-in can't be used in assignment?

I noticed a problem when I was trying to use del in a lambda to thin out a list of threads to just those running:

map(lambda x: del(x) if not x.isAlive() else x, self.threads)

Ignore for a second that this doesn't do anything, I'm just fooling around with map, reduce, and lambda.

This fails with a syntax error at del(x). With some messing around, I think the problem is del() doesn't return a value. For example, this fails with the same error:

b = 5
x = del(b)

This doesn't, however:

def rmThis(x): del(x)

Which means I'm using this workaround:

map(lambda x: rmThis(x) if not x.isAlive() else x, self.threads)

So is the limitation just because del() doesn't return a value? Why not?

I'm using python 2.6.2

like image 473
emcee Avatar asked May 24 '10 08:05

emcee


1 Answers

The limitation is that del is a statement and not an expression. It doesn't "return a value" because statements don't return values in Python.

The lambda form only allows you to mention expressions (because there is an implicit return before the expression), while the def form allows a single statement function to be specified on one line (as you have done with rmThis).

Normally del is used without parentheses, as:

del x

However, including parentheses around the argument as del(x) is allowed but doesn't mean it's a function call.

like image 57
Greg Hewgill Avatar answered Oct 13 '22 00:10

Greg Hewgill