OverLordGoldDragon
OverLordGoldDragon

Reputation: 19806

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

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

Clarification:


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

Answers (1)

Alain T.
Alain T.

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

Related Questions