Check for mutability in Python?

后端 未结 7 1840
小鲜肉
小鲜肉 2020-12-28 13:23

Consider this code:

a = {...} # a is an dict with arbitrary contents
b = a.copy()
  1. What role does mutability play in the keys and valu
7条回答
  •  执念已碎
    2020-12-28 13:50

    There are MutableSequence, MutableSet, MutableMapping in module collections. Which can be used to check mutability of premade types.

    issubclass(TYPE, (MutableSequence, MutableSet, MutableMapping))
    

    If you want use this on user defined types, the type must be either inherited from one of them or registered as a virtual subclass.

    class x(MutableSequence):
        ...
    

    or

    class x:
        ...
    
    abc.ABCMeta.register(MutableSequence,x)
    

提交回复
热议问题