I have several functions that I'd like to operate on both mutable and immutable containers (mostly tuples vs. objects) and I'm looking for the optimal way to test for mutability in these objects. I can think of many ways to do this. For example:

try setattr:
  do mutable stuff
except Error:
  do immutable replacements

I also considered adding a metaattribute to my classes based on mutability; however, this limits the usage of my functions to just the customized objects in my programs.

I could also make 2 functions, one for mutable and one for immutable objects, but then I get lots of extra code.

Does anyone know of a Pythonic, best way to think about this?

Edited by hughesadam_87

4 Years
Discussion Span
Last Post by hughesadam_87

try except statement is usually considered most Pythonic , "ask for forgiveness, not permission"

You could consider however using least efficient common way as default, which works both for mutable and immutable object. Then you could offer optimised version mutating the parameter. This could be good as natural way to do operation for immutable object is to produce new object and return it as value of function. Operations with using mutability are generally better not to return value to make clear that value of variable has changed as side effect.

Edited by pyTony

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.