Reputation: 19806
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 positivepickle
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.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)
Upvotes: 0
Views: 759
Reputation: 42133
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.
Upvotes: 1