Hi,

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?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.