Are there any caveats to isinstance(fn, type(lambda: 1))? I'm aware of this approach, but mine spares an import.
Clarification:
callabledoesn't cut it -classfalse positive- Context:
picklecan't pickle lambdas, must filter out of objects before pickling them. This includes local function definitions viadef, but my method above covers it. - Question purpose: to know of possible (1) memory, (2) correctness implications. (1): is
lambda: 1garbage-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)
Apart from creating an instance of a lambda just to get a type, there should be no problem with it. It will match
def functionas 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.