Is isinstance(lambda, type(lambda)) correct?

669 Views Asked by At

Are there any caveats to isinstance(fn, type(lambda: 1))? I'm aware of this approach, but mine spares an import.

Clarification:

  • callable doesn't cut it - class false positive
  • Context: pickle can't pickle lambdas, must filter out of objects before pickling them. This includes local function definitions via def, but my method above covers it.
  • Question purpose: to know of possible (1) memory, (2) correctness implications. (1): is lambda: 1 garbage-collected? (2): will my approach detect any objects other than lambdas, functions, and local functions?

Minimal code: (I know there's a shorter way here, but not in the full context)

for key, val in obj.items():
    if isinstance(val, type(lambda: 1)):  # can't pickle lambdas
        to_exclude.append(key)

to_save = {k:v for k,v in obj.items() if k not in to_exclude}
pickle.dump(to_save, file)
1

There are 1 best solutions below

7
On

Apart from creating an instance of a lambda just to get a type, there should be no problem with it. It will match def function as well as lambdas which makes the condition somewhat misleading relative to your intent.

If you merely need to know if fn is a callable object (function or lambda) you should express this as callable(fn) which better conveys your intention.