find method in parent class in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function testing list operations asserts are within individual test methods testing dict operations tests for unary and binary operators testing int operations the following crashes in python 2 2 this returns notimplemented in python 2 2 testing float operations testing complex operations see issue 9930 testing spamlist operations this is an ugly hack test subclassing testing spamdict operations this is an ugly hack test subclassing testing python subclass of dict testing python subclass of list testing metaclasses early binding of methods more metaclass examples automatically add super to the class this trick only works for dynamic classes name mangling for super removes leading underscores automatically create property attributes when methods named getx andor setx are found merge of multiple cooperating metaclasses make sure typex doesn t call x class init testing code to find most derived baseclass the most derived metaclass of d is a rather than type issue1294232 correct metaclass calculation bmeta new calls ameta new with super the most derived metaclass is bmeta bmeta prepare should ve been called the order of the bases shouldn t matter check correct metaclass calculation when a metaclass is declared special case the given metaclass isn t a class so there is no metaclass calculation the given metaclass is a class but not a descendant of type this is a typeerror because of a metaclass conflict bnotmeta is neither a subclass nor a superclass of type typeerror bnotmeta is neither a subclass nor a superclass of int testing python subclass of module https bugs python orgissue1174712 issue 34805 verify that definition order is retained testing multiple inheritance sf bug 442833 testing multiple inheritance special cases mro order disagreement see thread pythondev2002october029035 html testing ex5 from c3 switch discussion see a monotonic superclass linearization for dylan by kim barrett et al oopsla 1996 testing mro monotonicity see a monotonic superclass linearization for dylan by kim barrett et al oopsla 1996 testing consistency with epg testing error messages for mro disagreement the exact msg is generally considered an impl detail test some very simple errors test a slightly more complex error testing object class make sure that builtin immutable objects don t support class assignment because the object instances may be interned we set slots to ensure that the subclasses are memorylayout compatible and thus otherwise reasonable candidates for class assignment the following types have immutable instances but are not subclassable and thus don t need to be checked nonetype bool testing slots validate name mangling slots a def initself value self a value def getself return self a x c45 self assertnothasattrx dict self assertnothasattrx a self assertequalx get 5 try x a 6 except attributeerror pass else self faildouble underscored names not mangled make sure slot names are proper identifiers try class cobject slots none except typeerror pass else self failnone slots not caught try class cobject slots foo bar except typeerror pass else self fail foo bar slots not caught try class cobject slots foo0bar except typeerror pass else self fail foo0bar slots not caught try class cobject slots 1 except typeerror pass else self fail 1 slots not caught try class cobject slots except typeerror pass else self fail slots not caught class cobject slots a ab a a0123456789z xxxnnorwitz was there supposed to be something tested from the class above test a single string is not expanded as a sequence class cobject slots abc c c c abc 5 self assertequalc abc 5 test unicode slot names test a single unicode string is not expanded as a sequence class cobject slots abc c c c abc 5 self assertequalc abc 5 unicodetostring used to modify slots in certain circumstances slots foo bar class cobject slots slots x c x foo 5 self assertequalx foo 5 self assertistypeslots0 str this used to leak references try class cobject slots chr128 except typeerror unicodeencodeerror pass else self failchr128 slots not caught test leaks class countedobject counter 0 counts the number of instances alive def initself counted counter 1 def delself counted counter 1 class cobject slots a b c x c x a counted x b counted x c counted self assertequalcounted counter 3 del x support gccollect self assertequalcounted counter 0 class dc pass x d x a counted x z counted self assertequalcounted counter 2 del x support gccollect self assertequalcounted counter 0 class ed slots e x e x a counted x z counted x e counted self assertequalcounted counter 3 del x support gccollect self assertequalcounted counter 0 test cyclical leaks sf bug 519621 class fobject slots a b s f s a counted s self assertequalcounted counter 1 s none support gccollect self assertequalcounted counter 0 test lookup leaks sf bug 572567 if hasattrgc getobjects class gobject def eqself other return false g g origobjects lengc getobjects for i in range10 gg newobjects lengc getobjects self assertequalorigobjects newobjects class hobject slots a b def initself self a 1 self b 2 def delself self assertequalself a 1 self assertequalself b 2 with support capturedoutput stderr as s h h del h self assertequals getvalue class xobject slots a with self assertraisesattributeerror del x a inherit from object on purpose to check some backwards compatibility paths class xobject slots a with self assertraisesregexattributeerror x object has no attribute a x a test string subclass in slots see gh98783 class substrstr pass class xobject slots substr x x x 1 with self assertraisesregexattributeerror x object has no attribute a x a def testslotsspecialself testing dict and weakref in slots class dobject slots dict a d self asserthasattra dict self assertnothasattra weakref a foo 42 self assertequala dict foo 42 class wobject slots weakref a w self asserthasattra weakref self assertnothasattra dict try a foo 42 except attributeerror pass else self failshouldn t be allowed to set a foo class c1w d slots a c1 self asserthasattra dict self asserthasattra weakref a foo 42 self assertequala dict foo 42 class c2d w slots a c2 self asserthasattra dict self asserthasattra weakref a foo 42 self assertequala dict foo 42 def testslotsspecial2self testing qualname and classcell in slots class metatype def newcls name bases namespace attr self assertinattr namespace return super newcls name bases namespace class c1 def initself self b 42 class c2c1 metaclassmeta attrclasscell slots classcell def initself super init self assertisinstancec2 dictclasscell types memberdescriptortype c c2 self assertequalc b 42 self assertnothasattrc classcell c classcell 42 self assertequalc classcell 42 with self assertraisestypeerror class c3 classcell 42 slots classcell class q1metaclassmeta attrqualname slots qualname self assertequalq1 qualname c1 qualname 2 q1 self assertisinstanceq1 dictqualname types memberdescriptortype q q1 self assertnothasattrq qualname q qualname q self assertequalq qualname q with self assertraisestypeerror class q2 qualname object slots qualname def testslotsdescriptorself issue2115 slot descriptors did not correctly check the type of the given object import abc class myabcmetaclassabc abcmeta slots a class unrelatedobject pass myabc registerunrelated u unrelated self assertisinstanceu myabc this used to crash self assertraisestypeerror myabc a set u 3 def testdynamicsself testing class attribute propagation class dobject pass class ed pass class fd pass d foo 1 self assertequald foo 1 test that dynamic attributes are inherited self assertequale foo 1 self assertequalf foo 1 test dynamic instances class cobject pass a c self assertnothasattra foobar c foobar 2 self assertequala foobar 2 c method lambda self 42 self assertequala method 42 c repr lambda self c self assertequalrepra c c int lambda self 100 self assertequalinta 100 self assertequala foobar 2 self assertnothasattra spam def mygetattrself name if name spam return spam raise attributeerror c getattr mygetattr self assertequala spam spam a new 12 self assertequala new 12 def mysetattrself name value if name spam raise attributeerror return object setattrself name value c setattr mysetattr with self assertraisesattributeerror a spam not spam self assertequala spam spam class dc pass d d d foo 1 self assertequald foo 1 test handling of intseq and seqint class iint pass self assertequalai2 aa self assertequali2a aa self assertequal2i3 6 self assertequali32 6 self assertequali3i2 6 test comparison of classes with dynamic metaclasses class dynamicmetaclasstype pass class someclassmetaclassdynamicmetaclass pass self assertnotequalsomeclass object def testerrorsself testing errors try class clist dict pass except typeerror pass else self failinheritance from both list and dict should be illegal try class cobject none pass except typeerror pass else self failinheritance from nontype should be illegal class classic pass try class ctypelen pass except typeerror pass else self failinheritance from cfunction should be illegal try class cobject slots 1 except typeerror pass else self failslots 1 should be illegal try class cobject slots 1 except typeerror pass else self failslots 1 should be illegal class m1type pass class m2type pass class a1object metaclassm1 pass class a2object metaclassm2 pass try class ba1 a2 pass except typeerror pass else self failfinding the most derived metaclass should have failed def testclassmethodsself testing class methods class cobject def fooa return a goo classmethodfoo c c self assertequalc goo1 c 1 self assertequalc goo1 c 1 self assertequalc foo1 c 1 class dc pass d d self assertequald goo1 d 1 self assertequald goo1 d 1 self assertequald foo1 d 1 self assertequald food 1 d 1 test for a specific crash sf bug 528132 def fcls arg f docstring return cls arg ff classmethodf self assertequalff get0 int42 int 42 self assertequalff get042 int 42 test super with classmethods sf bug 535444 self assertequalc goo self c self assertequald goo self d self assertequalsuperd d goo self d self assertequalsuperd d goo self d self assertequalsuperd d goo d self assertequalsuperd d goo d verify that a noncallable will raise meth classmethod1 get1 self assertraisestypeerror meth verify that classmethod doesn t allow keyword args try classmethodf kw1 except typeerror pass else self failclassmethod shouldn t accept keyword args cm classmethodf cmdict annotations doc f docstring module name name f qualname f qualname self assertequalcm dict cmdict cm x 42 self assertequalcm x 42 self assertequalcm dict x 42 cmdict del cm x self assertnothasattrcm x support refcounttest def testrefleaksinclassmethodinitself gettotalrefcount support getattributesys gettotalrefcount cm classmethodnone refsbefore gettotalrefcount for i in range100 cm initnone self assertalmostequalgettotalrefcount refsbefore 0 delta10 support impldetailthe module xxsubtype is internal unittest skipifxxsubtype is none requires xxsubtype module def testclassmethodsincself testing cbased class methods import xxsubtype as spam a 1 2 3 d abc 123 x a1 d1 spam spamlist classmetha d self assertequalx spam spamlist self assertequala a1 self assertequald d1 x a1 d1 spam spamlist classmetha d self assertequalx spam spamlist self assertequala a1 self assertequald d1 spamcm spam spamlist dict classmeth x2 a2 d2 spamcmspam spamlist a d self assertequalx2 spam spamlist self assertequala2 a1 self assertequald2 d1 class subspamspam spamlist pass x2 a2 d2 spamcmsubspam a d self assertequalx2 subspam self assertequala2 a1 self assertequald2 d1 with self assertraisestypeerror as cm spamcm self assertequal strcm exception descriptor classmeth of xxsubtype spamlist object needs an argument with self assertraisestypeerror as cm spamcmspam spamlist self assertequal strcm exception descriptor classmeth for type xxsubtype spamlist needs a type not a xxsubtype spamlist as arg 2 with self assertraisestypeerror as cm spamcmlist expectederrmsg descriptor classmeth requires a subtype of xxsubtype spamlist but received list self assertequalstrcm exception expectederrmsg with self assertraisestypeerror as cm spamcm getnone list self assertequalstrcm exception expectederrmsg def teststaticmethodsself testing static methods class cobject def fooa return a goo staticmethodfoo c c self assertequalc goo1 1 self assertequalc goo1 1 self assertequalc foo1 c 1 class dc pass d d self assertequald goo1 1 self assertequald goo1 1 self assertequald foo1 d 1 self assertequald food 1 d 1 sm staticmethodnone self assertequalsm dict doc none sm x 42 self assertequalsm x 42 self assertequalsm dict x 42 doc none del sm x self assertnothasattrsm x support refcounttest def testrefleaksinstaticmethodinitself gettotalrefcount support getattributesys gettotalrefcount sm staticmethodnone refsbefore gettotalrefcount for i in range100 sm initnone self assertalmostequalgettotalrefcount refsbefore 0 delta10 support impldetailthe module xxsubtype is internal unittest skipifxxsubtype is none requires xxsubtype module def teststaticmethodsincself testing cbased static methods import xxsubtype as spam a 1 2 3 d abc 123 x a1 d1 spam spamlist staticmetha d self assertequalx none self assertequala a1 self assertequald d1 x a1 d2 spam spamlist staticmetha d self assertequalx none self assertequala a1 self assertequald d1 def testclassicself testing classic classes class c def fooa return a goo classmethodfoo c c self assertequalc goo1 c 1 self assertequalc goo1 c 1 self assertequalc foo1 c 1 class dc pass d d self assertequald goo1 d 1 self assertequald goo1 d 1 self assertequald foo1 d 1 self assertequald food 1 d 1 class e not subclassing from c foo c foo self assertequale foo func c foo i e unbound self asserttruereprc foo getc startswithbound method def testcompattrself testing computed attributes class cobject class computedattributeobject def initself get setnone deletenone self get get self set set self delete delete def getself obj typenone return self getobj def setself obj value return self setobj value def deleteself obj return self deleteobj def initself self x 0 def getxself x self x self x x1 return x def setxself x self x x def deletexself del self x x computedattributegetx setx deletex a c self assertequala x 0 self assertequala x 1 a x 10 self assertequala x 10 self assertequala x 11 del a x self assertnothasattra x def testnewslotsself testing new slot override class clist def newcls self list newcls self foo 1 return self def initself self foo self foo 2 a c self assertequala foo 3 self assertequala class c class dc pass b d self assertequalb foo 3 self assertequalb class d unittest expectedfailure def testbadnewself self assertraisestypeerror object new self assertraisestypeerror object new self assertraisestypeerror list new object self assertraisestypeerror object new list class cobject new list new self assertraisestypeerror c class clist new object new self assertraisestypeerror c def testobjectnewself class aobject pass object newa self assertraisestypeerror object new a 5 object inita self assertraisestypeerror object init a 5 class aobject def initself foo self foo foo object newa object newa 5 object inita3 self assertraisestypeerror object init a3 5 class aobject def newcls foo return object newcls object newa self assertraisestypeerror object new a 5 object inita3 object inita3 5 class aobject def newcls foo return object newcls def initself foo self foo foo object newa self assertraisestypeerror object new a 5 object inita3 self assertraisestypeerror object init a3 5 unittest expectedfailure def testrestoredobjectnewself class aobject def newcls args kwargs raise assertionerror self assertraisesassertionerror a class ba new object new def initself foo self foo foo with warnings catchwarnings warnings simplefilter error deprecationwarning b b3 self assertequalb foo 3 self assertequalb class b del b new self assertraisesassertionerror b del a new with warnings catchwarnings warnings simplefilter error deprecationwarning b b3 self assertequalb foo 3 self assertequalb class b def testaltmroself testing mro and overriding it class aobject def fself return a class ba pass class ca def fself return c class db c pass self assertequala mro a object self assertequala mro a object self assertequalb mro b a object self assertequalb mro b a object self assertequalc mro c a object self assertequalc mro c a object self assertequald mro d b c a object self assertequald mro d b c a object self assertequald f c class perversemetatypetype def mrocls l type mrocls l reverse return l class xd b c a metaclassperversemetatype pass self assertequalx mro object a c b d x self assertequalx f a try class metaclasstype def mroself return self dict object class xobject metaclassmetaclass pass in cpython the class creation above already raises typeerror as a protection against the fact that instances of x would segfault it in other python implementations it would be ok to let the class x be created but instead get a clean typeerror on the setitem below x object newx x5 6 except typeerror pass else self faildevious mro return not caught try class metaclasstype def mroself return 1 class xobject metaclassmetaclass pass except typeerror pass else self failnonclass mro return not caught try class metaclasstype def mroself return 1 class xobject metaclassmetaclass pass except typeerror pass else self failnonsequence mro return not caught def testoverloadingself testing operator overloading class bobject intermediate class because object doesn t have a setattr class cb def getattrself name if name foo return getattr name else raise attributeerror def setattrself name value if name foo self setattr name value else return b setattrself name value def delattrself name if name foo self delattr name else return b delattrself name def getitemself key return getitem key def setitemself key value self setitem key value def delitemself key self delitem key a c self assertequala foo getattr foo a foo 12 self assertequala setattr foo 12 del a foo self assertequala delattr foo self assertequala12 getitem 12 a12 21 self assertequala setitem 12 21 del a12 self assertequala delitem 12 self assertequala0 10 getitem slice0 10 a0 10 foo self assertequala setitem slice0 10 foo del a0 10 self assertequala delitem slice0 10 def testloadattrextendedargself https github compythoncpythonissues91625 class numbers def getattrself attr return intattr lstrip attrs joinfz n 03d for n in range280 code fdef numberattrsz n return attrs ns execcode ns numberattrs nsnumberattrs warm up the function for quickening pep 659 for in range30 self assertequalnumberattrsnumbers listrange280 def testmethodsself testing methods class cobject def initself x self x x def fooself return self x c1 c1 self assertequalc1 foo 1 class dc boo c foo goo c1 foo d2 d2 self assertequald2 foo 2 self assertequald2 boo 2 self assertequald2 goo 1 class eobject foo c foo self assertequale foo func c foo i e unbound self asserttruereprc foo getc1 startswithbound method support impldetailtesting error message from implementation def testmethodsincself this test checks error messages in builtin method descriptor it is allowed that other python implementations use different error messages setadd set add expectederrmsg unbound method set add needs an argument with self assertraisestypeerror as cm setadd self assertequalcm exception args0 expectederrmsg expectederrmsg descriptor add for set objects doesn t apply to a int object with self assertraisestypeerror as cm setadd0 self assertequalcm exception args0 expectederrmsg with self assertraisestypeerror as cm setadd get0 self assertequalcm exception args0 expectederrmsg def testspecialmethodlookupself the lookup of special methods bypasses getattr and getattribute but they still can be descriptors def runcontextmanager with manager pass def idenself return self def helloself return bhello def emptyseqself return def zeroself return 0 def complexnumself return 1j def stopself raise stopiteration def returntrueself thingnone return true def doisinstanceobj return isinstanceint obj def doissubclassobj return issubclassint obj def dodictmissingchecker class dictsubchecker class dict pass self assertequaldictsubhi 4 def somenumberself key self assertequalkey hi return 4 def swallowargs pass def formatimplself spec return hello it would be nice to have every special method tested here but i m only listing the ones i can remember outside of typeobject c since it does it right specials bytes bytes hello set reversed reversed emptyseq set lengthhint list zero set iter iden next stop sizeof sys getsizeof zero set instancecheck doisinstance returntrue set missing dodictmissing somenumber setclass subclasscheck doissubclass returntrue setbases enter runcontext iden set exit swallow exit runcontext swallow set enter iden complex complex complexnum set format format formatimpl set floor math floor zero set trunc math trunc zero set ceil math ceil zero set dir dir emptyseq set round round zero set class checkerobject def getattrself attr testself test failgetattr called with 0 formatattr def getattributeself attr testself if attr not in ok test failgetattribute called with 0 formatattr return object getattributeself attr class specialdescrobject def initself impl self impl impl def getself obj owner record append1 return self impl getobj owner class myexceptionexception pass class errdescrobject def getself obj owner raise myexception for name runner methimpl ok env in specials class xchecker pass for attr obj in env items setattrx attr obj setattrx name methimpl runnerx record class xchecker pass for attr obj in env items setattrx attr obj setattrx name specialdescrmethimpl runnerx self assertequalrecord 1 name class xchecker pass for attr obj in env items setattrx attr obj setattrx name errdescr self assertraisesmyexception runner x def testspecialsself testing special operators test operators like hash for which a builtin default exists test the default behavior for static classes class cobject def getitemself i if 0 i 10 return i raise indexerror c1 c c2 c self assertfalsenot c1 self assertnotequalidc1 idc2 hashc1 hashc2 self assertequalc1 c1 self asserttruec1 c2 self assertfalsec1 c1 self assertfalsec1 c2 note that the module name appears in strrepr and that varies depending on whether this test is run standalone or from a framework self assertgreaterequalstrc1 find c object at 0 self assertequalstrc1 reprc1 self assertnotin1 c1 for i in range10 self assertini c1 self assertnotin10 c1 test the default behavior for dynamic classes class dobject def getitemself i if 0 i 10 return i raise indexerror d1 d d2 d self assertfalsenot d1 self assertnotequalidd1 idd2 hashd1 hashd2 self assertequald1 d1 self assertnotequald1 d2 self assertfalsed1 d1 self assertfalsed1 d2 note that the module name appears in strrepr and that varies depending on whether this test is run standalone or from a framework self assertgreaterequalstrd1 find d object at 0 self assertequalstrd1 reprd1 self assertnotin1 d1 for i in range10 self assertini d1 self assertnotin10 d1 test overridden behavior class proxyobject def initself x self x x def boolself return not not self x def hashself return hashself x def eqself other return self x other def neself other return self x other def geself other return self x other def gtself other return self x other def leself other return self x other def ltself other return self x other def strself return proxy s self x def reprself return proxyr self x def containsself value return value in self x p0 proxy0 p1 proxy1 p1 proxy1 self assertfalsep0 self assertfalsenot p1 self assertequalhashp0 hash0 self assertequalp0 p0 self assertnotequalp0 p1 self assertfalsep0 p0 self assertequalnot p0 p1 self asserttruep0 p1 self asserttruep0 p1 self asserttruep1 p0 self asserttruep1 p0 self assertequalstrp0 proxy 0 self assertequalreprp0 proxy0 p10 proxyrange10 self assertnotin1 p10 for i in range10 self assertini p10 self assertnotin10 p10 def testweakrefsself testing weak references import weakref class cobject pass c c r weakref refc self assertequalr c del c support gccollect self assertequalr none del r class noweakobject slots foo no noweak try weakref refno except typeerror as msg self assertinweak reference strmsg else self failweakref refno should be illegal class weakobject slots foo weakref yes weak r weakref refyes self assertequalr yes del yes support gccollect self assertequalr none del r def testpropertiesself testing property class cobject def getxself return self x def setxself value self x value def delxself del self x x propertygetx setx delx doci m the x property a c self assertnothasattra x a x 42 self assertequala cx 42 self assertequala x 42 del a x self assertnothasattra x self assertnothasattra cx c x seta 100 self assertequalc x geta 100 c x deletea self assertnothasattra x raw c dict x self assertisinstanceraw property attrs dirraw self assertindoc attrs self assertinfget attrs self assertinfset attrs self assertinfdel attrs self assertequalraw doc i m the x property self assertisraw fget c dict getx self assertisraw fset c dict setx self assertisraw fdel c dict delx for attr in fget fset fdel try setattrraw attr 42 except attributeerror as msg if strmsg find readonly 0 self failwhen setting readonly attr r on a property got unexpected attributeerror msg r attr strmsg else self failexpected attributeerror from trying to set readonly r attr on a property attr raw doc 42 self assertequalraw doc 42 class dobject getitem propertylambda s 10 d d try for i in d stri except zerodivisionerror pass else self failexpected zerodivisionerror from bad property unittest skipifsys flags optimize 2 docstrings are omitted with o2 and above def testpropertiesdocattribself class eobject def getterself getter method return 0 def setterself value setter method pass prop propertygetter self assertequalprop doc getter method prop2 propertyfsetsetter self assertequalprop2 doc none support cpythononly def testtestcapinosegfaultself this segfaulted in 2 5b2 try import testcapi except importerror pass else class xobject p propertytestcapi testwithdocstring def testpropertiesplusself class cobject foo propertydochello foo getter def fooself return self foo foo setter def fooself value self foo absvalue foo deleter def fooself del self foo c c self assertequalc foo doc hello self assertnothasattrc foo c foo 42 self asserthasattrc foo self assertequalc foo 42 self assertequalc foo 42 del c foo self assertnothasattrc foo self assertnothasattrc foo class dc c foo deleter def fooself try del self foo except attributeerror pass d d d foo 24 self assertequald foo 24 del d foo del d foo class eobject property def fooself return self foo foo setter def fooself value raise runtimeerror foo setter def fooself value self foo absvalue foo deleter def fooself valuenone del self foo e e e foo 42 self assertequale foo 42 del e foo class fe e foo deleter def fooself del self foo foo setter def fooself value self foo max0 value f f f foo 10 self assertequalf foo 0 del f foo def testdictconstructorsself testing dict constructor d dict self assertequald d dict self assertequald d dict1 2 a b self assertequald 1 2 a b self assertequald dictlistd items self assertequald dictiterd items d dict one 1 two 2 self assertequald dictone1 two2 self assertequald dictd self assertequald dictone 1 two2 self assertequald dicttwo 2 one1 self assertequald dictone 100 two 200 d self assertequald dictd for badarg in 0 0 0j 0 0 0 try dictbadarg except typeerror pass except valueerror if badarg 0 it s a sequence and its elements are also sequences gotta love strings wink but they aren t of length 2 so this one seemed better as a valueerror than a typeerror pass else self failno typeerror from dictr badarg else self failno typeerror from dictr badarg with self assertraisestypeerror dict class mapping lacks a keys method will be added later dict 1 2 3 4 a 1j try dictmapping except typeerror pass else self failno typeerror from dictincomplete mapping mapping keys lambda self listself dict keys mapping getitem lambda self i self dicti d dictmapping self assertequald mapping dict init from sequence of iterable objects each producing a 2sequence class addressbookentry def initself first last self first first self last last def iterself return iterself first self last d dictaddressbookentry tim warsaw addressbookentry barry peters addressbookentry tim peters addressbookentry barry warsaw self assertequald barry warsaw tim peters d dictziprange4 range1 5 self assertequald dicti i1 for i in range4 bad sequence lengths for bad in tooshort too long by 1 try dictbad except valueerror pass else self failno valueerror from dictr bad def testdirself testing dir junk 12 self assertequaldir junk self del junk just make sure these don t blow up for arg in 2 2 2j 2e0 2 2 b2 2 2 2 type self testdir dirarg test dir on newstyle classes since these have object as a base class a lot more gets sucked in def interestingstrings return s for s in strings if not s startswith class cobject cdata 1 def cmethodself pass cstuff cdata cmethod self assertequalinterestingdirc cstuff c c self assertequalinterestingdirc cstuff self assertin self dirc cmethod c cdata 2 c cmethod lambda self 0 self assertequalinterestingdirc cstuff cdata cmethod self assertin self dirc cmethod class ac adata 1 def amethodself pass astuff adata amethod cstuff self assertequalinterestingdira astuff self assertin self dira amethod a a self assertequalinterestingdira astuff a adata 42 a amethod lambda self 3 self assertequalinterestingdira astuff adata amethod self assertin self dira amethod try a module subclass class mtypesys pass minstance mm minstance b 2 minstance a 1 defaultattributes name doc package loader spec names x for x in dirminstance if x not in defaultattributes self assertequalnames a b class m2m def getdictself return not a dict dict propertygetdict m2instance m2m2 m2instance b 2 m2instance a 1 self assertequalm2instance dict not a dict with self assertraisestypeerror dirm2instance two essentially featureless objects ellipsis just inherits stuff from object self assertequaldirobject direllipsis nasty test case for proxied objects class wrapperobject def initself obj self obj obj def reprself return wrappers reprself obj def getitemself key return wrapperself objkey def lenself return lenself obj def getattrself name return wrappergetattrself obj name class cobject def getclassself return wrappertypeself class propertygetclass dirc this used to segfault def testsupersself testing super class aobject def methself a return ar a self assertequala meth1 a1 class ba def initself self super superb self def methself a return br a self super metha self assertequalb meth2 b2a2 class ca def methself a return cr a self super metha c csuper superc self assertequalc meth3 c3a3 class dc b def methself a return dr a superd self metha self assertequald meth4 d4c4b4a4 test for subclassing super class mysupersuper def initself args return supermysuper self initargs class ed def methself a return er a mysupere self metha self assertequale meth5 e5d5c5b5a5 class fe def methself a s self super mysuperf self return frs a s class name s metha f fsuper mysuperf self assertequalf meth6 f6mysupere6d6c6b6a6 make sure certain errors are raised try superd 42 except typeerror pass else self failshouldn t allow superd 42 try superd c except typeerror pass else self failshouldn t allow superd c try superd get12 except typeerror pass else self failshouldn t allow superd get12 try superd getc except typeerror pass else self failshouldn t allow superd getc make sure data descriptors can be overridden and accessed via super new feature in python 2 3 class ddbaseobject def getxself return 42 x propertygetx class ddsubddbase def getxself return hello x propertygetx dd ddsub self assertequaldd x hello self assertequalsuperddsub dd x 42 ensure that super lookup of descriptor from classmethod works sf id 743627 class baseobject aprop propertylambda self foo class subbase classmethod def testklass return supersub klass aprop self assertequalsub test base aprop verify that super doesn t allow keyword args with self assertraisestypeerror superbase kw1 def testbasicinheritanceself testing inheritance from basic types class hexintint def reprself return hexself def addself other return hexintint addself other note that overriding radd doesn t work because the int type gets first dibs self assertequalreprhexint7 9 0x10 self assertequalreprhexint1000 7 0x3ef a hexint12345 self assertequala 12345 self assertequalinta 12345 self assertisinta class int self assertequalhasha hash12345 self assertisa class int self assertisa 0 class int self assertisa 0 class int self assertishexint0 12 class int self assertishexint0 12 class int class octlongint slots def strself return octself def addself other return self classsuperoctlong self addother radd add self assertequalstroctlong3 5 0o10 note that overriding radd here only seems to work because the example uses a short int left argument self assertequalstr5 octlong3000 0o5675 a octlong12345 self assertequala 12345 self assertequalinta 12345 self assertequalhasha hash12345 self assertisinta class int self assertisa class int self assertisa class int self assertisoctlong0 class int self assertisa 0 class int self assertisa 0 class int self assertisa 0 class int self assertisa 1 class int self assertisa 1 class int self assertisa 1 class int self assertis1 a class int self assertisa 0 class int self assertisa 0 class int self assertisa 1 class int self assertisoctlong0 12 class int self assertisoctlong0 12 class int self assertisabsoctlong0 class int because octlong overrides add we can t check the absence of 0 optimizations using octlong class longcloneint pass a longclone1 self assertisa 0 class int self assertis0 a class int check that negative clones don t segfault a longclone1 self assertequala dict self assertequalinta 1 self asserttrue pynumberlong copies the sign bit class precfloatfloat slots prec def initself value0 0 prec12 self prec intprec def reprself return g self prec self self assertequalreprprecfloat1 1 1 1 a precfloat12345 self assertequala 12345 0 self assertequalfloata 12345 0 self assertisfloata class float self assertequalhasha hash12345 0 self assertisa class float class madcomplexcomplex def reprself return 17gj 17g self imag self real a madcomplex3 4 self assertequalrepra 4j3 base complex3 4 self assertequalbase class complex self assertequala base self assertequalcomplexa base self assertequalcomplexa class complex a madcomplexa just trying another form of the constructor self assertequalrepra 4j3 self assertequala base self assertequalcomplexa base self assertequalcomplexa class complex self assertequalhasha hashbase self assertequala class complex self assertequala 0 class complex self assertequala 0 base self assertequala 0 class complex self assertequala 0 base self assertequala 1 class complex self assertequala 1 base self assertequala 1 class complex self assertequala 1 base class madtupletuple rev none def revself if self rev is not none return self rev l listself l reverse self rev self classl return self rev a madtuple1 2 3 4 5 6 7 8 9 0 self assertequala 1 2 3 4 5 6 7 8 9 0 self assertequala rev madtuple0 9 8 7 6 5 4 3 2 1 self assertequala rev rev madtuple1 2 3 4 5 6 7 8 9 0 for i in range512 t madtuplerangei u t rev v u rev self assertequalv t a madtuple1 2 3 4 5 self assertequaltuplea 1 2 3 4 5 self assertistuplea class tuple self assertequalhasha hash1 2 3 4 5 self assertisa class tuple self assertisa 1 class tuple self assertisa 0 class tuple self assertisa class tuple a madtuple self assertequaltuplea self assertistuplea class tuple self assertisa a class tuple self assertisa 0 class tuple self assertisa 1 class tuple self assertisa 2 class tuple self assertisa class tuple class madstringstr rev none def revself if self rev is not none return self rev l listself l reverse self rev self class joinl return self rev s madstringabcdefghijklmnopqrstuvwxyz self assertequals abcdefghijklmnopqrstuvwxyz self assertequals rev madstringzyxwvutsrqponmlkjihgfedcba self assertequals rev rev madstringabcdefghijklmnopqrstuvwxyz for i in range256 s madstring joinmapchr rangei t s rev u t rev self assertequalu s s madstring12345 self assertequalstrs 12345 self assertisstrs class str base x00 5 s madstringbase self assertequals base self assertequalstrs base self assertisstrs class str self assertequalhashs hashbase self assertequals 1base 1 self assertequalbase 1s 1 self assertiss class str self assertequals base self assertis s class str self assertequal s base self assertiss 0 class str self assertequals 0 self assertiss 1 class str self assertequals 1 base self assertiss 2 class str self assertequals 2 base base self assertiss class str self assertequals base self assertiss0 0 class str self assertequals0 0 self assertiss strip class str self assertequals strip base self assertiss lstrip class str self assertequals lstrip base self assertiss rstrip class str self assertequals rstrip base identitytab self assertiss translateidentitytab class str self assertequals translateidentitytab base self assertiss replacex x class str self assertequals replacex x base self assertiss ljustlens class str self assertequals ljustlens base self assertiss rjustlens class str self assertequals rjustlens base self assertiss centerlens class str self assertequals centerlens base self assertiss lower class str self assertequals lower base class madunicodestr rev none def revself if self rev is not none return self rev l listself l reverse self rev self class joinl return self rev u madunicodeabcdef self assertequalu abcdef self assertequalu rev madunicodefedcba self assertequalu rev rev madunicodeabcdef base 12345 u madunicodebase self assertequalstru base self assertisstru class str self assertequalhashu hashbase self assertequalu 1base 1 self assertequalbase 1u 1 self assertisu strip class str self assertequalu strip base self assertisu lstrip class str self assertequalu lstrip base self assertisu rstrip class str self assertequalu rstrip base self assertisu replacex x class str self assertequalu replacex x base self assertisu replacexy xy class str self assertequalu replacexy xy base self assertisu centerlenu class str self assertequalu centerlenu base self assertisu ljustlenu class str self assertequalu ljustlenu base self assertisu rjustlenu class str self assertequalu rjustlenu base self assertisu lower class str self assertequalu lower base self assertisu upper class str self assertequalu upper base self assertisu capitalize class str self assertequalu capitalize base self assertisu title class str self assertequalu title base self assertisu class str self assertequalu base self assertis u class str self assertequal u base self assertisu 0 class str self assertequalu 0 self assertisu 1 class str self assertequalu 1 base self assertisu 2 class str self assertequalu 2 base base self assertisu class str self assertequalu base self assertisu0 0 class str self assertequalu0 0 class sublistlist pass a sublistrange5 self assertequala listrange5 a appendhello self assertequala listrange5 hello a5 5 self assertequala listrange6 a extendrange6 20 self assertequala listrange20 a5 self assertequala listrange15 del a10 15 self assertequallena 10 self assertequala listrange10 self assertequallista listrange10 self assertequala0 0 self assertequala9 9 self assertequala10 0 self assertequala1 9 self assertequala 5 listrange5 class countedinputfile counts lines read by self readline self lineno is the 0based ordinal of the last line read up to a maximum of one greater than the number of lines in the file self ateof is true if and only if the final line has been read at which point self lineno stops incrementing and further calls to readline continue to return lineno 0 ateof 0 def readlineself if self ateof return s file readlineself next line works too s supercountedinput self readline self lineno 1 if s self ateof 1 return s f filenameoshelper testfn mode w lines an bn cn try f writelineslines f close f countedinputoshelper testfn for i expected in ziprange1 5 4 lines 2 got f readline self assertequalexpected got self assertequalf lineno i self assertequalf ateof i lenlines f close finally try f close except pass oshelper unlinkoshelper testfn def testkeywordsself testing keyword args to basic type constructors with self assertraisesregextypeerror keyword argument intx1 with self assertraisesregextypeerror keyword argument floatx2 with self assertraisesregextypeerror keyword argument boolx2 self assertequalcompleximag42 real666 complex666 42 self assertequalstrobject500 500 self assertequalstrobjectb abc errors strict abc with self assertraisesregextypeerror keyword argument tuplesequencerange3 with self assertraisesregextypeerror keyword argument listsequence0 1 2 note as of python 2 3 dict no longer has an items keyword arg for constructor in int float int complex str str tuple list try constructorboguskeywordarg1 except typeerror pass else self failexpected typeerror from bogus keyword argument to r constructor def teststrsubclassasdictkeyself testing a str subclass used as dict key class cistrstr def initself value self canonical value lower self hashcode hashself canonical def eqself other if not isinstanceother cistr other cistrother return self canonical other canonical def hashself return self hashcode self assertequalcistr abc abc self assertequal abc cistr abc self assertequalstrcistr abc abc d cistr one 1 cistr two 2 cistr three 3 self assertequaldcistr one 1 self assertequaldcistr two 2 self assertequaldcistr three 3 self assertincistr one d self assertequald getcistr three 3 def testclassiccomparisonsself testing classic comparisons class classic pass for base in classic int object class cbase def initself value self value intvalue def eqself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def neself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def ltself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def leself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def gtself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def geself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented c1 c1 c2 c2 c3 c3 self assertequalc1 1 c 1 c1 2 c2 3 c3 for x in 1 2 3 for y in 1 2 3 for op in self assertequalevalcx s cy op evalx s y op xd yd x y self assertequalevalcx s y op evalx s y op xd yd x y self assertequalevalx s cy op evalx s y op xd yd x y def testrichcomparisonsself testing rich comparisons class zcomplex pass z z1 self assertequalz 10j self assertequal10j z class zzcomplex def eqself other try return absself other 1e6 except return notimplemented zz zz1 0000003 self assertequalzz 10j self assertequal10j zz class classic pass for base in classic int object list class cbase def initself value self value intvalue def cmpself other self failshouldn t call cmp def eqself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def neself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def ltself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def leself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def gtself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented def geself other if isinstanceother c return self value other value if isinstanceother int or isinstanceother int return self value other return notimplemented c1 c1 c2 c2 c3 c3 self assertequalc1 1 c 1 c1 2 c2 3 c3 for x in 1 2 3 for y in 1 2 3 for op in self assertequalevalcx s cy op evalx s y op xd yd x y self assertequalevalcx s y op evalx s y op xd yd x y self assertequalevalx s cy op evalx s y op xd yd x y def testdescrdocself testing descriptor doc strings from io import fileio def checkdescr what self assertequaldescr doc what checkfileio closed true if the file is closed getset descriptor checkcomplex real the real part of a complex number member descriptor def testdocdescriptorself testing doc descriptor sf bug 542984 class docdescrobject def getself object otype if object object object class name instance if otype otype otype name return objects types object otype class newclass doc docdescr self assertequalnewclass doc objectnone typenewclass self assertequalnewclass doc objectnewclass instance typenewclass def testsetclassself testing class assignment class cobject pass class dobject pass class eobject pass class fd e pass for cls in c d e f for cls2 in c d e f x cls x class cls2 self assertisx class cls2 x class cls self assertisx class cls def cantx c try x class c except typeerror pass else self failshouldn t allow r class r x c try delattrx class except typeerror attributeerror pass else self failshouldn t allow del r class x cantc list cantlist c cantc 1 cantc object cantobject list cantlist object class intint slots canttrue int cant2 bool o object canto int canto typenone del o class gobject slots a b class hobject slots b a class iobject slots a b class jobject slots c b class kobject slots a b d class lh slots e class mi slots e class nj slots weakref class pj slots dict class qj pass class rj slots dict weakref for cls cls2 in g h g i i h q r r q x cls x a 1 x class cls2 self assertisx class cls2 assigning r as class for r silently failed cls2 x self assertequalx a 1 x class cls self assertisx class cls assigning r as class for r silently failed cls x self assertequalx a 1 for cls in g j k l m n p r list int for cls2 in g j k l m n p r list int if cls is cls2 continue cantcls cls2 issue5283 when class changes in del the wrong type gets decref d class oobject pass class aobject def delself self class o l a for x in range100 del l def testsetdictself testing dict assignment class cobject pass a c a dict b 1 self assertequala b 1 def cantx dict try x dict dict except attributeerror typeerror pass else self failshouldn t allow r dict r x dict canta none canta canta 1 del a dict deleting dict is allowed class baseobject pass def verifydictreadonlyx cantx try del x dict except attributeerror typeerror pass else self failshouldn t allow del r dict x dictdescr base dictdict try dictdescr setx except attributeerror typeerror pass else self faildictdescr allowed access to r s dict x classes don t allow dict assignment and have readonly dicts class meta1type base pass class meta2base type pass class dobject metaclassmeta1 pass class eobject metaclassmeta2 pass for cls in c d e verifydictreadonlycls classdict cls dict try classdictspam eggs except typeerror pass else self failr s dict can be modified cls modules also disallow dict assignment class module1types moduletype base pass class module2base types moduletype pass for moduletype in module1 module2 mod moduletypespam verifydictreadonlymod mod dictspam eggs exception s dict can be replaced but not deleted at least not any more than regular exception s dict can be deleted on cpython it is not the case whereas on pypy they can just like any other newstyle instance s dict def candeletedicte try del e dict except typeerror attributeerror return false else return true class exception1exception base pass class exception2base exception pass for exceptiontype in exception exception1 exception2 e exceptiontype e dict a 1 self assertequale a 1 self assertequalcandeletedicte candeletedictvalueerror def testbinaryoperatoroverrideself testing overrides of binary operations class iint def reprself return ir intself def addself other return iintself intother radd add def powself other modnone if mod is none return ipowintself intother else return ipowintself intother intmod def rpowself other modnone if mod is none return ipowintother intself mod else return ipowintother intself intmod self assertequalrepri1 i2 i3 self assertequalrepri1 2 i3 self assertequalrepr1 i2 i3 self assertequalrepri2 i3 i8 self assertequalrepr2 i3 i8 self assertequalrepri2 3 i8 self assertequalreprpowi2 i3 i5 i3 class sstr def eqself other return self lower other lower def testsubclasspropagationself testing propagation of slot functions to subclasses class aobject pass class ba pass class ca pass class db c pass d d orighash hashd related to idd in platformdependent ways a hash lambda self 42 self assertequalhashd 42 c hash lambda self 314 self assertequalhashd 314 b hash lambda self 144 self assertequalhashd 144 d hash lambda self 100 self assertequalhashd 100 d hash none self assertraisestypeerror hash d del d hash self assertequalhashd 144 b hash none self assertraisestypeerror hash d del b hash self assertequalhashd 314 c hash none self assertraisestypeerror hash d del c hash self assertequalhashd 42 a hash none self assertraisestypeerror hash d del a hash self assertequalhashd orighash d foo 42 d bar 42 self assertequald foo 42 self assertequald bar 42 def getattributeself name if name foo return 24 return object getattributeself name a getattribute getattribute self assertequald foo 24 self assertequald bar 42 def getattrself name if name in spam foo bar return hello raise attributeerrorname b getattr getattr self assertequald spam hello self assertequald foo 24 self assertequald bar 42 del a getattribute self assertequald foo 42 del d foo self assertequald foo hello self assertequald bar 42 del b getattr try d foo except attributeerror pass else self faild foo should be undefined now test a nasty bug in recursedownsubclasses class aobject pass class ba pass del b support gccollect a setitem lambda a none crash def testbufferinheritanceself testing that buffer interface is inherited import binascii sf bug 470040 parsetuple t vs subclasses class mybytesbytes pass base b abc m mybytesbase b2ahex uses the buffer interface to get its argument s value via pyargparsetuple t code self assertequalbinascii b2ahexm binascii b2ahexbase class myintint pass m myint42 try binascii b2ahexm self fail subclass of int should not have a buffer interface except typeerror pass def teststrofstrsubclassself testing str defined in subclass of str import binascii class octetstringstr def strself return binascii b2ahexself encode ascii decodeascii def reprself return self repr o octetstring a self assertequaltypeo octetstring self assertequaltypestro str self assertequaltyperepro str self assertequalordo 0x41 self assertequalstro 41 self assertequalrepro a repr self assertequalo str 41 self assertequalo repr a repr def testreprwithmodulestrsubclassself gh98783 class strsubstr pass class some pass some module strsub example self assertisinstancereprsome str should not crash self assertisinstancereprsome str should not crash def testkeywordargumentsself testing keyword arguments to init call def fa return a self assertequalf calla42 42 ba bytearray bytearray initba abcxbdu20ac encoding latin1 errors replace self assertequalba b abcxbd def testrecursivecallself testing recursive call by setting to instance of class class aobject pass a call a with self assertraisesrecursionerror a def testdeletehookself testing del hook log class cobject def delself log append1 c c self assertequallog del c support gccollect self assertequallog 1 class dobject pass d d try del d0 except typeerror pass else self failinvalid del didn t raise typeerror def testhashinheritanceself testing hash of mutable subclasses class mydictdict pass d mydict try hashd except typeerror pass else self failhash of dict subclass should fail class mylistlist pass d mylist try hashd except typeerror pass else self failhash of list subclass should fail def teststroperationsself try a 5 except typeerror pass else self fail 5 doesn t raise typeerror try split except valueerror pass else self fail split doesn t raise valueerror try join0 except typeerror pass else self fail join0 doesn t raise typeerror try rindex 5 except valueerror pass else self fail rindex 5 doesn t raise valueerror try ns none except typeerror pass else self fail ns none doesn t raise typeerror try n except valueerror pass else self fail n doesn t raise valueerror try s abc except typeerror pass else self fail s abc doesn t raise typeerror try s abc 5 except typeerror pass else self fail s abc 5 doesn t raise typeerror try s 1 2 except typeerror pass else self fail s 1 2 doesn t raise typeerror try none except valueerror pass else self fail none doesn t raise valueerror self assertequal 534253 isdigit 1 self assertequal 534253x isdigit 0 self assertequal c 5 x05 self assertequal c 5 5 def testdeepcopyrecursiveself testing deepcopy of recursive objects class node pass a node b node a b b b a a z deepcopya this blew up before def testuninitializedmodulesself testing uninitialized module objects from types import moduletype as m m m newm strm self assertnothasattrm name self assertnothasattrm file self assertnothasattrm foo self assertfalsem dict none or are both reasonable answers m foo 1 self assertequalm dict foo 1 def testfunnynewself testing new returning something unexpected class cobject def newcls arg if isinstancearg str return 1 2 3 elif isinstancearg int return object newd else return object newcls class dc def initself arg self foo arg self assertequalc1 1 2 3 self assertequald1 1 2 3 d dnone self assertequald foo none d c1 self assertisinstanced d self assertequald foo 1 d d1 self assertisinstanced d self assertequald foo 1 class cobject staticmethod def newargs return args self assertequalc1 2 c 1 2 class dc pass self assertequald1 2 d 1 2 class cobject classmethod def newargs return args self assertequalc1 2 c c 1 2 class dc pass self assertequald1 2 d d 1 2 def testimulbugself testing for imul problems sf bug 544647 class cobject def imulself other return self other x c y x y 1 0 self assertequaly x 1 0 y x y 2 self assertequaly x 2 y x y 3 self assertequaly x 3 y x y 1100 self assertequaly x 1100 y x y none self assertequaly x none y x y foo self assertequaly x foo def testcopysetstateself testing that copy copy correctly uses setstate import copy class cobject def initself foonone self foo foo self foo foo def setfooself foonone self foo foo def getfooself return self foo def getstateself return self foo def setstateself lst self assertequallenlst 1 self foo self foo lst0 a c42 a setfoo24 self assertequala foo 24 self assertequala getfoo 42 b copy copya self assertequalb foo 24 self assertequalb getfoo 24 b copy deepcopya self assertequalb foo 24 self assertequalb getfoo 24 def testslicesself testing cases with slices and overridden getitem strings self assertequalhello 4 hell self assertequalhelloslice4 hell self assertequalstr getitemhello slice4 hell class sstr def getitemself x return str getitemself x self assertequalshello 4 hell self assertequalshelloslice4 hell self assertequalshello getitemslice4 hell tuples self assertequal1 2 3 2 1 2 self assertequal1 2 3slice2 1 2 self assertequaltuple getitem1 2 3 slice2 1 2 class ttuple def getitemself x return tuple getitemself x self assertequalt1 2 3 2 1 2 self assertequalt1 2 3slice2 1 2 self assertequalt1 2 3 getitemslice2 1 2 lists self assertequal1 2 3 2 1 2 self assertequal1 2 3slice2 1 2 self assertequallist getitem1 2 3 slice2 1 2 class llist def getitemself x return list getitemself x self assertequall1 2 3 2 1 2 self assertequall1 2 3slice2 1 2 self assertequall1 2 3 getitemslice2 1 2 now do lists and setitem a l1 2 3 aslice1 3 3 2 self assertequala 1 3 2 aslice0 2 1 3 1 self assertequala 3 1 2 a setitemslice1 3 2 1 self assertequala 3 2 1 a setitemslice0 2 1 2 3 self assertequala 2 3 1 def testsubtyperesurrectionself testing resurrection of newstyle instance class cobject container def delself resurrect the instance c container appendself c c c attr 42 the most interesting thing here is whether this blows up due to flawed gc tracking logic in typeobject c s callfinalizer a 2 2 1 bug del c support gccollect self assertequallenc container 1 make c mortal again so that the test framework with l doesn t report it as a leak del c del def testslotstrashself testing slot trash deallocating deeply nested slotted trash caused stack overflows class trashobject slots x def initself x self x x o none for i in range50000 o trasho del o def testslotsmultipleinheritanceself sf bug 575229 multiple inheritance w slots dumps core class aobject slots class bobject pass class ca b slots if support checkimpldetail self assertequalc basicsize b basicsize self asserthasattrc dict self asserthasattrc weakref c x 2 def testrmulself testing correct invocation of rmul sf patch 592646 class cobject def mulself other return mul def rmulself other return rmul a c self assertequala2 mul self assertequala2 2 mul self assertequal2a rmul self assertequal2 2a rmul def testipowself testing correct invocation of ipow sf bug 620179 class cobject def ipowself other pass a c a 2 def testipowreturnsnotimplementedself class a def ipowself other return notimplemented class ba def rpowself other return 1 class ca def powself other return 2 a a b b c c a b self assertequala 1 c b self assertequalc 2 def testnoipowself class b def rpowself other return 1 a object b b a b self assertequala 1 def testipowexceptiontextself x none with self assertraisestypeerror as cm x 2 self assertin unsupported operand types for strcm exception with self assertraisestypeerror as cm y x 2 self assertin unsupported operand types for strcm exception def testmutablebasesself testing mutable bases stuff that should work class cobject pass class c2object def getattributeself attr if attr a return 2 else return superc2 self getattributeattr def methself return 1 class dc pass class ed pass d d e e d bases c d bases c2 self assertequald meth 1 self assertequale meth 1 self assertequald a 2 self assertequale a 2 self assertequalc2 subclasses d try del d bases except typeerror attributeerror pass else self failshouldn t be able to delete bases try d bases except typeerror as msg if strmsg a newstyle class can t have only classic bases self failwrong error message for bases else self failshouldn t be able to set bases to try d bases d except typeerror pass else actually we ll have crashed by here self failshouldn t be able to create inheritance cycles try d bases c c except typeerror pass else self faildidn t detect repeated base classes try d bases e except typeerror pass else self failshouldn t be able to create inheritance cycles def testbuiltinbasesself make sure all the builtin types can have their base queried without segfaulting see issue 5787 builtintypes tp for tp in builtins dict values if isinstancetp type for tp in builtintypes object getattributetp bases if tp is not object if tp is exceptiongroup numbases 2 else numbases 1 self assertequallentp bases numbases tp class llist pass class cobject pass class dc pass try l bases dict except typeerror pass else self failshouldn t turn list subclass into dict subclass try list bases dict except typeerror pass else self failshouldn t be able to assign to list bases try d bases c list except typeerror pass else self failbestbase calculation found wanting def testunsubclassabletypesself with self assertraisestypeerror class xtypenone pass with self assertraisestypeerror class xobject typenone pass with self assertraisestypeerror class xtypenone object pass class oobject pass with self assertraisestypeerror class xo typenone pass with self assertraisestypeerror class xtypenone o pass class xobject pass with self assertraisestypeerror x bases typenone with self assertraisestypeerror x bases object typenone with self assertraisestypeerror x bases typenone object with self assertraisestypeerror x bases o typenone with self assertraisestypeerror x bases typenone o def testmutablebaseswithfailingmroself testing mutable bases with failing mro class workoncetype def newself name bases ns self flag 0 return superworkonce self newworkonce name bases ns def mroself if self flag 0 raise runtimeerrorbozo else self flag 1 return type mroself class workalwaystype def mroself this is here to make sure that mros aren t called with an exception set which was possible at one point an error message will be printed in a debug build what s a good way to test for this return type mroself class cobject pass class c2object pass class dc pass class ed pass class fd metaclassworkonce pass class gd metaclassworkalways pass immediate subclasses have their mro s adjusted in alphabetical order so e s will get adjusted before adjusting f s fails we check here that e s gets restored emrobefore e mro dmrobefore d mro try d bases c2 except runtimeerror self assertequale mro emrobefore self assertequald mro dmrobefore else self failexception not propagated def testmutablebasescatchmroconflictself testing mutable bases catch mro conflict class aobject pass class bobject pass class ca b pass class da b pass class ec d pass try c bases b a except typeerror pass else self faildidn t catch mro conflict def testmutablenamesself testing mutable names class cobject pass c module could be testdescr or main mod c module c name d self assertequalc module c name mod d c name d e self assertequalc module c name mod d e def testeviltypenameself a badly placed pydecref in typesetname led to arbitrary code execution while the type structure was not in a sane state and a possible segmentation fault as a result see bug 16447 class nastystr def delself c name other class c pass c name nastyabc c name normal def testsubclassrightopself testing correct dispatch of subclass overloading rop this code tests various cases where rightdispatch of a subclass should be preferred over leftdispatch of a base class case 1 subclass of int this tests code in abstract c binaryop1 class bint def floordivself other return b floordiv def rfloordivself other return b rfloordiv self assertequalb1 1 b floordiv self assertequal1 b1 b rfloordiv case 2 subclass of object this is just the baseline for case 3 class cobject def floordivself other return c floordiv def rfloordivself other return c rfloordiv self assertequalc 1 c floordiv self assertequal1 c c rfloordiv case 3 subclass of newstyle class here it gets interesting class dc def floordivself other return d floordiv def rfloordivself other return d rfloordiv self assertequald c d floordiv self assertequalc d d rfloordiv case 4 this didn t work right in 2 2 2 and 2 3a1 class ec pass self assertequale rfloordiv c rfloordiv self assertequale 1 c floordiv self assertequal1 e c rfloordiv self assertequale c c floordiv self assertequalc e c floordiv this one would fail support impldetailtesting an internal kind of method object def testmethclassgetself testing get method of methclass c methods full coverage of descrobject c classmethodget baseline arg 1 2 3 res 1 none 2 none 3 none self assertequaldict fromkeysarg res self assertequal fromkeysarg res now get the descriptor descr dict dictfromkeys more baseline using the descriptor directly self assertequaldescr getnone dictarg res self assertequaldescr getarg res now check various error cases try descr getnone none except typeerror pass else self failshouldn t have allowed descr getnone none try descr get42 except typeerror pass else self failshouldn t have allowed descr get42 try descr getnone 42 except typeerror pass else self failshouldn t have allowed descr getnone 42 try descr getnone int except typeerror pass else self failshouldn t have allowed descr getnone int def testisinstisclassself testing proxy isinstance and isclass class proxyobject def initself obj self obj obj def getattributeself name if name startswithproxy return object getattributeself name else return getattrself obj name test with a classic class class c pass a c pa proxya self assertisinstancea c baseline self assertisinstancepa c test test with a classic subclass class dc pass a d pa proxya self assertisinstancea c baseline self assertisinstancepa c test test with a newstyle class class cobject pass a c pa proxya self assertisinstancea c baseline self assertisinstancepa c test test with a newstyle subclass class dc pass a d pa proxya self assertisinstancea c baseline self assertisinstancepa c test def testproxysuperself testing super for a proxy object class proxyobject def initself obj self obj obj def getattributeself name if name startswithproxy return object getattributeself name else return getattrself obj name class bobject def fself return b f class cb def fself return superc self f c f obj c p proxyobj self assertequalc dictfp b fc f def testcarloverreself testing prohibition of carlo verre s hack try object setattrstr foo 42 except typeerror pass else self failcarlo verre setattr succeeded try object delattrstr lower except typeerror pass else self failcarlo verre delattr succeeded def testcarloverremultiinheritvalidself class atype def setattrcls key value type setattrcls key value class b pass class cb a pass obj c d object try obj test true except typeerror self failsetattr through direct base types should be legal def testcarloverremultiinheritinvalidself class atype def setattrcls key value object setattrcls key value this should fail class b pass class cb a pass obj c d object try obj test true except typeerror pass else self failsetattr through indirect base types should be rejected def testweakrefsegfaultself testing weakref segfault sf 742911 import weakref class provoker def initself referrent self ref weakref refreferrent def delself x self ref class oopsobject pass o oops o whatever provokero del o support requiresresource cpu def testwrappersegfaultself sf 927248 deeply nested wrappers could cause stack overflow f lambda none for i in range1000000 f f call f none def testfilefaultself testing sys stdout is changed in getattr class stdoutguard def getattrself attr sys stdout sys stdout raise runtimeerrorfpremature access to sys stdout attr with redirectstdoutstdoutguard with self assertraisesruntimeerror printoops def testviciousdescriptornonsenseself testing viciousdescriptornonsense a potential segfault spotted by thomas wouters in mail to pythondev 20030417 turned into an example fixed by michael hudson just less than four months later class evilobject def hashself return hash attr def eqself other try del c attr except attributeerror possible race condition pass return 0 class descrobject def getself ob typenone return 1 class cobject attr descr c c c dictevil 0 self assertequalc attr 1 this makes a crash more likely support gccollect self assertnothasattrc attr def testinitself sf 1155938 class fooobject def initself return 10 try foo except typeerror pass else self faildid not test init for none return def assertnotorderableself a b with self assertraisestypeerror a b with self assertraisestypeerror a b with self assertraisestypeerror a b with self assertraisestypeerror a b def testmethodwrapperself testing methodwrapper objects type methodwrapper did not support any reflection before 2 5 l self asserttruel add l add self assertfalsel add l add self assertfalsel add add self asserttruel add add self assertfalsel add l mul self asserttruel add l mul self assertnotorderablel add l add self assertequall add name add self assertisl add self l self assertisl add objclass list self assertequall add doc list add doc hash add should not be based on hash hashl add def testbuiltinfunctionormethodself not really belonging to testdescr but introspection and comparison on type builtinfunctionormethod seems not to be tested elsewhere l self asserttruel append l append self assertfalsel append l append self assertfalsel append append self asserttruel append append self assertfalsel append l pop self asserttruel append l pop self assertnotorderablel append l append self assertequall append name append self assertisl append self l self assertisl append objclass list could be added self assertequall append doc list append doc hash append should not be based on hash hashl append def testspecialunboundmethodtypesself testing objects of type wrapperdescriptor self asserttruelist add list add self assertfalselist add list add self assertfalselist add list mul self asserttruelist add list mul self assertnotorderablelist add list add self assertequallist add name add self assertislist add objclass list testing objects of type methoddescriptor self asserttruelist append list append self assertfalselist append list append self assertfalselist append list pop self asserttruelist append list pop self assertnotorderablelist append list append self assertequallist append name append self assertislist append objclass list def testnotimplementedself testing notimplemented all binary methods should be able to return a notimplemented import operator def specialmethodself other return notimplemented def checkexpr x y try execexpr x x y y operator operator except typeerror pass else self failno typeerror from r expr n1 sys maxsize 1 might trigger overflowerrors instead of typeerrors n2 sys maxsize if sizeofint sizeoflong might trigger valueerrors instead of typeerrors for name expr iexpr in add x y x y sub x y x y mul x y x y matmul x y x y truediv x y x y floordiv x y x y mod x y x y divmod divmodx y none pow x y x y lshift x y x y rshift x y x y and x y x y or x y x y xor x y x y rname r name2 a type a name specialmethod a a checkexpr a a checkexpr a n1 checkexpr a n2 if iexpr checkiexpr a a checkiexpr a n1 checkiexpr a n2 iname i name2 c type c iname specialmethod c c checkiexpr c a checkiexpr c n1 checkiexpr c n2 def testassignsliceself ceval c s assignslice used to check for tptpassequencesqslice instead of tptpassequencesqassslice class cobject def setitemself idx value self value value c c c1 2 3 self assertequalc value 3 def testsetandnogetself see http mail python orgpipermailpythondev2010january095637 html class descrobject def initself name self name name def setself obj value obj dictself name value descr descra class xobject a descr x x self assertisx a descr x a 42 self assertequalx a 42 also check typegetattro for correctness class metatype pass class xmetaclassmeta pass x a 42 meta a descra self assertequalx a 42 def testgetattrhooksself issue 4230 class descriptorobject counter 0 def getself obj objtypenone def gettername self counter 1 raise attributeerrorname return getter descr descriptor class aobject getattribute descr class bobject getattr descr class cobject getattribute descr getattr descr self assertraisesattributeerror getattr a attr self assertequaldescr counter 1 self assertraisesattributeerror getattr b attr self assertequaldescr counter 2 self assertraisesattributeerror getattr c attr self assertequaldescr counter 4 class evilgetattributeobject this used to segfault def getattrself name raise attributeerrorname def getattributeself name del evilgetattribute getattr for i in range5 gc collect raise attributeerrorname self assertraisesattributeerror getattr evilgetattribute attr def testtypegetattributeself self assertraisestypeerror type getattribute list type def testabstractmethodsself type pretends not to have abstractmethods self assertraisesattributeerror getattr type abstractmethods class metatype pass self assertraisesattributeerror getattr meta abstractmethods class xobject pass with self assertraisesattributeerror del x abstractmethods def testproxycallself class fakestr class str fakestr fakestr isinstance reads class self assertisinstancefakestr str call a method descriptor with self assertraisestypeerror str splitfakestr call a slot wrapper descriptor with self assertraisestypeerror str addfakestr abc def testspecializedmethodcallschecktypesself https github compythoncpythonissues92063 class thing pass thing thing for i in range20 with self assertraisestypeerror callmethoddescriptorfastwithkeywords list sortthing for i in range20 with self assertraisestypeerror callmethoddescriptorfastwithkeywords str splitthing for i in range20 with self assertraisestypeerror callmethoddescriptornoargs str upperthing for i in range20 with self assertraisestypeerror callmethoddescriptorfast str stripthing from collections import deque for i in range20 with self assertraisestypeerror callmethoddescriptoro deque appendthing thing def testreprasstrself issue 11603 crash or infinite loop when rebinding str as repr class foo pass foo repr foo str foo foo self assertraisesrecursionerror str foo self assertraisesrecursionerror repr foo def testmixingslotwrappersself class xdict setattr dict setitem neg dict copy x x x y 42 self assertequalxy 42 self assertequalx x def testwrongclassslotwrapperself check bpo37619 a wrapper descriptor taken from the wrong class should raise an exception instead of silently being ignored class aint eq str eq add str add a a with self assertraisestypeerror a a with self assertraisestypeerror a a def testslotshadowsclassvariableself with self assertraisesvalueerror as cm class x slots foo foo none m strcm exception self assertequal foo in slots conflicts with class variable m def testsetdocself class x elephant x doc banana self assertequalx doc banana with self assertraisestypeerror as cm typelist dictdoc setlist blah self assertincannot set doc attribute of immutable type list strcm exception with self assertraisestypeerror as cm typex dictdoc deletex self assertincannot delete doc attribute of immutable type x strcm exception self assertequalx doc banana def testqualnameself descriptors str lower complex real float real int add types method member getset wrapper make sure we have an example of each type of descriptor for d n in zipdescriptors types self assertequaltyped name n descriptor for d in descriptors qualname d objclass qualname d name self assertequald qualname qualname self assertequalstr lower qualname str lower self assertequalcomplex real qualname complex real self assertequalfloat real qualname float real self assertequalint add qualname int add class x pass with self assertraisestypeerror del x qualname self assertraisestypeerror type dict qualname set str oink global y class y class inside pass self assertequaly qualname y self assertequaly inside qualname y inside def testqualnamedictself ns qualname some name tp type foo ns self assertequaltp qualname some name self assertnotin qualname tp dict self assertequalns qualname some name ns qualname 1 self assertraisestypeerror type foo ns def testcyclethroughdictself see bug 1469629 class xdict def initself dict initself self dict self x x x attr 42 wr weakref refx del x support gccollect self assertisnonewr for o in gc getobjects self assertisnottypeo x def testobjectnewandinitwithparametersself see issue 1683368 class overrideneither pass self assertraisestypeerror overrideneither 1 self assertraisestypeerror overrideneither kw1 class overridenew def newcls foo kw0 args kwds return object newcls args kwds class overrideinit def initself foo kw0 args kwargs return object initself args kwargs class overridebothoverridenew overrideinit pass for case in overridenew overrideinit overrideboth case1 case1 kw2 self assertraisestypeerror case 1 2 3 self assertraisestypeerror case 1 2 foo3 def testsubclassingdoesnotduplicatedictdescriptorsself class base pass class subbase pass self assertindict base dict self assertnotindict sub dict def testboundmethodreprself class foo def methodself pass self assertregexreprfoo method rbound method foo method of foo object at class base def methodself pass class derived1base pass class derived2base def methodself pass base base derived1 derived1 derived2 derived2 superd2 superderived2 derived2 self assertregexreprbase method rbound method base method of base object at self assertregexreprderived1 method rbound method base method of derived1 object at self assertregexreprderived2 method rbound method derived2 method of derived2 object at self assertregexreprsuperd2 method rbound method base method of derived2 object at class foo classmethod def methodcls pass foo foo self assertregexreprfoo method access via instance rbound method foo method of class foo self assertregexreprfoo method access via the class rbound method foo method of class foo class mycallable def callself arg pass func mycallable func has no name or qualname attributes instance object method types methodtypefunc instance self assertregexreprmethod rbound method of object object at func name name self assertregexreprmethod rbound method name of object object at func qualname qualname self assertregexreprmethod rbound method qualname of object object at unittest skipiftestcapi is none need the testcapi module def testbpo25750self bpo25750 calling a descriptor implemented as builtin function with methfastcall should not crash cpython if the descriptor deletes itself from the class class descr get testcapi badget class x descr descr def newcls cls descr none create this large list to corrupt some unused memory cls lst 2i for i in range10000 x descr def testremovesubclassself bpo46417 when the last subclass of a type is deleted removesubclass clears the internal dictionary of subclasses set pytypeobject tpsubclasses to null removesubclass is called when a type is deallocated class parent pass self assertequalparent subclasses class childparent pass self assertequalparent subclasses child del child gc collect self assertequalparent subclasses def testattrraisethroughpropertyself test case for gh103272 class a def getattrself name raise valueerrorfoo property def fooself return self getattrasdf with self assertraisesregexvalueerror foo a foo test case for gh103551 class b property def getattrself name raise valueerrorfoo property def fooself raise notimplementederrorbar with self assertraisesregexnotimplementederror bar b foo class dictproxytestsunittest testcase def setupself class cobject def methself pass self c c unittest skipifhasattrsys gettrace and sys gettrace trace function introduces local def testiterkeysself testing dictproxy keys it self c dict keys self assertnotisinstanceit list keys listit keys sort self assertequalkeys dict doc module weakref meth unittest skipifhasattrsys gettrace and sys gettrace trace function introduces local def testitervaluesself testing dictproxy values it self c dict values self assertnotisinstanceit list values listit self assertequallenvalues 5 unittest skipifhasattrsys gettrace and sys gettrace trace function introduces local def testiteritemsself testing dictproxy iteritems it self c dict items self assertnotisinstanceit list keys item0 for item in it keys sort self assertequalkeys dict doc module weakref meth def testdicttypewithmetaclassself testing type of dict when metaclass set class bobject pass class mtype pass class cmetaclassm in 2 3a1 c dict was a real dict rather than a dict proxy pass self assertequaltypec dict typeb dict def testreprself testing mappingproxy repr we can t blindly compare with the repr of another dict as ordering of keys and values is arbitrary and may differ r reprself c dict self asserttruer startswith mappingproxy r self asserttruer endswith r for k v in self c dict items self assertin r r formatk v r class aaaptypeslonginittestunittest testcase this is in its own testcase so that it can be run before any other tests hence the aaa in the test class name to make it the first item in a list sorted by name like unittest testloader gettestcasenames does def testpytypelongreadyself testing sf bug 551412 this dumps core when sf bug 551412 isn t fixed but only when testdescr py is run separately that can t be helped as soon as pytypeready is called for pylongtype the bug is gone class userlongobject def powself args pass try pow0 userlong 0 except pass another segfault only when run early before pytypereadytuple is called type mrotuple class misctestsunittest testcase def testtypelookupmroreferenceself issue 14199 pytypelookup has to keep a strong reference to the type mro because it may be modified during the lookup if bases is set during the lookup for example class mykeyobject def hashself return hash mykey def eqself other x bases base2 class baseobject mykey from base mykey2 from base class base2object mykey from base2 mykey2 from base2 x type x base mykey 5 mykey is read from base self assertequalx mykey from base mykey2 is read from base2 because mykey eq has set bases self assertequalx mykey2 from base2 class picklingtestsunittest testcase def checkreduceself proto obj args kwargs statenone listitemsnone dictitemsnone if proto 2 reducevalue obj reduceexproto if kwargs self assertequalreducevalue0 copyreg newobjex self assertequalreducevalue1 typeobj args kwargs else self assertequalreducevalue0 copyreg newobj self assertequalreducevalue1 typeobj args self assertequalreducevalue2 state if listitems is not none self assertlistequallistreducevalue3 listitems else self assertisnonereducevalue3 if dictitems is not none self assertdictequaldictreducevalue4 dictitems else self assertisnonereducevalue4 else basetype typeobj base reducevalue copyreg reconstructor typeobj basetype none if basetype is object else basetypeobj if state is not none reducevalue state self assertequalobj reduceexproto reducevalue self assertequalobj reduce reducevalue def testreduceself protocols rangepickle highestprotocol 1 args 101 spam kwargs bacon 201 fish 301 state cheese 401 class c1 def getnewargsself return args obj c1 for proto in protocols self checkreduceproto obj args for name value in state items setattrobj name value for proto in protocols self checkreduceproto obj args statestate class c2 def getnewargsself return bad args obj c2 for proto in protocols if proto 2 with self assertraisestypeerror obj reduceexproto class c3 def getnewargsexself return args kwargs obj c3 for proto in protocols if proto 2 self checkreduceproto obj args kwargs class c4 def getnewargsexself return args bad dict class c5 def getnewargsexself return bad tuple kwargs class c6 def getnewargsexself return class c7 def getnewargsexself return bad args for proto in protocols for cls in c4 c5 c6 c7 obj cls if proto 2 with self assertraisestypeerror valueerror obj reduceexproto class c9 def getnewargsexself return args obj c9 for proto in protocols self checkreduceproto obj args class c10 def getnewargsexself raise indexerror obj c10 for proto in protocols if proto 2 with self assertraisesindexerror obj reduceexproto class c11 def getstateself return state obj c11 for proto in protocols self checkreduceproto obj statestate class c12 def getstateself return not dict obj c12 for proto in protocols self checkreduceproto obj statenot dict class c13 def getstateself raise indexerror obj c13 for proto in protocols with self assertraisesindexerror obj reduceexproto if proto 2 with self assertraisesindexerror obj reduce class c14 slots tuplestate def initself for name value in state items setattrself name value obj c14 for proto in protocols if proto 2 self checkreduceproto obj statenone state else with self assertraisestypeerror obj reduceexproto with self assertraisestypeerror obj reduce class c15dict pass obj c15quebec 601 for proto in protocols self checkreduceproto obj dictitemsdictobj class c16list pass obj c16yukon for proto in protocols self checkreduceproto obj listitemslistobj def testspecialmethodlookupself protocols rangepickle highestprotocol 1 class picky def getstateself return def getattrself attr if attr in getnewargs getnewargsex raise assertionerrorattr return none for protocol in protocols state if protocol 2 else none self checkreduceprotocol picky statestate def assertiscopyself obj objcopy msgnone if msg is none msg r is not a copy of r formatobj objcopy if typeobj repr is object repr we have this limitation for now because we use the object s repr to help us verify that the two objects are copies this allows us to delegate the nongeneric verification logic to the objects themselves raise valueerrorobject passed to assertiscopy must override the repr method self assertisnotobj objcopy msgmsg self assertistypeobj typeobjcopy msgmsg if hasattrobj dict self assertdictequalobj dict objcopy dict msgmsg self assertisnotobj dict objcopy dict msgmsg if hasattrobj slots self assertlistequalobj slots objcopy slots msgmsg for slot in obj slots self assertequal hasattrobj slot hasattrobjcopy slot msgmsg self assertequalgetattrobj slot none getattrobjcopy slot none msgmsg self assertequalreprobj reprobjcopy msgmsg staticmethod def generatepicklecopiers class picklecopier this class copies object using pickle def initself proto dumps loads self proto proto self dumps dumps self loads loads def copyself obj return self loadsself dumpsobj self proto def reprself we try to be as descriptive as possible here since this is the string which we will allow us to tell the pickle configuration we are using during debugging return picklecopierproto dumps loads formatself proto self dumps module self dumps qualname self loads module self loads qualname return picklecopierargs for args in itertools productrangepickle highestprotocol 1 pickle dumps pickle dumps pickle loads pickle loads def testpickleslotsself tests pickling of classes with slots pickling of classes with slots but without getstate should fail if using protocol 0 or 1 global c class c slots a with self assertraisestypeerror pickle dumpsc 0 global d class dc pass with self assertraisestypeerror pickle dumpsd 0 class c a class with getstate and setstate implemented slots a def getstateself state getattrself dict copy for cls in typeself mro for slot in cls dict get slots try stateslot getattrself slot except attributeerror pass return state def setstateself state for k v in state items setattrself k v def reprself return sr typeself name self getstate class dc a subclass of a class with slots pass global e class ec a subclass with an extra slot slots b now it should work for picklecopier in self generatepicklecopiers with self subtestpicklecopierpicklecopier x c y picklecopier copyx self assertiscopyx y x a 42 y picklecopier copyx self assertiscopyx y x d x a 42 x b 100 y picklecopier copyx self assertiscopyx y x e x a 42 x b foo y picklecopier copyx self assertiscopyx y def testreducecopyingself tests pickling and copying newstyle classes and objects global c1 class c1 the state of this class is copyable via its instance dict args 1 2 needdictcopying true def initself a b super init self a a self b b def reprself return c1r r self a self b global c2 class c2list a list subclass copyable via getnewargs args 1 2 needdictcopying false def newcls a b self super newcls self a a self b b return self def initself args super init this helps testing that init is not called during the unpickling process which would cause extra appends self appendcheese classmethod def getnewargscls return cls args def reprself return c2r rr self a self b listself global c3 class c3list a list subclass copyable via getstate args 1 2 needdictcopying false def initself a b self a a self b b this helps testing that init is not called during the unpickling process which would cause extra appends self appendcheese classmethod def getstatecls return cls args def setstateself state a b state self a a self b b def reprself return c3r rr self a self b listself global c4 class c4int an int subclass copyable via getnewargs args hello world 1 needdictcopying false def newcls a b value self super newcls value self a a self b b return self classmethod def getnewargscls return cls args def reprself return c4r rr self a self b intself global c5 class c5int an int subclass copyable via getnewargsex args 1 2 kwargs value 3 needdictcopying false def newcls a b value0 self super newcls value self a a self b b return self classmethod def getnewargsexcls return cls args cls kwargs def reprself return c5r rr self a self b intself testclasses c1 c2 c3 c4 c5 testing copying through pickle picklecopiers self generatepicklecopiers for cls picklecopier in itertools producttestclasses picklecopiers with self subtestclscls picklecopierpicklecopier kwargs getattrcls kwargs obj clscls args kwargs proto picklecopier proto objcopy picklecopier copyobj self assertiscopyobj objcopy for test classes that supports this make sure we didn t go around the reduce protocol by simply copying the attribute dictionary we clear attributes using the previous copy to not mutate the original argument if proto 2 and not cls needdictcopying objcopy dict clear objcopy2 picklecopier copyobjcopy self assertiscopyobj objcopy2 testing copying through copy deepcopy for cls in testclasses with self subtestclscls kwargs getattrcls kwargs obj clscls args kwargs objcopy deepcopyobj self assertiscopyobj objcopy for test classes that supports this make sure we didn t go around the reduce protocol by simply copying the attribute dictionary we clear attributes using the previous copy to not mutate the original argument if not cls needdictcopying objcopy dict clear objcopy2 deepcopyobjcopy self assertiscopyobj objcopy2 def testissue24097self slot name is freed inside getattr and is later used class sstr not interned pass class a slotnames s spam def getattrself attr if attr spam a slotnames s spam return 42 else raise attributeerror import copyreg expected copyreg newobj a none spam 42 none none self assertequala reduceex2 expected shouldn t crash def testobjectreduceself issue 29914 reduce takes no arguments object reduce with self assertraisestypeerror object reduce0 reduceex takes one integer argument object reduceex0 with self assertraisestypeerror object reduceex with self assertraisestypeerror object reduceexnone class sharedkeytestsunittest testcase support cpythononly def testsubclassesself verify that subclasses can share keys per pep 412 class a pass class ba pass shrink keys by repeatedly creating instances a b for in range30 a b a b self assertequalsys getsizeofvarsa sys getsizeofvarsb self assertlesssys getsizeofvarsa sys getsizeofa 1 initial hash table can contain only one or two elements set 6 attributes to cause internal resizing a x a y a z a w a v a u range6 self assertnotequalsys getsizeofvarsa sys getsizeofvarsb a2 a self assertgreatersys getsizeofvarsa sys getsizeofvarsa2 self assertlesssys getsizeofvarsa2 sys getsizeofa 1 self assertlesssys getsizeofvarsb sys getsizeofa 1 class debughelpermetatype def newmcls name bases attrs if attrs get doc is none attrs doc name helps when debugging with gdb return type newmcls name bases attrs def reprcls return reprcls name class mrotestunittest testcase def setupself self step 0 self ready false def stepuntilself limit ret self step limit if ret self step 1 return ret def testincompletesetbasesonselfself class mdebughelpermeta def mrocls if self stepuntil1 assert cls mro is none cls bases return type mrocls class ametaclassm pass def testreentsetbasesonbaseself class mdebughelpermeta def mrocls if cls mro is not none and cls name b 45 steps are usually enough to make it crash somewhere if self stepuntil10 a bases return type mrocls class ametaclassm pass class ba pass b bases def testreentsetbasesondirectbaseself class mdebughelpermeta def mrocls base cls bases0 if base is not object if self stepuntil5 base bases return type mrocls class ametaclassm pass class ba pass class cb pass def testreentsetbasestpbasecycleself class mdebughelpermeta def mrocls if self ready if cls name b1 b2 bases b1 if cls name b2 b1 bases b2 return type mrocls class ametaclassm pass class b1a pass class b2a pass self ready true with self assertraisestypeerror b1 bases def testtpsubclassescycleinupdateslotsself class mdebughelpermeta def mrocls if self ready and cls name c self ready false c bases b2 return type mrocls class ametaclassm pass class b1a pass class b2a pass class ca pass self ready true c bases b1 b1 bases c self assertequalc bases b2 self assertequalb2 subclasses c self assertequalb1 subclasses self assertequalb1 bases c self assertequalc subclasses b1 def testtpsubclassescycleerrorreturnpathself class eexception pass class mdebughelpermeta def mrocls if self ready and cls name c if c bases b2 self ready false else c bases b2 raise e return type mrocls class ametaclassm pass class b1a pass class b2a pass class ca pass self ready true with self assertraisese c bases b1 b1 bases c self assertequalc bases b2 self assertequalc mro tupletype mroc def testincompleteextendself class mdebughelpermeta def mrocls if cls mro is none and cls name x with self assertraisestypeerror class xcls pass return type mrocls class ametaclassm pass def testincompletesuperself class mdebughelpermeta def mrocls if cls mro is none with self assertraisesattributeerror supercls cls xxx return type mrocls class ametaclassm pass def testdisappearingcustommroself class b pass class mdebughelpermeta def mrocls del m mro return b with self assertraisestypeerror class ametaclassm pass if name main unittest main find method in parent class in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function in some implementations e g pypy m can be a regular unbound method object the getattr below obtains its underlying function testing list operations asserts are within individual test methods testing dict operations tests for unary and binary operators testing int operations the following crashes in python 2 2 this returns notimplemented in python 2 2 testing float operations testing complex operations see issue 9930 testing spamlist operations this is an ugly hack test subclassing testing spamdict operations this is an ugly hack test subclassing testing python subclass of dict testing python subclass of list testing metaclasses early binding of methods more metaclass examples automatically add __super to the class this trick only works for dynamic classes name mangling for __super removes leading underscores automatically create property attributes when methods named _get_x and or _set_x are found merge of multiple cooperating metaclasses make sure type x doesn t call x __class__ __init__ testing code to find most derived baseclass the most derived metaclass of d is a rather than type issue1294232 correct metaclass calculation to check the order of __new__ calls bmeta __new__ calls ameta __new__ with super the most derived metaclass is bmeta bmeta __prepare__ should ve been called the order of the bases shouldn t matter check correct metaclass calculation when a metaclass is declared special case the given metaclass isn t a class so there is no metaclass calculation the given metaclass is a class but not a descendant of type to track __prepare__ calls this is a typeerror because of a metaclass conflict bnotmeta is neither a subclass nor a superclass of type typeerror bnotmeta is neither a subclass nor a superclass of int testing python subclass of module https bugs python org issue1174712 issue 34805 verify that definition order is retained testing multiple inheritance sf bug 442833 testing multiple inheritance special cases mro order disagreement see thread python dev 2002 october 029035 html testing ex5 from c3 switch discussion see a monotonic superclass linearization for dylan by kim barrett et al oopsla 1996 testing mro monotonicity see a monotonic superclass linearization for dylan by kim barrett et al oopsla 1996 testing consistency with epg testing error messages for mro disagreement the exact msg is generally considered an impl detail test some very simple errors test a slightly more complex error testing object class make sure that builtin immutable objects don t support __class__ assignment because the object instances may be interned we set __slots__ to ensure that the subclasses are memory layout compatible and thus otherwise reasonable candidates for __class__ assignment the following types have immutable instances but are not subclassable and thus don t need to be checked nonetype bool testing __slots__ validate name mangling make sure slot names are proper identifiers xxx nnorwitz was there supposed to be something tested from the class above test a single string is not expanded as a sequence test unicode slot names test a single unicode string is not expanded as a sequence _unicode_to_string used to modify slots in certain circumstances this used to leak references test leaks counts the number of instances alive test cyclical leaks sf bug 519621 test lookup leaks sf bug 572567 inherit from object on purpose to check some backwards compatibility paths test string subclass in __slots__ see gh 98783 testing __dict__ and __weakref__ in __slots__ testing __qualname__ and __classcell__ in __slots__ issue2115 slot descriptors did not correctly check the type of the given object this used to crash testing class attribute propagation test that dynamic attributes are inherited test dynamic instances test handling of int seq and seq int test comparison of classes with dynamic metaclasses testing errors testing class methods test for a specific crash sf bug 528132 test super with classmethods sf bug 535444 verify that a non callable will raise verify that classmethod doesn t allow keyword args testing c based class methods testing static methods testing c based static methods testing classic classes not subclassing from c i e unbound testing computed attributes testing __new__ slot override testing mro and overriding it in cpython the class creation above already raises typeerror as a protection against the fact that instances of x would segfault it in other python implementations it would be ok to let the class x be created but instead get a clean typeerror on the __setitem__ below testing operator overloading https github com python cpython issues 91625 warm up the function for quickening pep 659 testing methods i e unbound this test checks error messages in builtin method descriptor it is allowed that other python implementations use different error messages the lookup of special methods bypasses __getattr__ and __getattribute__ but they still can be descriptors it would be nice to have every special method tested here but i m only listing the ones i can remember outside of typeobject c since it does it right testing special operators test operators like __hash__ for which a built in default exists test the default behavior for static classes note that the module name appears in str repr and that varies depending on whether this test is run standalone or from a framework test the default behavior for dynamic classes note that the module name appears in str repr and that varies depending on whether this test is run standalone or from a framework test overridden behavior testing weak references testing property this segfaulted in 2 5b2 testing dict constructor it s a sequence and its elements are also sequences gotta love strings wink but they aren t of length 2 so this one seemed better as a valueerror than a typeerror lacks a keys method will be added later init from sequence of iterable objects each producing a 2 sequence bad sequence lengths testing dir just make sure these don t blow up test dir on new style classes since these have object as a base class a lot more gets sucked in self assertin __self__ dir c cmethod self assertin __self__ dir c cmethod self assertin __self__ dir a amethod self assertin __self__ dir a amethod try a module subclass two essentially featureless objects ellipsis just inherits stuff from object nasty test case for proxied objects this used to segfault testing super test for subclassing super mysuper f self make sure certain errors are raised make sure data descriptors can be overridden and accessed via super new feature in python 2 3 ensure that super lookup of descriptor from classmethod works sf id 743627 verify that super doesn t allow keyword args testing inheritance from basic types note that overriding __radd__ doesn t work because the int type gets first dibs note that overriding __radd__ here only seems to work because the example uses a short int left argument because octlong overrides __add__ we can t check the absence of 0 optimizations using octlong check that negative clones don t segfault self asserttrue pynumber_long copies the sign bit just trying another form of the constructor class countedinput file counts lines read by self readline self lineno is the 0 based ordinal of the last line read up to a maximum of one greater than the number of lines in the file self ateof is true if and only if the final line has been read at which point self lineno stops incrementing and further calls to readline continue to return lineno 0 ateof 0 def readline self if self ateof return s file readline self next line works too s super countedinput self readline self lineno 1 if s self ateof 1 return s f file name os_helper testfn mode w lines a n b n c n try f writelines lines f close f countedinput os_helper testfn for i expected in zip range 1 5 4 lines 2 got f readline self assertequal expected got self assertequal f lineno i self assertequal f ateof i len lines f close finally try f close except pass os_helper unlink os_helper testfn testing keyword args to basic type constructors note as of python 2 3 dict no longer has an items keyword arg testing a str subclass used as dict key subclass of str that computes __eq__ case insensitively also computes a hash code of the string in canonical form testing classic comparisons testing rich comparisons testing descriptor doc strings getset descriptor member descriptor testing __doc__ descriptor sf bug 542984 testing __class__ assignment issue5283 when __class__ changes in __del__ the wrong type gets decref d testing __dict__ assignment deleting __dict__ is allowed x has to be an instance of a class inheriting from base classes don t allow __dict__ assignment and have readonly dicts modules also disallow __dict__ assignment exception s __dict__ can be replaced but not deleted at least not any more than regular exception s __dict__ can be deleted on cpython it is not the case whereas on pypy they can just like any other new style instance s __dict__ testing overrides of binary operations testing propagation of slot functions to subclasses related to id d in platform dependent ways test a nasty bug in recurse_down_subclasses crash testing that buffer interface is inherited sf bug 470040 parsetuple t vs subclasses b2a_hex uses the buffer interface to get its argument s value via pyarg_parsetuple t code testing __str__ defined in subclass of str gh 98783 should not crash should not crash testing keyword arguments to __init__ __call__ testing recursive __call__ by setting to instance of class testing __del__ hook testing hash of mutable subclasses testing deepcopy of recursive objects this blew up before testing uninitialized module objects none or are both reasonable answers testing __new__ returning something unexpected testing for __imul__ problems sf bug 544647 testing that copy copy correctly uses __setstate__ testing cases with slices and overridden __getitem__ strings tuples lists now do lists and __setitem__ testing resurrection of new style instance resurrect the instance the most interesting thing here is whether this blows up due to flawed gc tracking logic in typeobject c s call_finalizer a 2 2 1 bug make c mortal again so that the test framework with l doesn t report it as a leak testing slot trash deallocating deeply nested slotted trash caused stack overflows sf bug 575229 multiple inheritance w slots dumps core testing correct invocation of __rmul__ sf patch 592646 testing correct invocation of __ipow__ sf bug 620179 testing mutable bases stuff that should work actually we ll have crashed by here make sure all the builtin types can have their base queried without segfaulting see issue 5787 testing mutable bases with failing mro this is here to make sure that mro s aren t called with an exception set which was possible at one point an error message will be printed in a debug build what s a good way to test for this immediate subclasses have their mro s adjusted in alphabetical order so e s will get adjusted before adjusting f s fails we check here that e s gets restored testing mutable bases catch mro conflict testing mutable names c __module__ could be test_descr or __main__ a badly placed py_decref in type_set_name led to arbitrary code execution while the type structure was not in a sane state and a possible segmentation fault as a result see bug 16447 testing correct dispatch of subclass overloading __r op __ this code tests various cases where right dispatch of a subclass should be preferred over left dispatch of a base class case 1 subclass of int this tests code in abstract c binary_op1 case 2 subclass of object this is just the baseline for case 3 case 3 subclass of new style class here it gets interesting case 4 this didn t work right in 2 2 2 and 2 3a1 this one would fail testing __get__ method of meth_class c methods full coverage of descrobject c classmethod_get baseline now get the descriptor more baseline using the descriptor directly now check various error cases testing proxy isinstance and isclass test with a classic class baseline test test with a classic subclass baseline test test with a new style class baseline test test with a new style subclass baseline test testing super for a proxy object testing prohibition of carlo verre s hack this should fail testing weakref segfault sf 742911 sf 927248 deeply nested wrappers could cause stack overflow testing sys stdout is changed in getattr testing vicious_descriptor_nonsense a potential segfault spotted by thomas wouters in mail to python dev 2003 04 17 turned into an example fixed by michael hudson just less than four months later possible race condition this makes a crash more likely sf 1155938 testing method wrapper objects type method wrapper did not support any reflection before 2 5 hash __add__ should not be based on hash not really belonging to test_descr but introspection and comparison on type builtin_function_or_method seems not to be tested elsewhere self assertis l append __objclass__ list could be added hash append should not be based on hash testing objects of type wrapper_descriptor testing objects of type method_descriptor testing notimplemented all binary methods should be able to return a notimplemented might trigger overflowerrors instead of typeerrors if sizeof int sizeof long might trigger valueerrors instead of typeerrors ceval c s assign_slice used to check for tp tp_as_sequence sq_slice instead of tp tp_as_sequence sq_ass_slice see http mail python org pipermail python dev 2010 january 095637 html also check type_getattro for correctness issue 4230 this used to segfault type pretends not to have __abstractmethods__ isinstance reads __class__ call a method descriptor call a slot wrapper descriptor https github com python cpython issues 92063 call_method_descriptor_fast_with_keywords call_method_descriptor_fast_with_keywords call_method_descriptor_noargs call_method_descriptor_fast call_method_descriptor_o issue 11603 crash or infinite loop when rebinding __str__ as __repr__ check bpo 37619 a wrapper descriptor taken from the wrong class should raise an exception instead of silently being ignored make sure we have an example of each type of descriptor see bug 1469629 see issue 1683368 access via instance access via the class func has no __name__ or __qualname__ attributes bpo 25750 calling a descriptor implemented as built in function with meth_fastcall should not crash cpython if the descriptor deletes itself from the class create this large list to corrupt some unused memory bpo 46417 when the last subclass of a type is deleted remove_subclass clears the internal dictionary of subclasses set pytypeobject tp_subclasses to null remove_subclass is called when a type is deallocated test case for gh 103272 test case for gh 103551 testing dict proxy keys testing dict proxy values testing dict proxy iteritems testing type of __dict__ when metaclass set in 2 3a1 c __dict__ was a real dict rather than a dict proxy testing mappingproxy __repr__ we can t blindly compare with the repr of another dict as ordering of keys and values is arbitrary and may differ this is in its own testcase so that it can be run before any other tests hence the aaa in the test class name to make it the first item in a list sorted by name like unittest testloader gettestcasenames does testing sf bug 551412 this dumps core when sf bug 551412 isn t fixed but only when test_descr py is run separately that can t be helped as soon as pytype_ready is called for pylong_type the bug is gone another segfault only when run early before pytype_ready tuple is called issue 14199 _pytype_lookup has to keep a strong reference to the type mro because it may be modified during the lookup if __bases__ is set during the lookup for example mykey is read from base mykey2 is read from base2 because mykey __eq__ has set __bases__ utility method to verify if two objects are copies of each others we have this limitation for now because we use the object s repr to help us verify that the two objects are copies this allows us to delegate the non generic verification logic to the objects themselves utility method to generate the many possible pickle configurations we try to be as descriptive as possible here since this is the string which we will allow us to tell the pickle configuration we are using during debugging tests pickling of classes with __slots__ pickling of classes with __slots__ but without __getstate__ should fail if using protocol 0 or 1 now it should work tests pickling and copying new style classes and objects this helps testing that __init__ is not called during the unpickling process which would cause extra appends this helps testing that __init__ is not called during the unpickling process which would cause extra appends testing copying through pickle for test classes that supports this make sure we didn t go around the reduce protocol by simply copying the attribute dictionary we clear attributes using the previous copy to not mutate the original argument testing copying through copy deepcopy for test classes that supports this make sure we didn t go around the reduce protocol by simply copying the attribute dictionary we clear attributes using the previous copy to not mutate the original argument slot name is freed inside __getattr__ and is later used not interned shouldn t crash issue 29914 __reduce__ takes no arguments __reduce_ex__ takes one integer argument verify that subclasses can share keys per pep 412 shrink keys by repeatedly creating instances initial hash table can contain only one or two elements set 6 attributes to cause internal resizing sets default __doc__ and simplifies repr output helps when debugging with gdb regressions for some bugs revealed through mcsl mro customization typeobject c mro_internal and cls __bases__ assignment typeobject c type_set_bases type_set_bases must be aware that type tp_mro can be null deep reentrancy must not over decref old_mro 4 5 steps are usually enough to make it crash somewhere similar to test_reent_set_bases_on_base but may crash differently type_set_bases must check for an inheritance cycle not only through mro of the type which may be not yet updated in case of reentrance but also through tp_base chain which is assigned before diving into inner calls to mro otherwise the following snippet can loop forever do type type tp_base while type null functions that rely on tp_base like solid_base and pytype_issubtype would not be happy in that case causing a stack overflow type_set_bases must check for reentrancy upon finishing its job by updating tp_subclasses of old new bases of the type otherwise an implicit inheritance cycle through tp_subclasses can break functions that recurse on elements of that field like recurse_down_subclasses and mro_hierarchy eventually leading to a stack overflow the same as test_tp_subclasses_cycle_in_update_slots but tests a code path executed on error goto bail extending an uninitialized type with type tp_mro null must throw a reasonable typeerror exception instead of failing with pyerr_badinternalcall attribute lookup on a super object must be aware that its target type can be uninitialized type tp_mro null gh 92112 a custom mro returning a result conflicting with __bases__ and deleting itself caused a double free
import builtins
import copyreg
import gc
import itertools
import math
import pickle
import random
import string
import sys
import types
import unittest
import warnings
import weakref

from copy import deepcopy
from contextlib import redirect_stdout
from test import support

try:
    import _testcapi
except ImportError:
    _testcapi = None

try:
    import xxsubtype
except ImportError:
    xxsubtype = None


class OperatorsTest(unittest.TestCase):

    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.binops = {
            'add': '+',
            'sub': '-',
            'mul': '*',
            'matmul': '@',
            'truediv': '/',
            'floordiv': '//',
            'divmod': 'divmod',
            'pow': '**',
            'lshift': '<<',
            'rshift': '>>',
            'and': '&',
            'xor': '^',
            'or': '|',
            'cmp': 'cmp',
            'lt': '<',
            'le': '<=',
            'eq': '==',
            'ne': '!=',
            'gt': '>',
            'ge': '>=',
        }

        for name, expr in list(self.binops.items()):
            if expr.islower():
                expr = expr + "(a, b)"
            else:
                expr = 'a %s b' % expr
            self.binops[name] = expr

        self.unops = {
            'pos': '+',
            'neg': '-',
            'abs': 'abs',
            'invert': '~',
            'int': 'int',
            'float': 'float',
        }

        for name, expr in list(self.unops.items()):
            if expr.islower():
                expr = expr + "(a)"
            else:
                expr = '%s a' % expr
            self.unops[name] = expr

    def unop_test(self, a, res, expr="len(a)", meth="__len__"):
        d = {'a': a}
        self.assertEqual(eval(expr, d), res)
        t = type(a)
        m = getattr(t, meth)

        
        while meth not in t.__dict__:
            t = t.__bases__[0]
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        self.assertEqual(m(a), res)
        bm = getattr(a, meth)
        self.assertEqual(bm(), res)

    def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
        d = {'a': a, 'b': b}

        self.assertEqual(eval(expr, d), res)
        t = type(a)
        m = getattr(t, meth)
        while meth not in t.__dict__:
            t = t.__bases__[0]
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        self.assertEqual(m(a, b), res)
        bm = getattr(a, meth)
        self.assertEqual(bm(b), res)

    def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
        d = {'a': a, 'b': b, 'c': c}
        self.assertEqual(eval(expr, d), res)
        t = type(a)
        m = getattr(t, meth)
        while meth not in t.__dict__:
            t = t.__bases__[0]
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        self.assertEqual(m(a, slice(b, c)), res)
        bm = getattr(a, meth)
        self.assertEqual(bm(slice(b, c)), res)

    def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
        d = {'a': deepcopy(a), 'b': b}
        exec(stmt, d)
        self.assertEqual(d['a'], res)
        t = type(a)
        m = getattr(t, meth)
        while meth not in t.__dict__:
            t = t.__bases__[0]
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        d['a'] = deepcopy(a)
        m(d['a'], b)
        self.assertEqual(d['a'], res)
        d['a'] = deepcopy(a)
        bm = getattr(d['a'], meth)
        bm(b)
        self.assertEqual(d['a'], res)

    def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
        d = {'a': deepcopy(a), 'b': b, 'c': c}
        exec(stmt, d)
        self.assertEqual(d['a'], res)
        t = type(a)
        m = getattr(t, meth)
        while meth not in t.__dict__:
            t = t.__bases__[0]
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        d['a'] = deepcopy(a)
        m(d['a'], b, c)
        self.assertEqual(d['a'], res)
        d['a'] = deepcopy(a)
        bm = getattr(d['a'], meth)
        bm(b, c)
        self.assertEqual(d['a'], res)

    def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
        dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
        exec(stmt, dictionary)
        self.assertEqual(dictionary['a'], res)
        t = type(a)
        while meth not in t.__dict__:
            t = t.__bases__[0]
        m = getattr(t, meth)
        
        
        self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
        dictionary['a'] = deepcopy(a)
        m(dictionary['a'], slice(b, c), d)
        self.assertEqual(dictionary['a'], res)
        dictionary['a'] = deepcopy(a)
        bm = getattr(dictionary['a'], meth)
        bm(slice(b, c), d)
        self.assertEqual(dictionary['a'], res)

    def test_lists(self):
        
        
        self.binop_test([1], [2], [1,2], "a+b", "__add__")
        self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
        self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
        self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
        self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
        self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
        self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
        self.unop_test([1,2,3], 3, "len(a)", "__len__")
        self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
        self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
        self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
        self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
                        "__setitem__")

    def test_dicts(self):
        
        self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
        self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
        self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")

        d = {1:2, 3:4}
        l1 = []
        for i in list(d.keys()):
            l1.append(i)
        l = []
        for i in iter(d):
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in d.__iter__():
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in dict.__iter__(d):
            l.append(i)
        self.assertEqual(l, l1)
        d = {1:2, 3:4}
        self.unop_test(d, 2, "len(a)", "__len__")
        self.assertEqual(eval(repr(d), {}), d)
        self.assertEqual(eval(d.__repr__(), {}), d)
        self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
                        "__setitem__")

    
    def number_operators(self, a, b, skip=[]):
        dict = {'a': a, 'b': b}

        for name, expr in self.binops.items():
            if name not in skip:
                name = "__%s__" % name
                if hasattr(a, name):
                    res = eval(expr, dict)
                    self.binop_test(a, b, res, expr, name)

        for name, expr in list(self.unops.items()):
            if name not in skip:
                name = "__%s__" % name
                if hasattr(a, name):
                    res = eval(expr, dict)
                    self.unop_test(a, res, expr, name)

    def test_ints(self):
        
        self.number_operators(100, 3)
        
        self.assertEqual((1).__bool__(), 1)
        self.assertEqual((0).__bool__(), 0)
        
        class C(int):
            def __add__(self, other):
                return NotImplemented
        self.assertEqual(C(5), 5)
        try:
            C() + ""
        except TypeError:
            pass
        else:
            self.fail("NotImplemented should have caused TypeError")

    def test_floats(self):
        
        self.number_operators(100.0, 3.0)

    def test_complexes(self):
        
        self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
                                                  'int', 'float',
                                                  'floordiv', 'divmod', 'mod'])

        class Number(complex):
            __slots__ = ['prec']
            def __new__(cls, *args, **kwds):
                result = complex.__new__(cls, *args)
                result.prec = kwds.get('prec', 12)
                return result
            def __repr__(self):
                prec = self.prec
                if self.imag == 0.0:
                    return "%.*g" % (prec, self.real)
                if self.real == 0.0:
                    return "%.*gj" % (prec, self.imag)
                return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
            __str__ = __repr__

        a = Number(3.14, prec=6)
        self.assertEqual(repr(a), "3.14")
        self.assertEqual(a.prec, 6)

        a = Number(a, prec=2)
        self.assertEqual(repr(a), "3.1")
        self.assertEqual(a.prec, 2)

        a = Number(234.5)
        self.assertEqual(repr(a), "234.5")
        self.assertEqual(a.prec, 12)

    def test_explicit_reverse_methods(self):
        
        self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
        self.assertEqual(float.__rsub__(3.0, 1), -2.0)

    @support.impl_detail("the module 'xxsubtype' is internal")
    @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
    def test_spam_lists(self):
        
        import copy, xxsubtype as spam

        def spamlist(l, memo=None):
            import xxsubtype as spam
            return spam.spamlist(l)

        
        copy._deepcopy_dispatch[spam.spamlist] = spamlist

        self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
                       "__add__")
        self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
        self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
        self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
        self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
                          "__getitem__")
        self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
                        "__iadd__")
        self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
                        "__imul__")
        self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
                        "__mul__")
        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
                        "__rmul__")
        self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
                         "__setitem__")
        self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
                             spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
        
        class C(spam.spamlist):
            def foo(self): return 1
        a = C()
        self.assertEqual(a, [])
        self.assertEqual(a.foo(), 1)
        a.append(100)
        self.assertEqual(a, [100])
        self.assertEqual(a.getstate(), 0)
        a.setstate(42)
        self.assertEqual(a.getstate(), 42)

    @support.impl_detail("the module 'xxsubtype' is internal")
    @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
    def test_spam_dicts(self):
        
        import copy, xxsubtype as spam
        def spamdict(d, memo=None):
            import xxsubtype as spam
            sd = spam.spamdict()
            for k, v in list(d.items()):
                sd[k] = v
            return sd
        
        copy._deepcopy_dispatch[spam.spamdict] = spamdict

        self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
        self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
        self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
        d = spamdict({1:2,3:4})
        l1 = []
        for i in list(d.keys()):
            l1.append(i)
        l = []
        for i in iter(d):
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in d.__iter__():
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in type(spamdict({})).__iter__(d):
            l.append(i)
        self.assertEqual(l, l1)
        straightd = {1:2, 3:4}
        spamd = spamdict(straightd)
        self.unop_test(spamd, 2, "len(a)", "__len__")
        self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
        self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
                   "a[b]=c", "__setitem__")
        
        class C(spam.spamdict):
            def foo(self): return 1
        a = C()
        self.assertEqual(list(a.items()), [])
        self.assertEqual(a.foo(), 1)
        a['foo'] = 'bar'
        self.assertEqual(list(a.items()), [('foo', 'bar')])
        self.assertEqual(a.getstate(), 0)
        a.setstate(100)
        self.assertEqual(a.getstate(), 100)

    def test_wrap_lenfunc_bad_cast(self):
        self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize)


class ClassPropertiesAndMethods(unittest.TestCase):

    def assertHasAttr(self, obj, name):
        self.assertTrue(hasattr(obj, name),
                        '%r has no attribute %r' % (obj, name))

    def assertNotHasAttr(self, obj, name):
        self.assertFalse(hasattr(obj, name),
                         '%r has unexpected attribute %r' % (obj, name))

    def test_python_dicts(self):
        
        self.assertTrue(issubclass(dict, dict))
        self.assertIsInstance({}, dict)
        d = dict()
        self.assertEqual(d, {})
        self.assertIs(d.__class__, dict)
        self.assertIsInstance(d, dict)
        class C(dict):
            state = -1
            def __init__(self_local, *a, **kw):
                if a:
                    self.assertEqual(len(a), 1)
                    self_local.state = a[0]
                if kw:
                    for k, v in list(kw.items()):
                        self_local[v] = k
            def __getitem__(self, key):
                return self.get(key, 0)
            def __setitem__(self_local, key, value):
                self.assertIsInstance(key, int)
                dict.__setitem__(self_local, key, value)
            def setstate(self, state):
                self.state = state
            def getstate(self):
                return self.state
        self.assertTrue(issubclass(C, dict))
        a1 = C(12)
        self.assertEqual(a1.state, 12)
        a2 = C(foo=1, bar=2)
        self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
        a = C()
        self.assertEqual(a.state, -1)
        self.assertEqual(a.getstate(), -1)
        a.setstate(0)
        self.assertEqual(a.state, 0)
        self.assertEqual(a.getstate(), 0)
        a.setstate(10)
        self.assertEqual(a.state, 10)
        self.assertEqual(a.getstate(), 10)
        self.assertEqual(a[42], 0)
        a[42] = 24
        self.assertEqual(a[42], 24)
        N = 50
        for i in range(N):
            a[i] = C()
            for j in range(N):
                a[i][j] = i*j
        for i in range(N):
            for j in range(N):
                self.assertEqual(a[i][j], i*j)

    def test_python_lists(self):
        
        class C(list):
            def __getitem__(self, i):
                if isinstance(i, slice):
                    return i.start, i.stop
                return list.__getitem__(self, i) + 100
        a = C()
        a.extend([0,1,2])
        self.assertEqual(a[0], 100)
        self.assertEqual(a[1], 101)
        self.assertEqual(a[2], 102)
        self.assertEqual(a[100:200], (100,200))

    def test_metaclass(self):
        
        class C(metaclass=type):
            def __init__(self):
                self.__state = 0
            def getstate(self):
                return self.__state
            def setstate(self, state):
                self.__state = state
        a = C()
        self.assertEqual(a.getstate(), 0)
        a.setstate(10)
        self.assertEqual(a.getstate(), 10)
        class _metaclass(type):
            def myself(cls): return cls
        class D(metaclass=_metaclass):
            pass
        self.assertEqual(D.myself(), D)
        d = D()
        self.assertEqual(d.__class__, D)
        class M1(type):
            def __new__(cls, name, bases, dict):
                dict['__spam__'] = 1
                return type.__new__(cls, name, bases, dict)
        class C(metaclass=M1):
            pass
        self.assertEqual(C.__spam__, 1)
        c = C()
        self.assertEqual(c.__spam__, 1)

        class _instance(object):
            pass
        class M2(object):
            @staticmethod
            def __new__(cls, name, bases, dict):
                self = object.__new__(cls)
                self.name = name
                self.bases = bases
                self.dict = dict
                return self
            def __call__(self):
                it = _instance()
                
                for key in self.dict:
                    if key.startswith("__"):
                        continue
                    setattr(it, key, self.dict[key].__get__(it, self))
                return it
        class C(metaclass=M2):
            def spam(self):
                return 42
        self.assertEqual(C.name, 'C')
        self.assertEqual(C.bases, ())
        self.assertIn('spam', C.dict)
        c = C()
        self.assertEqual(c.spam(), 42)

        

        class autosuper(type):
            
            
            def __new__(metaclass, name, bases, dict):
                cls = super(autosuper, metaclass).__new__(metaclass,
                                                          name, bases, dict)
                
                while name[:1] == "_":
                    name = name[1:]
                if name:
                    name = "_%s__super" % name
                else:
                    name = "__super"
                setattr(cls, name, super(cls))
                return cls
        class A(metaclass=autosuper):
            def meth(self):
                return "A"
        class B(A):
            def meth(self):
                return "B" + self.__super.meth()
        class C(A):
            def meth(self):
                return "C" + self.__super.meth()
        class D(C, B):
            def meth(self):
                return "D" + self.__super.meth()
        self.assertEqual(D().meth(), "DCBA")
        class E(B, C):
            def meth(self):
                return "E" + self.__super.meth()
        self.assertEqual(E().meth(), "EBCA")

        class autoproperty(type):
            
            
            def __new__(metaclass, name, bases, dict):
                hits = {}
                for key, val in dict.items():
                    if key.startswith("_get_"):
                        key = key[5:]
                        get, set = hits.get(key, (None, None))
                        get = val
                        hits[key] = get, set
                    elif key.startswith("_set_"):
                        key = key[5:]
                        get, set = hits.get(key, (None, None))
                        set = val
                        hits[key] = get, set
                for key, (get, set) in hits.items():
                    dict[key] = property(get, set)
                return super(autoproperty, metaclass).__new__(metaclass,
                                                            name, bases, dict)
        class A(metaclass=autoproperty):
            def _get_x(self):
                return -self.__x
            def _set_x(self, x):
                self.__x = -x
        a = A()
        self.assertNotHasAttr(a, "x")
        a.x = 12
        self.assertEqual(a.x, 12)
        self.assertEqual(a._A__x, -12)

        class multimetaclass(autoproperty, autosuper):
            
            pass
        class A(metaclass=multimetaclass):
            def _get_x(self):
                return "A"
        class B(A):
            def _get_x(self):
                return "B" + self.__super._get_x()
        class C(A):
            def _get_x(self):
                return "C" + self.__super._get_x()
        class D(C, B):
            def _get_x(self):
                return "D" + self.__super._get_x()
        self.assertEqual(D().x, "DCBA")

        
        class T(type):
            counter = 0
            def __init__(self, *args):
                T.counter += 1
        class C(metaclass=T):
            pass
        self.assertEqual(T.counter, 1)
        a = C()
        self.assertEqual(type(a), C)
        self.assertEqual(T.counter, 1)

        class C(object): pass
        c = C()
        try: c()
        except TypeError: pass
        else: self.fail("calling object w/o call method should raise "
                        "TypeError")

        
        class A(type):
            def __new__(*args, **kwargs):
                return type.__new__(*args, **kwargs)

        class B(object):
            pass

        class C(object, metaclass=A):
            pass

        
        class D(B, C):
            pass
        self.assertIs(A, type(D))

        
        new_calls = []  
        class AMeta(type):
            @staticmethod
            def __new__(mcls, name, bases, ns):
                new_calls.append('AMeta')
                return super().__new__(mcls, name, bases, ns)
            @classmethod
            def __prepare__(mcls, name, bases):
                return {}

        class BMeta(AMeta):
            @staticmethod
            def __new__(mcls, name, bases, ns):
                new_calls.append('BMeta')
                return super().__new__(mcls, name, bases, ns)
            @classmethod
            def __prepare__(mcls, name, bases):
                ns = super().__prepare__(name, bases)
                ns['BMeta_was_here'] = True
                return ns

        class A(metaclass=AMeta):
            pass
        self.assertEqual(['AMeta'], new_calls)
        new_calls.clear()

        class B(metaclass=BMeta):
            pass
        
        self.assertEqual(['BMeta', 'AMeta'], new_calls)
        new_calls.clear()

        class C(A, B):
            pass
        
        self.assertEqual(['BMeta', 'AMeta'], new_calls)
        new_calls.clear()
        
        self.assertIn('BMeta_was_here', C.__dict__)

        
        class C2(B, A):
            pass
        self.assertEqual(['BMeta', 'AMeta'], new_calls)
        new_calls.clear()
        self.assertIn('BMeta_was_here', C2.__dict__)

        
        class D(C, metaclass=type):
            pass
        self.assertEqual(['BMeta', 'AMeta'], new_calls)
        new_calls.clear()
        self.assertIn('BMeta_was_here', D.__dict__)

        class E(C, metaclass=AMeta):
            pass
        self.assertEqual(['BMeta', 'AMeta'], new_calls)
        new_calls.clear()
        self.assertIn('BMeta_was_here', E.__dict__)

        
        
        marker = object()
        def func(*args, **kwargs):
            return marker
        class X(metaclass=func):
            pass
        class Y(object, metaclass=func):
            pass
        class Z(D, metaclass=func):
            pass
        self.assertIs(marker, X)
        self.assertIs(marker, Y)
        self.assertIs(marker, Z)

        
        
        prepare_calls = []  
        class ANotMeta:
            def __new__(mcls, *args, **kwargs):
                new_calls.append('ANotMeta')
                return super().__new__(mcls)
            @classmethod
            def __prepare__(mcls, name, bases):
                prepare_calls.append('ANotMeta')
                return {}
        class BNotMeta(ANotMeta):
            def __new__(mcls, *args, **kwargs):
                new_calls.append('BNotMeta')
                return super().__new__(mcls)
            @classmethod
            def __prepare__(mcls, name, bases):
                prepare_calls.append('BNotMeta')
                return super().__prepare__(name, bases)

        class A(metaclass=ANotMeta):
            pass
        self.assertIs(ANotMeta, type(A))
        self.assertEqual(['ANotMeta'], prepare_calls)
        prepare_calls.clear()
        self.assertEqual(['ANotMeta'], new_calls)
        new_calls.clear()

        class B(metaclass=BNotMeta):
            pass
        self.assertIs(BNotMeta, type(B))
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()

        class C(A, B):
            pass
        self.assertIs(BNotMeta, type(C))
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()

        class C2(B, A):
            pass
        self.assertIs(BNotMeta, type(C2))
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()

        
        
        with self.assertRaises(TypeError):
            class D(C, metaclass=type):
                pass

        class E(C, metaclass=ANotMeta):
            pass
        self.assertIs(BNotMeta, type(E))
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()

        class F(object(), C):
            pass
        self.assertIs(BNotMeta, type(F))
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()

        class F2(C, object()):
            pass
        self.assertIs(BNotMeta, type(F2))
        self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
        new_calls.clear()
        self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
        prepare_calls.clear()

        
        
        with self.assertRaises(TypeError):
            class X(C, int()):
                pass
        with self.assertRaises(TypeError):
            class X(int(), C):
                pass

    def test_module_subclasses(self):
        
        log = []
        MT = type(sys)
        class MM(MT):
            def __init__(self, name):
                MT.__init__(self, name)
            def __getattribute__(self, name):
                log.append(("getattr", name))
                return MT.__getattribute__(self, name)
            def __setattr__(self, name, value):
                log.append(("setattr", name, value))
                MT.__setattr__(self, name, value)
            def __delattr__(self, name):
                log.append(("delattr", name))
                MT.__delattr__(self, name)
        a = MM("a")
        a.foo = 12
        x = a.foo
        del a.foo
        self.assertEqual(log, [("setattr", "foo", 12),
                               ("getattr", "foo"),
                               ("delattr", "foo")])

        
        try:
            class Module(types.ModuleType, str):
                pass
        except TypeError:
            pass
        else:
            self.fail("inheriting from ModuleType and str at the same time "
                      "should fail")

        
        def random_name():
            return ''.join(random.choices(string.ascii_letters, k=10))
        class A:
            pass
        subclasses = [type(random_name(), (A,), {}) for i in range(100)]
        self.assertEqual(A.__subclasses__(), subclasses)

    def test_multiple_inheritance(self):
        
        class C(object):
            def __init__(self):
                self.__state = 0
            def getstate(self):
                return self.__state
            def setstate(self, state):
                self.__state = state
        a = C()
        self.assertEqual(a.getstate(), 0)
        a.setstate(10)
        self.assertEqual(a.getstate(), 10)
        class D(dict, C):
            def __init__(self):
                dict.__init__(self)
                C.__init__(self)
        d = D()
        self.assertEqual(list(d.keys()), [])
        d["hello"] = "world"
        self.assertEqual(list(d.items()), [("hello", "world")])
        self.assertEqual(d["hello"], "world")
        self.assertEqual(d.getstate(), 0)
        d.setstate(10)
        self.assertEqual(d.getstate(), 10)
        self.assertEqual(D.__mro__, (D, dict, C, object))

        
        class Node(object):
            def __int__(self):
                return int(self.foo())
            def foo(self):
                return "23"
        class Frag(Node, list):
            def foo(self):
                return "42"
        self.assertEqual(Node().__int__(), 23)
        self.assertEqual(int(Node()), 23)
        self.assertEqual(Frag().__int__(), 42)
        self.assertEqual(int(Frag()), 42)

    def test_diamond_inheritance(self):
        
        class A(object):
            def spam(self): return "A"
        self.assertEqual(A().spam(), "A")
        class B(A):
            def boo(self): return "B"
            def spam(self): return "B"
        self.assertEqual(B().spam(), "B")
        self.assertEqual(B().boo(), "B")
        class C(A):
            def boo(self): return "C"
        self.assertEqual(C().spam(), "A")
        self.assertEqual(C().boo(), "C")
        class D(B, C): pass
        self.assertEqual(D().spam(), "B")
        self.assertEqual(D().boo(), "B")
        self.assertEqual(D.__mro__, (D, B, C, A, object))
        class E(C, B): pass
        self.assertEqual(E().spam(), "B")
        self.assertEqual(E().boo(), "C")
        self.assertEqual(E.__mro__, (E, C, B, A, object))
        
        try:
            class F(D, E): pass
        except TypeError:
            pass
        else:
            self.fail("expected MRO order disagreement (F)")
        try:
            class G(E, D): pass
        except TypeError:
            pass
        else:
            self.fail("expected MRO order disagreement (G)")

    
    def test_ex5_from_c3_switch(self):
        
        class A(object): pass
        class B(object): pass
        class C(object): pass
        class X(A): pass
        class Y(A): pass
        class Z(X,B,Y,C): pass
        self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))

    
    
    def test_monotonicity(self):
        
        class Boat(object): pass
        class DayBoat(Boat): pass
        class WheelBoat(Boat): pass
        class EngineLess(DayBoat): pass
        class SmallMultihull(DayBoat): pass
        class PedalWheelBoat(EngineLess,WheelBoat): pass
        class SmallCatamaran(SmallMultihull): pass
        class Pedalo(PedalWheelBoat,SmallCatamaran): pass

        self.assertEqual(PedalWheelBoat.__mro__,
              (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
        self.assertEqual(SmallCatamaran.__mro__,
              (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
        self.assertEqual(Pedalo.__mro__,
              (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
               SmallMultihull, DayBoat, WheelBoat, Boat, object))

    
    
    def test_consistency_with_epg(self):
        
        class Pane(object): pass
        class ScrollingMixin(object): pass
        class EditingMixin(object): pass
        class ScrollablePane(Pane,ScrollingMixin): pass
        class EditablePane(Pane,EditingMixin): pass
        class EditableScrollablePane(ScrollablePane,EditablePane): pass

        self.assertEqual(EditableScrollablePane.__mro__,
              (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
                ScrollingMixin, EditingMixin, object))

    def test_mro_disagreement(self):
        
        mro_err_msg = ("Cannot create a consistent method resolution "
                       "order (MRO) for bases ")

        def raises(exc, expected, callable, *args):
            try:
                callable(*args)
            except exc as msg:
                
                if support.check_impl_detail():
                    if not str(msg).startswith(expected):
                        self.fail("Message %r, expected %r" %
                                  (str(msg), expected))
            else:
                self.fail("Expected %s" % exc)

        class A(object): pass
        class B(A): pass
        class C(object): pass

        
        raises(TypeError, "duplicate base class A",
               type, "X", (A, A), {})
        raises(TypeError, mro_err_msg,
               type, "X", (A, B), {})
        raises(TypeError, mro_err_msg,
               type, "X", (A, C, B), {})
        
        class GridLayout(object): pass
        class HorizontalGrid(GridLayout): pass
        class VerticalGrid(GridLayout): pass
        class HVGrid(HorizontalGrid, VerticalGrid): pass
        class VHGrid(VerticalGrid, HorizontalGrid): pass
        raises(TypeError, mro_err_msg,
               type, "ConfusedGrid", (HVGrid, VHGrid), {})

    def test_object_class(self):
        
        a = object()
        self.assertEqual(a.__class__, object)
        self.assertEqual(type(a), object)
        b = object()
        self.assertNotEqual(a, b)
        self.assertNotHasAttr(a, "foo")
        try:
            a.foo = 12
        except (AttributeError, TypeError):
            pass
        else:
            self.fail("object() should not allow setting a foo attribute")
        self.assertNotHasAttr(object(), "__dict__")

        class Cdict(object):
            pass
        x = Cdict()
        self.assertEqual(x.__dict__, {})
        x.foo = 1
        self.assertEqual(x.foo, 1)
        self.assertEqual(x.__dict__, {'foo': 1})

    def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
        class SubType(types.ModuleType):
            a = 1

        m = types.ModuleType("m")
        self.assertTrue(m.__class__ is types.ModuleType)
        self.assertFalse(hasattr(m, "a"))

        m.__class__ = SubType
        self.assertTrue(m.__class__ is SubType)
        self.assertTrue(hasattr(m, "a"))

        m.__class__ = types.ModuleType
        self.assertTrue(m.__class__ is types.ModuleType)
        self.assertFalse(hasattr(m, "a"))

        
        
        
        
        

        
        
        

        class MyInt(int):
            __slots__ = ()
        with self.assertRaises(TypeError):
            (1).__class__ = MyInt

        class MyFloat(float):
            __slots__ = ()
        with self.assertRaises(TypeError):
            (1.0).__class__ = MyFloat

        class MyComplex(complex):
            __slots__ = ()
        with self.assertRaises(TypeError):
            (1 + 2j).__class__ = MyComplex

        class MyStr(str):
            __slots__ = ()
        with self.assertRaises(TypeError):
            "a".__class__ = MyStr

        class MyBytes(bytes):
            __slots__ = ()
        with self.assertRaises(TypeError):
            b"a".__class__ = MyBytes

        class MyTuple(tuple):
            __slots__ = ()
        with self.assertRaises(TypeError):
            ().__class__ = MyTuple

        class MyFrozenSet(frozenset):
            __slots__ = ()
        with self.assertRaises(TypeError):
            frozenset().__class__ = MyFrozenSet

    def test_slots(self):
        
        class C0(object):
            __slots__ = []
        x = C0()
        self.assertNotHasAttr(x, "__dict__")
        self.assertNotHasAttr(x, "foo")

        class C1(object):
            __slots__ = ['a']
        x = C1()
        self.assertNotHasAttr(x, "__dict__")
        self.assertNotHasAttr(x, "a")
        x.a = 1
        self.assertEqual(x.a, 1)
        x.a = None
        self.assertEqual(x.a, None)
        del x.a
        self.assertNotHasAttr(x, "a")

        class C3(object):
            __slots__ = ['a', 'b', 'c']
        x = C3()
        self.assertNotHasAttr(x, "__dict__")
        self.assertNotHasAttr(x, 'a')
        self.assertNotHasAttr(x, 'b')
        self.assertNotHasAttr(x, 'c')
        x.a = 1
        x.b = 2
        x.c = 3
        self.assertEqual(x.a, 1)
        self.assertEqual(x.b, 2)
        self.assertEqual(x.c, 3)

        class C4(object):
            
            __slots__ = ['__a']
            def __init__(self, value):
                self.__a = value
            def get(self):
                return self.__a
        x = C4(5)
        self.assertNotHasAttr(x, '__dict__')
        self.assertNotHasAttr(x, '__a')
        self.assertEqual(x.get(), 5)
        try:
            x.__a = 6
        except AttributeError:
            pass
        else:
            self.fail("Double underscored names not mangled")

        
        try:
            class C(object):
                __slots__ = [None]
        except TypeError:
            pass
        else:
            self.fail("[None] slots not caught")
        try:
            class C(object):
                __slots__ = ["foo bar"]
        except TypeError:
            pass
        else:
            self.fail("['foo bar'] slots not caught")
        try:
            class C(object):
                __slots__ = ["foo\0bar"]
        except TypeError:
            pass
        else:
            self.fail("['foo\\0bar'] slots not caught")
        try:
            class C(object):
                __slots__ = ["1"]
        except TypeError:
            pass
        else:
            self.fail("['1'] slots not caught")
        try:
            class C(object):
                __slots__ = [""]
        except TypeError:
            pass
        else:
            self.fail("[''] slots not caught")
        class C(object):
            __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
        
        

        
        class C(object):
            __slots__ = "abc"
        c = C()
        c.abc = 5
        self.assertEqual(c.abc, 5)

        
        
        class C(object):
            __slots__ = "abc"
        c = C()
        c.abc = 5
        self.assertEqual(c.abc, 5)

        
        slots = ("foo", "bar")
        class C(object):
            __slots__ = slots
        x = C()
        x.foo = 5
        self.assertEqual(x.foo, 5)
        self.assertIs(type(slots[0]), str)
        
        try:
            class C(object):
                __slots__ = [chr(128)]
        except (TypeError, UnicodeEncodeError):
            pass
        else:
            self.fail("[chr(128)] slots not caught")

        
        class Counted(object):
            counter = 0    
            def __init__(self):
                Counted.counter += 1
            def __del__(self):
                Counted.counter -= 1
        class C(object):
            __slots__ = ['a', 'b', 'c']
        x = C()
        x.a = Counted()
        x.b = Counted()
        x.c = Counted()
        self.assertEqual(Counted.counter, 3)
        del x
        support.gc_collect()
        self.assertEqual(Counted.counter, 0)
        class D(C):
            pass
        x = D()
        x.a = Counted()
        x.z = Counted()
        self.assertEqual(Counted.counter, 2)
        del x
        support.gc_collect()
        self.assertEqual(Counted.counter, 0)
        class E(D):
            __slots__ = ['e']
        x = E()
        x.a = Counted()
        x.z = Counted()
        x.e = Counted()
        self.assertEqual(Counted.counter, 3)
        del x
        support.gc_collect()
        self.assertEqual(Counted.counter, 0)

        
        class F(object):
            __slots__ = ['a', 'b']
        s = F()
        s.a = [Counted(), s]
        self.assertEqual(Counted.counter, 1)
        s = None
        support.gc_collect()
        self.assertEqual(Counted.counter, 0)

        
        if hasattr(gc, 'get_objects'):
            class G(object):
                def __eq__(self, other):
                    return False
            g = G()
            orig_objects = len(gc.get_objects())
            for i in range(10):
                g==g
            new_objects = len(gc.get_objects())
            self.assertEqual(orig_objects, new_objects)

        class H(object):
            __slots__ = ['a', 'b']
            def __init__(self):
                self.a = 1
                self.b = 2
            def __del__(self_):
                self.assertEqual(self_.a, 1)
                self.assertEqual(self_.b, 2)
        with support.captured_output('stderr') as s:
            h = H()
            del h
        self.assertEqual(s.getvalue(), '')

        class X(object):
            __slots__ = "a"
        with self.assertRaises(AttributeError):
            del X().a

        
        class X(object):
            __slots__ = "a"
        with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"):
            X().a

        
        class SubStr(str):
            pass
        class X(object):
            __slots__ = (SubStr('x'),)
        X().x = 1
        with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"):
            X().a

    def test_slots_special(self):
        
        class D(object):
            __slots__ = ["__dict__"]
        a = D()
        self.assertHasAttr(a, "__dict__")
        self.assertNotHasAttr(a, "__weakref__")
        a.foo = 42
        self.assertEqual(a.__dict__, {"foo": 42})

        class W(object):
            __slots__ = ["__weakref__"]
        a = W()
        self.assertHasAttr(a, "__weakref__")
        self.assertNotHasAttr(a, "__dict__")
        try:
            a.foo = 42
        except AttributeError:
            pass
        else:
            self.fail("shouldn't be allowed to set a.foo")

        class C1(W, D):
            __slots__ = []
        a = C1()
        self.assertHasAttr(a, "__dict__")
        self.assertHasAttr(a, "__weakref__")
        a.foo = 42
        self.assertEqual(a.__dict__, {"foo": 42})

        class C2(D, W):
            __slots__ = []
        a = C2()
        self.assertHasAttr(a, "__dict__")
        self.assertHasAttr(a, "__weakref__")
        a.foo = 42
        self.assertEqual(a.__dict__, {"foo": 42})

    def test_slots_special2(self):
        
        class Meta(type):
            def __new__(cls, name, bases, namespace, attr):
                self.assertIn(attr, namespace)
                return super().__new__(cls, name, bases, namespace)

        class C1:
            def __init__(self):
                self.b = 42
        class C2(C1, metaclass=Meta, attr="__classcell__"):
            __slots__ = ["__classcell__"]
            def __init__(self):
                super().__init__()
        self.assertIsInstance(C2.__dict__["__classcell__"],
                              types.MemberDescriptorType)
        c = C2()
        self.assertEqual(c.b, 42)
        self.assertNotHasAttr(c, "__classcell__")
        c.__classcell__ = 42
        self.assertEqual(c.__classcell__, 42)
        with self.assertRaises(TypeError):
            class C3:
                __classcell__ = 42
                __slots__ = ["__classcell__"]

        class Q1(metaclass=Meta, attr="__qualname__"):
            __slots__ = ["__qualname__"]
        self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
        self.assertIsInstance(Q1.__dict__["__qualname__"],
                              types.MemberDescriptorType)
        q = Q1()
        self.assertNotHasAttr(q, "__qualname__")
        q.__qualname__ = "q"
        self.assertEqual(q.__qualname__, "q")
        with self.assertRaises(TypeError):
            class Q2:
                __qualname__ = object()
                __slots__ = ["__qualname__"]

    def test_slots_descriptor(self):
        
        
        import abc
        class MyABC(metaclass=abc.ABCMeta):
            __slots__ = "a"

        class Unrelated(object):
            pass
        MyABC.register(Unrelated)

        u = Unrelated()
        self.assertIsInstance(u, MyABC)

        
        self.assertRaises(TypeError, MyABC.a.__set__, u, 3)

    def test_dynamics(self):
        
        class D(object):
            pass
        class E(D):
            pass
        class F(D):
            pass
        D.foo = 1
        self.assertEqual(D.foo, 1)
        
        self.assertEqual(E.foo, 1)
        self.assertEqual(F.foo, 1)
        
        class C(object):
            pass
        a = C()
        self.assertNotHasAttr(a, "foobar")
        C.foobar = 2
        self.assertEqual(a.foobar, 2)
        C.method = lambda self: 42
        self.assertEqual(a.method(), 42)
        C.__repr__ = lambda self: "C()"
        self.assertEqual(repr(a), "C()")
        C.__int__ = lambda self: 100
        self.assertEqual(int(a), 100)
        self.assertEqual(a.foobar, 2)
        self.assertNotHasAttr(a, "spam")
        def mygetattr(self, name):
            if name == "spam":
                return "spam"
            raise AttributeError
        C.__getattr__ = mygetattr
        self.assertEqual(a.spam, "spam")
        a.new = 12
        self.assertEqual(a.new, 12)
        def mysetattr(self, name, value):
            if name == "spam":
                raise AttributeError
            return object.__setattr__(self, name, value)
        C.__setattr__ = mysetattr
        with self.assertRaises(AttributeError):
            a.spam = "not spam"

        self.assertEqual(a.spam, "spam")
        class D(C):
            pass
        d = D()
        d.foo = 1
        self.assertEqual(d.foo, 1)

        
        class I(int):
            pass
        self.assertEqual("a"*I(2), "aa")
        self.assertEqual(I(2)*"a", "aa")
        self.assertEqual(2*I(3), 6)
        self.assertEqual(I(3)*2, 6)
        self.assertEqual(I(3)*I(2), 6)

        
        class dynamicmetaclass(type):
            pass
        class someclass(metaclass=dynamicmetaclass):
            pass
        self.assertNotEqual(someclass, object)

    def test_errors(self):
        
        try:
            class C(list, dict):
                pass
        except TypeError:
            pass
        else:
            self.fail("inheritance from both list and dict should be illegal")

        try:
            class C(object, None):
                pass
        except TypeError:
            pass
        else:
            self.fail("inheritance from non-type should be illegal")
        class Classic:
            pass

        try:
            class C(type(len)):
                pass
        except TypeError:
            pass
        else:
            self.fail("inheritance from CFunction should be illegal")

        try:
            class C(object):
                __slots__ = 1
        except TypeError:
            pass
        else:
            self.fail("__slots__ = 1 should be illegal")

        try:
            class C(object):
                __slots__ = [1]
        except TypeError:
            pass
        else:
            self.fail("__slots__ = [1] should be illegal")

        class M1(type):
            pass
        class M2(type):
            pass
        class A1(object, metaclass=M1):
            pass
        class A2(object, metaclass=M2):
            pass
        try:
            class B(A1, A2):
                pass
        except TypeError:
            pass
        else:
            self.fail("finding the most derived metaclass should have failed")

    def test_classmethods(self):
        
        class C(object):
            def foo(*a): return a
            goo = classmethod(foo)
        c = C()
        self.assertEqual(C.goo(1), (C, 1))
        self.assertEqual(c.goo(1), (C, 1))
        self.assertEqual(c.foo(1), (c, 1))
        class D(C):
            pass
        d = D()
        self.assertEqual(D.goo(1), (D, 1))
        self.assertEqual(d.goo(1), (D, 1))
        self.assertEqual(d.foo(1), (d, 1))
        self.assertEqual(D.foo(d, 1), (d, 1))
        
        def f(cls, arg):
            "f docstring"
            return (cls, arg)
        ff = classmethod(f)
        self.assertEqual(ff.__get__(0, int)(42), (int, 42))
        self.assertEqual(ff.__get__(0)(42), (int, 42))

        
        self.assertEqual(C.goo.__self__, C)
        self.assertEqual(D.goo.__self__, D)
        self.assertEqual(super(D,D).goo.__self__, D)
        self.assertEqual(super(D,d).goo.__self__, D)
        self.assertEqual(super(D,D).goo(), (D,))
        self.assertEqual(super(D,d).goo(), (D,))

        
        meth = classmethod(1).__get__(1)
        self.assertRaises(TypeError, meth)

        
        try:
            classmethod(f, kw=1)
        except TypeError:
            pass
        else:
            self.fail("classmethod shouldn't accept keyword args")

        cm = classmethod(f)
        cm_dict = {'__annotations__': {},
                   '__doc__': "f docstring",
                   '__module__': __name__,
                   '__name__': 'f',
                   '__qualname__': f.__qualname__}
        self.assertEqual(cm.__dict__, cm_dict)

        cm.x = 42
        self.assertEqual(cm.x, 42)
        self.assertEqual(cm.__dict__, {"x" : 42, **cm_dict})
        del cm.x
        self.assertNotHasAttr(cm, "x")

    @support.refcount_test
    def test_refleaks_in_classmethod___init__(self):
        gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
        cm = classmethod(None)
        refs_before = gettotalrefcount()
        for i in range(100):
            cm.__init__(None)
        self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)

    @support.impl_detail("the module 'xxsubtype' is internal")
    @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
    def test_classmethods_in_c(self):
        
        import xxsubtype as spam
        a = (1, 2, 3)
        d = {'abc': 123}
        x, a1, d1 = spam.spamlist.classmeth(*a, **d)
        self.assertEqual(x, spam.spamlist)
        self.assertEqual(a, a1)
        self.assertEqual(d, d1)
        x, a1, d1 = spam.spamlist().classmeth(*a, **d)
        self.assertEqual(x, spam.spamlist)
        self.assertEqual(a, a1)
        self.assertEqual(d, d1)
        spam_cm = spam.spamlist.__dict__['classmeth']
        x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
        self.assertEqual(x2, spam.spamlist)
        self.assertEqual(a2, a1)
        self.assertEqual(d2, d1)
        class SubSpam(spam.spamlist): pass
        x2, a2, d2 = spam_cm(SubSpam, *a, **d)
        self.assertEqual(x2, SubSpam)
        self.assertEqual(a2, a1)
        self.assertEqual(d2, d1)

        with self.assertRaises(TypeError) as cm:
            spam_cm()
        self.assertEqual(
            str(cm.exception),
            "descriptor 'classmeth' of 'xxsubtype.spamlist' "
            "object needs an argument")

        with self.assertRaises(TypeError) as cm:
            spam_cm(spam.spamlist())
        self.assertEqual(
            str(cm.exception),
            "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
            "needs a type, not a 'xxsubtype.spamlist' as arg 2")

        with self.assertRaises(TypeError) as cm:
            spam_cm(list)
        expected_errmsg = (
            "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
            "but received 'list'")
        self.assertEqual(str(cm.exception), expected_errmsg)

        with self.assertRaises(TypeError) as cm:
            spam_cm.__get__(None, list)
        self.assertEqual(str(cm.exception), expected_errmsg)

    def test_staticmethods(self):
        
        class C(object):
            def foo(*a): return a
            goo = staticmethod(foo)
        c = C()
        self.assertEqual(C.goo(1), (1,))
        self.assertEqual(c.goo(1), (1,))
        self.assertEqual(c.foo(1), (c, 1,))
        class D(C):
            pass
        d = D()
        self.assertEqual(D.goo(1), (1,))
        self.assertEqual(d.goo(1), (1,))
        self.assertEqual(d.foo(1), (d, 1))
        self.assertEqual(D.foo(d, 1), (d, 1))
        sm = staticmethod(None)
        self.assertEqual(sm.__dict__, {'__doc__': None})
        sm.x = 42
        self.assertEqual(sm.x, 42)
        self.assertEqual(sm.__dict__, {"x" : 42, '__doc__': None})
        del sm.x
        self.assertNotHasAttr(sm, "x")

    @support.refcount_test
    def test_refleaks_in_staticmethod___init__(self):
        gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
        sm = staticmethod(None)
        refs_before = gettotalrefcount()
        for i in range(100):
            sm.__init__(None)
        self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)

    @support.impl_detail("the module 'xxsubtype' is internal")
    @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
    def test_staticmethods_in_c(self):
        
        import xxsubtype as spam
        a = (1, 2, 3)
        d = {"abc": 123}
        x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
        self.assertEqual(x, None)
        self.assertEqual(a, a1)
        self.assertEqual(d, d1)
        x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
        self.assertEqual(x, None)
        self.assertEqual(a, a1)
        self.assertEqual(d, d1)

    def test_classic(self):
        
        class C:
            def foo(*a): return a
            goo = classmethod(foo)
        c = C()
        self.assertEqual(C.goo(1), (C, 1))
        self.assertEqual(c.goo(1), (C, 1))
        self.assertEqual(c.foo(1), (c, 1))
        class D(C):
            pass
        d = D()
        self.assertEqual(D.goo(1), (D, 1))
        self.assertEqual(d.goo(1), (D, 1))
        self.assertEqual(d.foo(1), (d, 1))
        self.assertEqual(D.foo(d, 1), (d, 1))
        class E: 
            foo = C.foo
        self.assertEqual(E().foo.__func__, C.foo) 
        self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))

    def test_compattr(self):
        
        class C(object):
            class computed_attribute(object):
                def __init__(self, get, set=None, delete=None):
                    self.__get = get
                    self.__set = set
                    self.__delete = delete
                def __get__(self, obj, type=None):
                    return self.__get(obj)
                def __set__(self, obj, value):
                    return self.__set(obj, value)
                def __delete__(self, obj):
                    return self.__delete(obj)
            def __init__(self):
                self.__x = 0
            def __get_x(self):
                x = self.__x
                self.__x = x+1
                return x
            def __set_x(self, x):
                self.__x = x
            def __delete_x(self):
                del self.__x
            x = computed_attribute(__get_x, __set_x, __delete_x)
        a = C()
        self.assertEqual(a.x, 0)
        self.assertEqual(a.x, 1)
        a.x = 10
        self.assertEqual(a.x, 10)
        self.assertEqual(a.x, 11)
        del a.x
        self.assertNotHasAttr(a, 'x')

    def test_newslots(self):
        
        class C(list):
            def __new__(cls):
                self = list.__new__(cls)
                self.foo = 1
                return self
            def __init__(self):
                self.foo = self.foo + 2
        a = C()
        self.assertEqual(a.foo, 3)
        self.assertEqual(a.__class__, C)
        class D(C):
            pass
        b = D()
        self.assertEqual(b.foo, 3)
        self.assertEqual(b.__class__, D)

    @unittest.expectedFailure
    def test_bad_new(self):
        self.assertRaises(TypeError, object.__new__)
        self.assertRaises(TypeError, object.__new__, '')
        self.assertRaises(TypeError, list.__new__, object)
        self.assertRaises(TypeError, object.__new__, list)
        class C(object):
            __new__ = list.__new__
        self.assertRaises(TypeError, C)
        class C(list):
            __new__ = object.__new__
        self.assertRaises(TypeError, C)

    def test_object_new(self):
        class A(object):
            pass
        object.__new__(A)
        self.assertRaises(TypeError, object.__new__, A, 5)
        object.__init__(A())
        self.assertRaises(TypeError, object.__init__, A(), 5)

        class A(object):
            def __init__(self, foo):
                self.foo = foo
        object.__new__(A)
        object.__new__(A, 5)
        object.__init__(A(3))
        self.assertRaises(TypeError, object.__init__, A(3), 5)

        class A(object):
            def __new__(cls, foo):
                return object.__new__(cls)
        object.__new__(A)
        self.assertRaises(TypeError, object.__new__, A, 5)
        object.__init__(A(3))
        object.__init__(A(3), 5)

        class A(object):
            def __new__(cls, foo):
                return object.__new__(cls)
            def __init__(self, foo):
                self.foo = foo
        object.__new__(A)
        self.assertRaises(TypeError, object.__new__, A, 5)
        object.__init__(A(3))
        self.assertRaises(TypeError, object.__init__, A(3), 5)

    @unittest.expectedFailure
    def test_restored_object_new(self):
        class A(object):
            def __new__(cls, *args, **kwargs):
                raise AssertionError
        self.assertRaises(AssertionError, A)
        class B(A):
            __new__ = object.__new__
            def __init__(self, foo):
                self.foo = foo
        with warnings.catch_warnings():
            warnings.simplefilter('error', DeprecationWarning)
            b = B(3)
        self.assertEqual(b.foo, 3)
        self.assertEqual(b.__class__, B)
        del B.__new__
        self.assertRaises(AssertionError, B)
        del A.__new__
        with warnings.catch_warnings():
            warnings.simplefilter('error', DeprecationWarning)
            b = B(3)
        self.assertEqual(b.foo, 3)
        self.assertEqual(b.__class__, B)

    def test_altmro(self):
        
        class A(object):
            def f(self): return "A"
        class B(A):
            pass
        class C(A):
            def f(self): return "C"
        class D(B, C):
            pass
        self.assertEqual(A.mro(), [A, object])
        self.assertEqual(A.__mro__, (A, object))
        self.assertEqual(B.mro(), [B, A, object])
        self.assertEqual(B.__mro__, (B, A, object))
        self.assertEqual(C.mro(), [C, A, object])
        self.assertEqual(C.__mro__, (C, A, object))
        self.assertEqual(D.mro(), [D, B, C, A, object])
        self.assertEqual(D.__mro__, (D, B, C, A, object))
        self.assertEqual(D().f(), "C")

        class PerverseMetaType(type):
            def mro(cls):
                L = type.mro(cls)
                L.reverse()
                return L
        class X(D,B,C,A, metaclass=PerverseMetaType):
            pass
        self.assertEqual(X.__mro__, (object, A, C, B, D, X))
        self.assertEqual(X().f(), "A")

        try:
            class _metaclass(type):
                def mro(self):
                    return [self, dict, object]
            class X(object, metaclass=_metaclass):
                pass
            
            
            
            
            
            
            x = object.__new__(X)
            x[5] = 6
        except TypeError:
            pass
        else:
            self.fail("devious mro() return not caught")

        try:
            class _metaclass(type):
                def mro(self):
                    return [1]
            class X(object, metaclass=_metaclass):
                pass
        except TypeError:
            pass
        else:
            self.fail("non-class mro() return not caught")

        try:
            class _metaclass(type):
                def mro(self):
                    return 1
            class X(object, metaclass=_metaclass):
                pass
        except TypeError:
            pass
        else:
            self.fail("non-sequence mro() return not caught")

    def test_overloading(self):
        

        class B(object):
            "Intermediate class because object doesn't have a __setattr__"

        class C(B):
            def __getattr__(self, name):
                if name == "foo":
                    return ("getattr", name)
                else:
                    raise AttributeError
            def __setattr__(self, name, value):
                if name == "foo":
                    self.setattr = (name, value)
                else:
                    return B.__setattr__(self, name, value)
            def __delattr__(self, name):
                if name == "foo":
                    self.delattr = name
                else:
                    return B.__delattr__(self, name)

            def __getitem__(self, key):
                return ("getitem", key)
            def __setitem__(self, key, value):
                self.setitem = (key, value)
            def __delitem__(self, key):
                self.delitem = key

        a = C()
        self.assertEqual(a.foo, ("getattr", "foo"))
        a.foo = 12
        self.assertEqual(a.setattr, ("foo", 12))
        del a.foo
        self.assertEqual(a.delattr, "foo")

        self.assertEqual(a[12], ("getitem", 12))
        a[12] = 21
        self.assertEqual(a.setitem, (12, 21))
        del a[12]
        self.assertEqual(a.delitem, 12)

        self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
        a[0:10] = "foo"
        self.assertEqual(a.setitem, (slice(0, 10), "foo"))
        del a[0:10]
        self.assertEqual(a.delitem, (slice(0, 10)))

    def test_load_attr_extended_arg(self):
        
        class Numbers:
            def __getattr__(self, attr):
                return int(attr.lstrip("_"))
        attrs = ", ".join(f"Z._{n:03d}" for n in range(280))
        code = f"def number_attrs(Z):\n    return [ {attrs} ]"
        ns = {}
        exec(code, ns)
        number_attrs = ns["number_attrs"]
        
        for _ in range(30):
            self.assertEqual(number_attrs(Numbers()), list(range(280)))

    def test_methods(self):
        
        class C(object):
            def __init__(self, x):
                self.x = x
            def foo(self):
                return self.x
        c1 = C(1)
        self.assertEqual(c1.foo(), 1)
        class D(C):
            boo = C.foo
            goo = c1.foo
        d2 = D(2)
        self.assertEqual(d2.foo(), 2)
        self.assertEqual(d2.boo(), 2)
        self.assertEqual(d2.goo(), 1)
        class E(object):
            foo = C.foo
        self.assertEqual(E().foo.__func__, C.foo) 
        self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))

    @support.impl_detail("testing error message from implementation")
    def test_methods_in_c(self):
        
        
        
        set_add = set.add

        expected_errmsg = "unbound method set.add() needs an argument"

        with self.assertRaises(TypeError) as cm:
            set_add()
        self.assertEqual(cm.exception.args[0], expected_errmsg)

        expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"

        with self.assertRaises(TypeError) as cm:
            set_add(0)
        self.assertEqual(cm.exception.args[0], expected_errmsg)

        with self.assertRaises(TypeError) as cm:
            set_add.__get__(0)
        self.assertEqual(cm.exception.args[0], expected_errmsg)

    def test_special_method_lookup(self):
        
        

        def run_context(manager):
            with manager:
                pass
        def iden(self):
            return self
        def hello(self):
            return b"hello"
        def empty_seq(self):
            return []
        def zero(self):
            return 0
        def complex_num(self):
            return 1j
        def stop(self):
            raise StopIteration
        def return_true(self, thing=None):
            return True
        def do_isinstance(obj):
            return isinstance(int, obj)
        def do_issubclass(obj):
            return issubclass(int, obj)
        def do_dict_missing(checker):
            class DictSub(checker.__class__, dict):
                pass
            self.assertEqual(DictSub()["hi"], 4)
        def some_number(self_, key):
            self.assertEqual(key, "hi")
            return 4
        def swallow(*args): pass
        def format_impl(self, spec):
            return "hello"

        
        
        
        specials = [
            ("__bytes__", bytes, hello, set(), {}),
            ("__reversed__", reversed, empty_seq, set(), {}),
            ("__length_hint__", list, zero, set(),
             {"__iter__" : iden, "__next__" : stop}),
            ("__sizeof__", sys.getsizeof, zero, set(), {}),
            ("__instancecheck__", do_isinstance, return_true, set(), {}),
            ("__missing__", do_dict_missing, some_number,
             set(("__class__",)), {}),
            ("__subclasscheck__", do_issubclass, return_true,
             set(("__bases__",)), {}),
            ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
            ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
            ("__complex__", complex, complex_num, set(), {}),
            ("__format__", format, format_impl, set(), {}),
            ("__floor__", math.floor, zero, set(), {}),
            ("__trunc__", math.trunc, zero, set(), {}),
            ("__ceil__", math.ceil, zero, set(), {}),
            ("__dir__", dir, empty_seq, set(), {}),
            ("__round__", round, zero, set(), {}),
            ]

        class Checker(object):
            def __getattr__(self, attr, test=self):
                test.fail("__getattr__ called with {0}".format(attr))
            def __getattribute__(self, attr, test=self):
                if attr not in ok:
                    test.fail("__getattribute__ called with {0}".format(attr))
                return object.__getattribute__(self, attr)
        class SpecialDescr(object):
            def __init__(self, impl):
                self.impl = impl
            def __get__(self, obj, owner):
                record.append(1)
                return self.impl.__get__(obj, owner)
        class MyException(Exception):
            pass
        class ErrDescr(object):
            def __get__(self, obj, owner):
                raise MyException

        for name, runner, meth_impl, ok, env in specials:
            class X(Checker):
                pass
            for attr, obj in env.items():
                setattr(X, attr, obj)
            setattr(X, name, meth_impl)
            runner(X())

            record = []
            class X(Checker):
                pass
            for attr, obj in env.items():
                setattr(X, attr, obj)
            setattr(X, name, SpecialDescr(meth_impl))
            runner(X())
            self.assertEqual(record, [1], name)

            class X(Checker):
                pass
            for attr, obj in env.items():
                setattr(X, attr, obj)
            setattr(X, name, ErrDescr())
            self.assertRaises(MyException, runner, X())

    def test_specials(self):
        
        

        
        class C(object):
            def __getitem__(self, i):
                if 0 <= i < 10: return i
                raise IndexError
        c1 = C()
        c2 = C()
        self.assertFalse(not c1)
        self.assertNotEqual(id(c1), id(c2))
        hash(c1)
        hash(c2)
        self.assertEqual(c1, c1)
        self.assertTrue(c1 != c2)
        self.assertFalse(c1 != c1)
        self.assertFalse(c1 == c2)
        
        
        self.assertGreaterEqual(str(c1).find('C object at '), 0)
        self.assertEqual(str(c1), repr(c1))
        self.assertNotIn(-1, c1)
        for i in range(10):
            self.assertIn(i, c1)
        self.assertNotIn(10, c1)
        
        class D(object):
            def __getitem__(self, i):
                if 0 <= i < 10: return i
                raise IndexError
        d1 = D()
        d2 = D()
        self.assertFalse(not d1)
        self.assertNotEqual(id(d1), id(d2))
        hash(d1)
        hash(d2)
        self.assertEqual(d1, d1)
        self.assertNotEqual(d1, d2)
        self.assertFalse(d1 != d1)
        self.assertFalse(d1 == d2)
        
        
        self.assertGreaterEqual(str(d1).find('D object at '), 0)
        self.assertEqual(str(d1), repr(d1))
        self.assertNotIn(-1, d1)
        for i in range(10):
            self.assertIn(i, d1)
        self.assertNotIn(10, d1)
        
        class Proxy(object):
            def __init__(self, x):
                self.x = x
            def __bool__(self):
                return not not self.x
            def __hash__(self):
                return hash(self.x)
            def __eq__(self, other):
                return self.x == other
            def __ne__(self, other):
                return self.x != other
            def __ge__(self, other):
                return self.x >= other
            def __gt__(self, other):
                return self.x > other
            def __le__(self, other):
                return self.x <= other
            def __lt__(self, other):
                return self.x < other
            def __str__(self):
                return "Proxy:%s" % self.x
            def __repr__(self):
                return "Proxy(%r)" % self.x
            def __contains__(self, value):
                return value in self.x
        p0 = Proxy(0)
        p1 = Proxy(1)
        p_1 = Proxy(-1)
        self.assertFalse(p0)
        self.assertFalse(not p1)
        self.assertEqual(hash(p0), hash(0))
        self.assertEqual(p0, p0)
        self.assertNotEqual(p0, p1)
        self.assertFalse(p0 != p0)
        self.assertEqual(not p0, p1)
        self.assertTrue(p0 < p1)
        self.assertTrue(p0 <= p1)
        self.assertTrue(p1 > p0)
        self.assertTrue(p1 >= p0)
        self.assertEqual(str(p0), "Proxy:0")
        self.assertEqual(repr(p0), "Proxy(0)")
        p10 = Proxy(range(10))
        self.assertNotIn(-1, p10)
        for i in range(10):
            self.assertIn(i, p10)
        self.assertNotIn(10, p10)

    def test_weakrefs(self):
        
        import weakref
        class C(object):
            pass
        c = C()
        r = weakref.ref(c)
        self.assertEqual(r(), c)
        del c
        support.gc_collect()
        self.assertEqual(r(), None)
        del r
        class NoWeak(object):
            __slots__ = ['foo']
        no = NoWeak()
        try:
            weakref.ref(no)
        except TypeError as msg:
            self.assertIn("weak reference", str(msg))
        else:
            self.fail("weakref.ref(no) should be illegal")
        class Weak(object):
            __slots__ = ['foo', '__weakref__']
        yes = Weak()
        r = weakref.ref(yes)
        self.assertEqual(r(), yes)
        del yes
        support.gc_collect()
        self.assertEqual(r(), None)
        del r

    def test_properties(self):
        
        class C(object):
            def getx(self):
                return self.__x
            def setx(self, value):
                self.__x = value
            def delx(self):
                del self.__x
            x = property(getx, setx, delx, doc="I'm the x property.")
        a = C()
        self.assertNotHasAttr(a, "x")
        a.x = 42
        self.assertEqual(a._C__x, 42)
        self.assertEqual(a.x, 42)
        del a.x
        self.assertNotHasAttr(a, "x")
        self.assertNotHasAttr(a, "_C__x")
        C.x.__set__(a, 100)
        self.assertEqual(C.x.__get__(a), 100)
        C.x.__delete__(a)
        self.assertNotHasAttr(a, "x")

        raw = C.__dict__['x']
        self.assertIsInstance(raw, property)

        attrs = dir(raw)
        self.assertIn("__doc__", attrs)
        self.assertIn("fget", attrs)
        self.assertIn("fset", attrs)
        self.assertIn("fdel", attrs)

        self.assertEqual(raw.__doc__, "I'm the x property.")
        self.assertIs(raw.fget, C.__dict__['getx'])
        self.assertIs(raw.fset, C.__dict__['setx'])
        self.assertIs(raw.fdel, C.__dict__['delx'])

        for attr in "fget", "fset", "fdel":
            try:
                setattr(raw, attr, 42)
            except AttributeError as msg:
                if str(msg).find('readonly') < 0:
                    self.fail("when setting readonly attr %r on a property, "
                              "got unexpected AttributeError msg %r" % (attr, str(msg)))
            else:
                self.fail("expected AttributeError from trying to set readonly %r "
                          "attr on a property" % attr)

        raw.__doc__ = 42
        self.assertEqual(raw.__doc__, 42)

        class D(object):
            __getitem__ = property(lambda s: 1/0)

        d = D()
        try:
            for i in d:
                str(i)
        except ZeroDivisionError:
            pass
        else:
            self.fail("expected ZeroDivisionError from bad property")

    @unittest.skipIf(sys.flags.optimize >= 2,
                     "Docstrings are omitted with -O2 and above")
    def test_properties_doc_attrib(self):
        class E(object):
            def getter(self):
                "getter method"
                return 0
            def setter(self_, value):
                "setter method"
                pass
            prop = property(getter)
            self.assertEqual(prop.__doc__, "getter method")
            prop2 = property(fset=setter)
            self.assertEqual(prop2.__doc__, None)

    @support.cpython_only
    def test_testcapi_no_segfault(self):
        
        try:
            import _testcapi
        except ImportError:
            pass
        else:
            class X(object):
                p = property(_testcapi.test_with_docstring)

    def test_properties_plus(self):
        class C(object):
            foo = property(doc="hello")
            @foo.getter
            def foo(self):
                return self._foo
            @foo.setter
            def foo(self, value):
                self._foo = abs(value)
            @foo.deleter
            def foo(self):
                del self._foo
        c = C()
        self.assertEqual(C.foo.__doc__, "hello")
        self.assertNotHasAttr(c, "foo")
        c.foo = -42
        self.assertHasAttr(c, '_foo')
        self.assertEqual(c._foo, 42)
        self.assertEqual(c.foo, 42)
        del c.foo
        self.assertNotHasAttr(c, '_foo')
        self.assertNotHasAttr(c, "foo")

        class D(C):
            @C.foo.deleter
            def foo(self):
                try:
                    del self._foo
                except AttributeError:
                    pass
        d = D()
        d.foo = 24
        self.assertEqual(d.foo, 24)
        del d.foo
        del d.foo

        class E(object):
            @property
            def foo(self):
                return self._foo
            @foo.setter
            def foo(self, value):
                raise RuntimeError
            @foo.setter
            def foo(self, value):
                self._foo = abs(value)
            @foo.deleter
            def foo(self, value=None):
                del self._foo

        e = E()
        e.foo = -42
        self.assertEqual(e.foo, 42)
        del e.foo

        class F(E):
            @E.foo.deleter
            def foo(self):
                del self._foo
            @foo.setter
            def foo(self, value):
                self._foo = max(0, value)
        f = F()
        f.foo = -10
        self.assertEqual(f.foo, 0)
        del f.foo

    def test_dict_constructors(self):
        
        d = dict()
        self.assertEqual(d, {})
        d = dict({})
        self.assertEqual(d, {})
        d = dict({1: 2, 'a': 'b'})
        self.assertEqual(d, {1: 2, 'a': 'b'})
        self.assertEqual(d, dict(list(d.items())))
        self.assertEqual(d, dict(iter(d.items())))
        d = dict({'one':1, 'two':2})
        self.assertEqual(d, dict(one=1, two=2))
        self.assertEqual(d, dict(**d))
        self.assertEqual(d, dict({"one": 1}, two=2))
        self.assertEqual(d, dict([("two", 2)], one=1))
        self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
        self.assertEqual(d, dict(**d))

        for badarg in 0, 0, 0j, "0", [0], (0,):
            try:
                dict(badarg)
            except TypeError:
                pass
            except ValueError:
                if badarg == "0":
                    
                    
                    
                    pass
                else:
                    self.fail("no TypeError from dict(%r)" % badarg)
            else:
                self.fail("no TypeError from dict(%r)" % badarg)

        with self.assertRaises(TypeError):
            dict({}, {})

        class Mapping:
            
            dict = {1:2, 3:4, 'a':1j}

        try:
            dict(Mapping())
        except TypeError:
            pass
        else:
            self.fail("no TypeError from dict(incomplete mapping)")

        Mapping.keys = lambda self: list(self.dict.keys())
        Mapping.__getitem__ = lambda self, i: self.dict[i]
        d = dict(Mapping())
        self.assertEqual(d, Mapping.dict)

        
        class AddressBookEntry:
            def __init__(self, first, last):
                self.first = first
                self.last = last
            def __iter__(self):
                return iter([self.first, self.last])

        d = dict([AddressBookEntry('Tim', 'Warsaw'),
                  AddressBookEntry('Barry', 'Peters'),
                  AddressBookEntry('Tim', 'Peters'),
                  AddressBookEntry('Barry', 'Warsaw')])
        self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})

        d = dict(zip(range(4), range(1, 5)))
        self.assertEqual(d, dict([(i, i+1) for i in range(4)]))

        
        for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
            try:
                dict(bad)
            except ValueError:
                pass
            else:
                self.fail("no ValueError from dict(%r)" % bad)

    def test_dir(self):
        
        junk = 12
        self.assertEqual(dir(), ['junk', 'self'])
        del junk

        
        for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
            dir(arg)

        
        
        def interesting(strings):
            return [s for s in strings if not s.startswith('_')]

        class C(object):
            Cdata = 1
            def Cmethod(self): pass

        cstuff = ['Cdata', 'Cmethod']
        self.assertEqual(interesting(dir(C)), cstuff)

        c = C()
        self.assertEqual(interesting(dir(c)), cstuff)
        

        c.cdata = 2
        c.cmethod = lambda self: 0
        self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
        

        class A(C):
            Adata = 1
            def Amethod(self): pass

        astuff = ['Adata', 'Amethod'] + cstuff
        self.assertEqual(interesting(dir(A)), astuff)
        
        a = A()
        self.assertEqual(interesting(dir(a)), astuff)
        a.adata = 42
        a.amethod = lambda self: 3
        self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
        

        
        class M(type(sys)):
            pass
        minstance = M("m")
        minstance.b = 2
        minstance.a = 1
        default_attributes = ['__name__', '__doc__', '__package__',
                              '__loader__', '__spec__']
        names = [x for x in dir(minstance) if x not in default_attributes]
        self.assertEqual(names, ['a', 'b'])

        class M2(M):
            def getdict(self):
                return "Not a dict!"
            __dict__ = property(getdict)

        m2instance = M2("m2")
        m2instance.b = 2
        m2instance.a = 1
        self.assertEqual(m2instance.__dict__, "Not a dict!")
        with self.assertRaises(TypeError):
            dir(m2instance)

        
        
        self.assertEqual(dir(object()), dir(Ellipsis))

        
        class Wrapper(object):
            def __init__(self, obj):
                self.__obj = obj
            def __repr__(self):
                return "Wrapper(%s)" % repr(self.__obj)
            def __getitem__(self, key):
                return Wrapper(self.__obj[key])
            def __len__(self):
                return len(self.__obj)
            def __getattr__(self, name):
                return Wrapper(getattr(self.__obj, name))

        class C(object):
            def __getclass(self):
                return Wrapper(type(self))
            __class__ = property(__getclass)

        dir(C()) 

    def test_supers(self):
        

        class A(object):
            def meth(self, a):
                return "A(%r)" % a

        self.assertEqual(A().meth(1), "A(1)")

        class B(A):
            def __init__(self):
                self.__super = super(B, self)
            def meth(self, a):
                return "B(%r)" % a + self.__super.meth(a)

        self.assertEqual(B().meth(2), "B(2)A(2)")

        class C(A):
            def meth(self, a):
                return "C(%r)" % a + self.__super.meth(a)
        C._C__super = super(C)

        self.assertEqual(C().meth(3), "C(3)A(3)")

        class D(C, B):
            def meth(self, a):
                return "D(%r)" % a + super(D, self).meth(a)

        self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")

        

        class mysuper(super):
            def __init__(self, *args):
                return super(mysuper, self).__init__(*args)

        class E(D):
            def meth(self, a):
                return "E(%r)" % a + mysuper(E, self).meth(a)

        self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")

        class F(E):
            def meth(self, a):
                s = self.__super 
                return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
        F._F__super = mysuper(F)

        self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")

        

        try:
            super(D, 42)
        except TypeError:
            pass
        else:
            self.fail("shouldn't allow super(D, 42)")

        try:
            super(D, C())
        except TypeError:
            pass
        else:
            self.fail("shouldn't allow super(D, C())")

        try:
            super(D).__get__(12)
        except TypeError:
            pass
        else:
            self.fail("shouldn't allow super(D).__get__(12)")

        try:
            super(D).__get__(C())
        except TypeError:
            pass
        else:
            self.fail("shouldn't allow super(D).__get__(C())")

        
        

        class DDbase(object):
            def getx(self): return 42
            x = property(getx)

        class DDsub(DDbase):
            def getx(self): return "hello"
            x = property(getx)

        dd = DDsub()
        self.assertEqual(dd.x, "hello")
        self.assertEqual(super(DDsub, dd).x, 42)

        
        

        class Base(object):
            aProp = property(lambda self: "foo")

        class Sub(Base):
            @classmethod
            def test(klass):
                return super(Sub,klass).aProp

        self.assertEqual(Sub.test(), Base.aProp)

        
        with self.assertRaises(TypeError):
            super(Base, kw=1)

    def test_basic_inheritance(self):
        

        class hexint(int):
            def __repr__(self):
                return hex(self)
            def __add__(self, other):
                return hexint(int.__add__(self, other))
            
            
        self.assertEqual(repr(hexint(7) + 9), "0x10")
        self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
        a = hexint(12345)
        self.assertEqual(a, 12345)
        self.assertEqual(int(a), 12345)
        self.assertIs(int(a).__class__, int)
        self.assertEqual(hash(a), hash(12345))
        self.assertIs((+a).__class__, int)
        self.assertIs((a >> 0).__class__, int)
        self.assertIs((a << 0).__class__, int)
        self.assertIs((hexint(0) << 12).__class__, int)
        self.assertIs((hexint(0) >> 12).__class__, int)

        class octlong(int):
            __slots__ = []
            def __str__(self):
                return oct(self)
            def __add__(self, other):
                return self.__class__(super(octlong, self).__add__(other))
            __radd__ = __add__
        self.assertEqual(str(octlong(3) + 5), "0o10")
        
        
        self.assertEqual(str(5 + octlong(3000)), "0o5675")
        a = octlong(12345)
        self.assertEqual(a, 12345)
        self.assertEqual(int(a), 12345)
        self.assertEqual(hash(a), hash(12345))
        self.assertIs(int(a).__class__, int)
        self.assertIs((+a).__class__, int)
        self.assertIs((-a).__class__, int)
        self.assertIs((-octlong(0)).__class__, int)
        self.assertIs((a >> 0).__class__, int)
        self.assertIs((a << 0).__class__, int)
        self.assertIs((a - 0).__class__, int)
        self.assertIs((a * 1).__class__, int)
        self.assertIs((a ** 1).__class__, int)
        self.assertIs((a // 1).__class__, int)
        self.assertIs((1 * a).__class__, int)
        self.assertIs((a | 0).__class__, int)
        self.assertIs((a ^ 0).__class__, int)
        self.assertIs((a & -1).__class__, int)
        self.assertIs((octlong(0) << 12).__class__, int)
        self.assertIs((octlong(0) >> 12).__class__, int)
        self.assertIs(abs(octlong(0)).__class__, int)

        
        
        class longclone(int):
            pass
        a = longclone(1)
        self.assertIs((a + 0).__class__, int)
        self.assertIs((0 + a).__class__, int)

        
        a = longclone(-1)
        self.assertEqual(a.__dict__, {})
        self.assertEqual(int(a), -1)  

        class precfloat(float):
            __slots__ = ['prec']
            def __init__(self, value=0.0, prec=12):
                self.prec = int(prec)
            def __repr__(self):
                return "%.*g" % (self.prec, self)
        self.assertEqual(repr(precfloat(1.1)), "1.1")
        a = precfloat(12345)
        self.assertEqual(a, 12345.0)
        self.assertEqual(float(a), 12345.0)
        self.assertIs(float(a).__class__, float)
        self.assertEqual(hash(a), hash(12345.0))
        self.assertIs((+a).__class__, float)

        class madcomplex(complex):
            def __repr__(self):
                return "%.17gj%+.17g" % (self.imag, self.real)
        a = madcomplex(-3, 4)
        self.assertEqual(repr(a), "4j-3")
        base = complex(-3, 4)
        self.assertEqual(base.__class__, complex)
        self.assertEqual(a, base)
        self.assertEqual(complex(a), base)
        self.assertEqual(complex(a).__class__, complex)
        a = madcomplex(a)  
        self.assertEqual(repr(a), "4j-3")
        self.assertEqual(a, base)
        self.assertEqual(complex(a), base)
        self.assertEqual(complex(a).__class__, complex)
        self.assertEqual(hash(a), hash(base))
        self.assertEqual((+a).__class__, complex)
        self.assertEqual((a + 0).__class__, complex)
        self.assertEqual(a + 0, base)
        self.assertEqual((a - 0).__class__, complex)
        self.assertEqual(a - 0, base)
        self.assertEqual((a * 1).__class__, complex)
        self.assertEqual(a * 1, base)
        self.assertEqual((a / 1).__class__, complex)
        self.assertEqual(a / 1, base)

        class madtuple(tuple):
            _rev = None
            def rev(self):
                if self._rev is not None:
                    return self._rev
                L = list(self)
                L.reverse()
                self._rev = self.__class__(L)
                return self._rev
        a = madtuple((1,2,3,4,5,6,7,8,9,0))
        self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
        self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
        self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
        for i in range(512):
            t = madtuple(range(i))
            u = t.rev()
            v = u.rev()
            self.assertEqual(v, t)
        a = madtuple((1,2,3,4,5))
        self.assertEqual(tuple(a), (1,2,3,4,5))
        self.assertIs(tuple(a).__class__, tuple)
        self.assertEqual(hash(a), hash((1,2,3,4,5)))
        self.assertIs(a[:].__class__, tuple)
        self.assertIs((a * 1).__class__, tuple)
        self.assertIs((a * 0).__class__, tuple)
        self.assertIs((a + ()).__class__, tuple)
        a = madtuple(())
        self.assertEqual(tuple(a), ())
        self.assertIs(tuple(a).__class__, tuple)
        self.assertIs((a + a).__class__, tuple)
        self.assertIs((a * 0).__class__, tuple)
        self.assertIs((a * 1).__class__, tuple)
        self.assertIs((a * 2).__class__, tuple)
        self.assertIs(a[:].__class__, tuple)

        class madstring(str):
            _rev = None
            def rev(self):
                if self._rev is not None:
                    return self._rev
                L = list(self)
                L.reverse()
                self._rev = self.__class__("".join(L))
                return self._rev
        s = madstring("abcdefghijklmnopqrstuvwxyz")
        self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
        self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
        self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
        for i in range(256):
            s = madstring("".join(map(chr, range(i))))
            t = s.rev()
            u = t.rev()
            self.assertEqual(u, s)
        s = madstring("12345")
        self.assertEqual(str(s), "12345")
        self.assertIs(str(s).__class__, str)

        base = "\x00" * 5
        s = madstring(base)
        self.assertEqual(s, base)
        self.assertEqual(str(s), base)
        self.assertIs(str(s).__class__, str)
        self.assertEqual(hash(s), hash(base))
        self.assertEqual({s: 1}[base], 1)
        self.assertEqual({base: 1}[s], 1)
        self.assertIs((s + "").__class__, str)
        self.assertEqual(s + "", base)
        self.assertIs(("" + s).__class__, str)
        self.assertEqual("" + s, base)
        self.assertIs((s * 0).__class__, str)
        self.assertEqual(s * 0, "")
        self.assertIs((s * 1).__class__, str)
        self.assertEqual(s * 1, base)
        self.assertIs((s * 2).__class__, str)
        self.assertEqual(s * 2, base + base)
        self.assertIs(s[:].__class__, str)
        self.assertEqual(s[:], base)
        self.assertIs(s[0:0].__class__, str)
        self.assertEqual(s[0:0], "")
        self.assertIs(s.strip().__class__, str)
        self.assertEqual(s.strip(), base)
        self.assertIs(s.lstrip().__class__, str)
        self.assertEqual(s.lstrip(), base)
        self.assertIs(s.rstrip().__class__, str)
        self.assertEqual(s.rstrip(), base)
        identitytab = {}
        self.assertIs(s.translate(identitytab).__class__, str)
        self.assertEqual(s.translate(identitytab), base)
        self.assertIs(s.replace("x", "x").__class__, str)
        self.assertEqual(s.replace("x", "x"), base)
        self.assertIs(s.ljust(len(s)).__class__, str)
        self.assertEqual(s.ljust(len(s)), base)
        self.assertIs(s.rjust(len(s)).__class__, str)
        self.assertEqual(s.rjust(len(s)), base)
        self.assertIs(s.center(len(s)).__class__, str)
        self.assertEqual(s.center(len(s)), base)
        self.assertIs(s.lower().__class__, str)
        self.assertEqual(s.lower(), base)

        class madunicode(str):
            _rev = None
            def rev(self):
                if self._rev is not None:
                    return self._rev
                L = list(self)
                L.reverse()
                self._rev = self.__class__("".join(L))
                return self._rev
        u = madunicode("ABCDEF")
        self.assertEqual(u, "ABCDEF")
        self.assertEqual(u.rev(), madunicode("FEDCBA"))
        self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
        base = "12345"
        u = madunicode(base)
        self.assertEqual(str(u), base)
        self.assertIs(str(u).__class__, str)
        self.assertEqual(hash(u), hash(base))
        self.assertEqual({u: 1}[base], 1)
        self.assertEqual({base: 1}[u], 1)
        self.assertIs(u.strip().__class__, str)
        self.assertEqual(u.strip(), base)
        self.assertIs(u.lstrip().__class__, str)
        self.assertEqual(u.lstrip(), base)
        self.assertIs(u.rstrip().__class__, str)
        self.assertEqual(u.rstrip(), base)
        self.assertIs(u.replace("x", "x").__class__, str)
        self.assertEqual(u.replace("x", "x"), base)
        self.assertIs(u.replace("xy", "xy").__class__, str)
        self.assertEqual(u.replace("xy", "xy"), base)
        self.assertIs(u.center(len(u)).__class__, str)
        self.assertEqual(u.center(len(u)), base)
        self.assertIs(u.ljust(len(u)).__class__, str)
        self.assertEqual(u.ljust(len(u)), base)
        self.assertIs(u.rjust(len(u)).__class__, str)
        self.assertEqual(u.rjust(len(u)), base)
        self.assertIs(u.lower().__class__, str)
        self.assertEqual(u.lower(), base)
        self.assertIs(u.upper().__class__, str)
        self.assertEqual(u.upper(), base)
        self.assertIs(u.capitalize().__class__, str)
        self.assertEqual(u.capitalize(), base)
        self.assertIs(u.title().__class__, str)
        self.assertEqual(u.title(), base)
        self.assertIs((u + "").__class__, str)
        self.assertEqual(u + "", base)
        self.assertIs(("" + u).__class__, str)
        self.assertEqual("" + u, base)
        self.assertIs((u * 0).__class__, str)
        self.assertEqual(u * 0, "")
        self.assertIs((u * 1).__class__, str)
        self.assertEqual(u * 1, base)
        self.assertIs((u * 2).__class__, str)
        self.assertEqual(u * 2, base + base)
        self.assertIs(u[:].__class__, str)
        self.assertEqual(u[:], base)
        self.assertIs(u[0:0].__class__, str)
        self.assertEqual(u[0:0], "")

        class sublist(list):
            pass
        a = sublist(range(5))
        self.assertEqual(a, list(range(5)))
        a.append("hello")
        self.assertEqual(a, list(range(5)) + ["hello"])
        a[5] = 5
        self.assertEqual(a, list(range(6)))
        a.extend(range(6, 20))
        self.assertEqual(a, list(range(20)))
        a[-5:] = []
        self.assertEqual(a, list(range(15)))
        del a[10:15]
        self.assertEqual(len(a), 10)
        self.assertEqual(a, list(range(10)))
        self.assertEqual(list(a), list(range(10)))
        self.assertEqual(a[0], 0)
        self.assertEqual(a[9], 9)
        self.assertEqual(a[-10], 0)
        self.assertEqual(a[-1], 9)
        self.assertEqual(a[:5], list(range(5)))

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

    def test_keywords(self):
        
        with self.assertRaisesRegex(TypeError, 'keyword argument'):
            int(x=1)
        with self.assertRaisesRegex(TypeError, 'keyword argument'):
            float(x=2)
        with self.assertRaisesRegex(TypeError, 'keyword argument'):
            bool(x=2)
        self.assertEqual(complex(imag=42, real=666), complex(666, 42))
        self.assertEqual(str(object=500), '500')
        self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
        with self.assertRaisesRegex(TypeError, 'keyword argument'):
            tuple(sequence=range(3))
        with self.assertRaisesRegex(TypeError, 'keyword argument'):
            list(sequence=(0, 1, 2))
        

        for constructor in (int, float, int, complex, str, str,
                            tuple, list):
            try:
                constructor(bogus_keyword_arg=1)
            except TypeError:
                pass
            else:
                self.fail("expected TypeError from bogus keyword argument to %r"
                            % constructor)

    def test_str_subclass_as_dict_key(self):
        

        class cistr(str):
            

            def __init__(self, value):
                self.canonical = value.lower()
                self.hashcode = hash(self.canonical)

            def __eq__(self, other):
                if not isinstance(other, cistr):
                    other = cistr(other)
                return self.canonical == other.canonical

            def __hash__(self):
                return self.hashcode

        self.assertEqual(cistr('ABC'), 'abc')
        self.assertEqual('aBc', cistr('ABC'))
        self.assertEqual(str(cistr('ABC')), 'ABC')

        d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
        self.assertEqual(d[cistr('one')], 1)
        self.assertEqual(d[cistr('tWo')], 2)
        self.assertEqual(d[cistr('THrEE')], 3)
        self.assertIn(cistr('ONe'), d)
        self.assertEqual(d.get(cistr('thrEE')), 3)

    def test_classic_comparisons(self):
        
        class classic:
            pass

        for base in (classic, int, object):
            class C(base):
                def __init__(self, value):
                    self.value = int(value)
                def __eq__(self, other):
                    if isinstance(other, C):
                        return self.value == other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value == other
                    return NotImplemented
                def __ne__(self, other):
                    if isinstance(other, C):
                        return self.value != other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value != other
                    return NotImplemented
                def __lt__(self, other):
                    if isinstance(other, C):
                        return self.value < other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value < other
                    return NotImplemented
                def __le__(self, other):
                    if isinstance(other, C):
                        return self.value <= other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value <= other
                    return NotImplemented
                def __gt__(self, other):
                    if isinstance(other, C):
                        return self.value > other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value > other
                    return NotImplemented
                def __ge__(self, other):
                    if isinstance(other, C):
                        return self.value >= other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value >= other
                    return NotImplemented

            c1 = C(1)
            c2 = C(2)
            c3 = C(3)
            self.assertEqual(c1, 1)
            c = {1: c1, 2: c2, 3: c3}
            for x in 1, 2, 3:
                for y in 1, 2, 3:
                    for op in "<", "<=", "==", "!=", ">", ">=":
                        self.assertEqual(eval("c[x] %s c[y]" % op),
                                     eval("x %s y" % op),
                                     "x=%d, y=%d" % (x, y))
                        self.assertEqual(eval("c[x] %s y" % op),
                                     eval("x %s y" % op),
                                     "x=%d, y=%d" % (x, y))
                        self.assertEqual(eval("x %s c[y]" % op),
                                     eval("x %s y" % op),
                                     "x=%d, y=%d" % (x, y))

    def test_rich_comparisons(self):
        
        class Z(complex):
            pass
        z = Z(1)
        self.assertEqual(z, 1+0j)
        self.assertEqual(1+0j, z)
        class ZZ(complex):
            def __eq__(self, other):
                try:
                    return abs(self - other) <= 1e-6
                except:
                    return NotImplemented
        zz = ZZ(1.0000003)
        self.assertEqual(zz, 1+0j)
        self.assertEqual(1+0j, zz)

        class classic:
            pass
        for base in (classic, int, object, list):
            class C(base):
                def __init__(self, value):
                    self.value = int(value)
                def __cmp__(self_, other):
                    self.fail("shouldn't call __cmp__")
                def __eq__(self, other):
                    if isinstance(other, C):
                        return self.value == other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value == other
                    return NotImplemented
                def __ne__(self, other):
                    if isinstance(other, C):
                        return self.value != other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value != other
                    return NotImplemented
                def __lt__(self, other):
                    if isinstance(other, C):
                        return self.value < other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value < other
                    return NotImplemented
                def __le__(self, other):
                    if isinstance(other, C):
                        return self.value <= other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value <= other
                    return NotImplemented
                def __gt__(self, other):
                    if isinstance(other, C):
                        return self.value > other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value > other
                    return NotImplemented
                def __ge__(self, other):
                    if isinstance(other, C):
                        return self.value >= other.value
                    if isinstance(other, int) or isinstance(other, int):
                        return self.value >= other
                    return NotImplemented
            c1 = C(1)
            c2 = C(2)
            c3 = C(3)
            self.assertEqual(c1, 1)
            c = {1: c1, 2: c2, 3: c3}
            for x in 1, 2, 3:
                for y in 1, 2, 3:
                    for op in "<", "<=", "==", "!=", ">", ">=":
                        self.assertEqual(eval("c[x] %s c[y]" % op),
                                         eval("x %s y" % op),
                                         "x=%d, y=%d" % (x, y))
                        self.assertEqual(eval("c[x] %s y" % op),
                                         eval("x %s y" % op),
                                         "x=%d, y=%d" % (x, y))
                        self.assertEqual(eval("x %s c[y]" % op),
                                         eval("x %s y" % op),
                                         "x=%d, y=%d" % (x, y))

    def test_descrdoc(self):
        
        from _io import FileIO
        def check(descr, what):
            self.assertEqual(descr.__doc__, what)
        check(FileIO.closed, "True if the file is closed") 
        check(complex.real, "the real part of a complex number") 

    def test_doc_descriptor(self):
        
        
        class DocDescr(object):
            def __get__(self, object, otype):
                if object:
                    object = object.__class__.__name__ + ' instance'
                if otype:
                    otype = otype.__name__
                return 'object=%s; type=%s' % (object, otype)
        class NewClass:
            __doc__ = DocDescr()
        self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
        self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')

    def test_set_class(self):
        
        class C(object): pass
        class D(object): pass
        class E(object): pass
        class F(D, E): pass
        for cls in C, D, E, F:
            for cls2 in C, D, E, F:
                x = cls()
                x.__class__ = cls2
                self.assertIs(x.__class__, cls2)
                x.__class__ = cls
                self.assertIs(x.__class__, cls)
        def cant(x, C):
            try:
                x.__class__ = C
            except TypeError:
                pass
            else:
                self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
            try:
                delattr(x, "__class__")
            except (TypeError, AttributeError):
                pass
            else:
                self.fail("shouldn't allow del %r.__class__" % x)
        cant(C(), list)
        cant(list(), C)
        cant(C(), 1)
        cant(C(), object)
        cant(object(), list)
        cant(list(), object)
        class Int(int): __slots__ = []
        cant(True, int)
        cant(2, bool)
        o = object()
        cant(o, int)
        cant(o, type(None))
        del o
        class G(object):
            __slots__ = ["a", "b"]
        class H(object):
            __slots__ = ["b", "a"]
        class I(object):
            __slots__ = ["a", "b"]
        class J(object):
            __slots__ = ["c", "b"]
        class K(object):
            __slots__ = ["a", "b", "d"]
        class L(H):
            __slots__ = ["e"]
        class M(I):
            __slots__ = ["e"]
        class N(J):
            __slots__ = ["__weakref__"]
        class P(J):
            __slots__ = ["__dict__"]
        class Q(J):
            pass
        class R(J):
            __slots__ = ["__dict__", "__weakref__"]

        for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
            x = cls()
            x.a = 1
            x.__class__ = cls2
            self.assertIs(x.__class__, cls2,
                   "assigning %r as __class__ for %r silently failed" % (cls2, x))
            self.assertEqual(x.a, 1)
            x.__class__ = cls
            self.assertIs(x.__class__, cls,
                   "assigning %r as __class__ for %r silently failed" % (cls, x))
            self.assertEqual(x.a, 1)
        for cls in G, J, K, L, M, N, P, R, list, Int:
            for cls2 in G, J, K, L, M, N, P, R, list, Int:
                if cls is cls2:
                    continue
                cant(cls(), cls2)

        
        
        class O(object):
            pass
        class A(object):
            def __del__(self):
                self.__class__ = O
        l = [A() for x in range(100)]
        del l

    def test_set_dict(self):
        
        class C(object): pass
        a = C()
        a.__dict__ = {'b': 1}
        self.assertEqual(a.b, 1)
        def cant(x, dict):
            try:
                x.__dict__ = dict
            except (AttributeError, TypeError):
                pass
            else:
                self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
        cant(a, None)
        cant(a, [])
        cant(a, 1)
        del a.__dict__ 

        class Base(object):
            pass
        def verify_dict_readonly(x):
            
            cant(x, {})
            try:
                del x.__dict__
            except (AttributeError, TypeError):
                pass
            else:
                self.fail("shouldn't allow del %r.__dict__" % x)
            dict_descr = Base.__dict__["__dict__"]
            try:
                dict_descr.__set__(x, {})
            except (AttributeError, TypeError):
                pass
            else:
                self.fail("dict_descr allowed access to %r's dict" % x)

        
        class Meta1(type, Base):
            pass
        class Meta2(Base, type):
            pass
        class D(object, metaclass=Meta1):
            pass
        class E(object, metaclass=Meta2):
            pass
        for cls in C, D, E:
            verify_dict_readonly(cls)
            class_dict = cls.__dict__
            try:
                class_dict["spam"] = "eggs"
            except TypeError:
                pass
            else:
                self.fail("%r's __dict__ can be modified" % cls)

        
        class Module1(types.ModuleType, Base):
            pass
        class Module2(Base, types.ModuleType):
            pass
        for ModuleType in Module1, Module2:
            mod = ModuleType("spam")
            verify_dict_readonly(mod)
            mod.__dict__["spam"] = "eggs"

        
        
        
        
        def can_delete_dict(e):
            try:
                del e.__dict__
            except (TypeError, AttributeError):
                return False
            else:
                return True
        class Exception1(Exception, Base):
            pass
        class Exception2(Base, Exception):
            pass
        for ExceptionType in Exception, Exception1, Exception2:
            e = ExceptionType()
            e.__dict__ = {"a": 1}
            self.assertEqual(e.a, 1)
            self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))

    def test_binary_operator_override(self):
        
        class I(int):
            def __repr__(self):
                return "I(%r)" % int(self)
            def __add__(self, other):
                return I(int(self) + int(other))
            __radd__ = __add__
            def __pow__(self, other, mod=None):
                if mod is None:
                    return I(pow(int(self), int(other)))
                else:
                    return I(pow(int(self), int(other), int(mod)))
            def __rpow__(self, other, mod=None):
                if mod is None:
                    return I(pow(int(other), int(self), mod))
                else:
                    return I(pow(int(other), int(self), int(mod)))

        self.assertEqual(repr(I(1) + I(2)), "I(3)")
        self.assertEqual(repr(I(1) + 2), "I(3)")
        self.assertEqual(repr(1 + I(2)), "I(3)")
        self.assertEqual(repr(I(2) ** I(3)), "I(8)")
        self.assertEqual(repr(2 ** I(3)), "I(8)")
        self.assertEqual(repr(I(2) ** 3), "I(8)")
        self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
        class S(str):
            def __eq__(self, other):
                return self.lower() == other.lower()

    def test_subclass_propagation(self):
        
        class A(object):
            pass
        class B(A):
            pass
        class C(A):
            pass
        class D(B, C):
            pass
        d = D()
        orig_hash = hash(d) 
        A.__hash__ = lambda self: 42
        self.assertEqual(hash(d), 42)
        C.__hash__ = lambda self: 314
        self.assertEqual(hash(d), 314)
        B.__hash__ = lambda self: 144
        self.assertEqual(hash(d), 144)
        D.__hash__ = lambda self: 100
        self.assertEqual(hash(d), 100)
        D.__hash__ = None
        self.assertRaises(TypeError, hash, d)
        del D.__hash__
        self.assertEqual(hash(d), 144)
        B.__hash__ = None
        self.assertRaises(TypeError, hash, d)
        del B.__hash__
        self.assertEqual(hash(d), 314)
        C.__hash__ = None
        self.assertRaises(TypeError, hash, d)
        del C.__hash__
        self.assertEqual(hash(d), 42)
        A.__hash__ = None
        self.assertRaises(TypeError, hash, d)
        del A.__hash__
        self.assertEqual(hash(d), orig_hash)
        d.foo = 42
        d.bar = 42
        self.assertEqual(d.foo, 42)
        self.assertEqual(d.bar, 42)
        def __getattribute__(self, name):
            if name == "foo":
                return 24
            return object.__getattribute__(self, name)
        A.__getattribute__ = __getattribute__
        self.assertEqual(d.foo, 24)
        self.assertEqual(d.bar, 42)
        def __getattr__(self, name):
            if name in ("spam", "foo", "bar"):
                return "hello"
            raise AttributeError(name)
        B.__getattr__ = __getattr__
        self.assertEqual(d.spam, "hello")
        self.assertEqual(d.foo, 24)
        self.assertEqual(d.bar, 42)
        del A.__getattribute__
        self.assertEqual(d.foo, 42)
        del d.foo
        self.assertEqual(d.foo, "hello")
        self.assertEqual(d.bar, 42)
        del B.__getattr__
        try:
            d.foo
        except AttributeError:
            pass
        else:
            self.fail("d.foo should be undefined now")

        
        class A(object):
            pass
        class B(A):
            pass
        del B
        support.gc_collect()
        A.__setitem__ = lambda *a: None 

    def test_buffer_inheritance(self):
        

        import binascii
        

        class MyBytes(bytes):
            pass
        base = b'abc'
        m = MyBytes(base)
        
        
        self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))

        class MyInt(int):
            pass
        m = MyInt(42)
        try:
            binascii.b2a_hex(m)
            self.fail('subclass of int should not have a buffer interface')
        except TypeError:
            pass

    def test_str_of_str_subclass(self):
        
        import binascii

        class octetstring(str):
            def __str__(self):
                return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
            def __repr__(self):
                return self + " repr"

        o = octetstring('A')
        self.assertEqual(type(o), octetstring)
        self.assertEqual(type(str(o)), str)
        self.assertEqual(type(repr(o)), str)
        self.assertEqual(ord(o), 0x41)
        self.assertEqual(str(o), '41')
        self.assertEqual(repr(o), 'A repr')
        self.assertEqual(o.__str__(), '41')
        self.assertEqual(o.__repr__(), 'A repr')

    def test_repr_with_module_str_subclass(self):
        
        class StrSub(str):
            pass
        class Some:
            pass
        Some.__module__ = StrSub('example')
        self.assertIsInstance(repr(Some), str)  
        self.assertIsInstance(repr(Some()), str)  

    def test_keyword_arguments(self):
        
        def f(a): return a
        self.assertEqual(f.__call__(a=42), 42)
        ba = bytearray()
        bytearray.__init__(ba, 'abc\xbd\u20ac',
                           encoding='latin1', errors='replace')
        self.assertEqual(ba, b'abc\xbd?')

    def test_recursive_call(self):
        
        class A(object):
            pass

        A.__call__ = A()
        with self.assertRaises(RecursionError):
            A()()

    def test_delete_hook(self):
        
        log = []
        class C(object):
            def __del__(self):
                log.append(1)
        c = C()
        self.assertEqual(log, [])
        del c
        support.gc_collect()
        self.assertEqual(log, [1])

        class D(object): pass
        d = D()
        try: del d[0]
        except TypeError: pass
        else: self.fail("invalid del() didn't raise TypeError")

    def test_hash_inheritance(self):
        

        class mydict(dict):
            pass
        d = mydict()
        try:
            hash(d)
        except TypeError:
            pass
        else:
            self.fail("hash() of dict subclass should fail")

        class mylist(list):
            pass
        d = mylist()
        try:
            hash(d)
        except TypeError:
            pass
        else:
            self.fail("hash() of list subclass should fail")

    def test_str_operations(self):
        try: 'a' + 5
        except TypeError: pass
        else: self.fail("'' + 5 doesn't raise TypeError")

        try: ''.split('')
        except ValueError: pass
        else: self.fail("''.split('') doesn't raise ValueError")

        try: ''.join([0])
        except TypeError: pass
        else: self.fail("''.join([0]) doesn't raise TypeError")

        try: ''.rindex('5')
        except ValueError: pass
        else: self.fail("''.rindex('5') doesn't raise ValueError")

        try: '%(n)s' % None
        except TypeError: pass
        else: self.fail("'%(n)s' % None doesn't raise TypeError")

        try: '%(n' % {}
        except ValueError: pass
        else: self.fail("'%(n' % {} '' doesn't raise ValueError")

        try: '%*s' % ('abc')
        except TypeError: pass
        else: self.fail("'%*s' % ('abc') doesn't raise TypeError")

        try: '%*.*s' % ('abc', 5)
        except TypeError: pass
        else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")

        try: '%s' % (1, 2)
        except TypeError: pass
        else: self.fail("'%s' % (1, 2) doesn't raise TypeError")

        try: '%' % None
        except ValueError: pass
        else: self.fail("'%' % None doesn't raise ValueError")

        self.assertEqual('534253'.isdigit(), 1)
        self.assertEqual('534253x'.isdigit(), 0)
        self.assertEqual('%c' % 5, '\x05')
        self.assertEqual('%c' % '5', '5')

    def test_deepcopy_recursive(self):
        
        class Node:
            pass
        a = Node()
        b = Node()
        a.b = b
        b.a = a
        z = deepcopy(a) 

    def test_uninitialized_modules(self):
        
        from types import ModuleType as M
        m = M.__new__(M)
        str(m)
        self.assertNotHasAttr(m, "__name__")
        self.assertNotHasAttr(m, "__file__")
        self.assertNotHasAttr(m, "foo")
        self.assertFalse(m.__dict__)   
        m.foo = 1
        self.assertEqual(m.__dict__, {"foo": 1})

    def test_funny_new(self):
        
        class C(object):
            def __new__(cls, arg):
                if isinstance(arg, str): return [1, 2, 3]
                elif isinstance(arg, int): return object.__new__(D)
                else: return object.__new__(cls)
        class D(C):
            def __init__(self, arg):
                self.foo = arg
        self.assertEqual(C("1"), [1, 2, 3])
        self.assertEqual(D("1"), [1, 2, 3])
        d = D(None)
        self.assertEqual(d.foo, None)
        d = C(1)
        self.assertIsInstance(d, D)
        self.assertEqual(d.foo, 1)
        d = D(1)
        self.assertIsInstance(d, D)
        self.assertEqual(d.foo, 1)

        class C(object):
            @staticmethod
            def __new__(*args):
                return args
        self.assertEqual(C(1, 2), (C, 1, 2))
        class D(C):
            pass
        self.assertEqual(D(1, 2), (D, 1, 2))

        class C(object):
            @classmethod
            def __new__(*args):
                return args
        self.assertEqual(C(1, 2), (C, C, 1, 2))
        class D(C):
            pass
        self.assertEqual(D(1, 2), (D, D, 1, 2))

    def test_imul_bug(self):
        
        
        class C(object):
            def __imul__(self, other):
                return (self, other)
        x = C()
        y = x
        y *= 1.0
        self.assertEqual(y, (x, 1.0))
        y = x
        y *= 2
        self.assertEqual(y, (x, 2))
        y = x
        y *= 3
        self.assertEqual(y, (x, 3))
        y = x
        y *= 1<<100
        self.assertEqual(y, (x, 1<<100))
        y = x
        y *= None
        self.assertEqual(y, (x, None))
        y = x
        y *= "foo"
        self.assertEqual(y, (x, "foo"))

    def test_copy_setstate(self):
        
        import copy
        class C(object):
            def __init__(self, foo=None):
                self.foo = foo
                self.__foo = foo
            def setfoo(self, foo=None):
                self.foo = foo
            def getfoo(self):
                return self.__foo
            def __getstate__(self):
                return [self.foo]
            def __setstate__(self_, lst):
                self.assertEqual(len(lst), 1)
                self_.__foo = self_.foo = lst[0]
        a = C(42)
        a.setfoo(24)
        self.assertEqual(a.foo, 24)
        self.assertEqual(a.getfoo(), 42)
        b = copy.copy(a)
        self.assertEqual(b.foo, 24)
        self.assertEqual(b.getfoo(), 24)
        b = copy.deepcopy(a)
        self.assertEqual(b.foo, 24)
        self.assertEqual(b.getfoo(), 24)

    def test_slices(self):
        

        
        self.assertEqual("hello"[:4], "hell")
        self.assertEqual("hello"[slice(4)], "hell")
        self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
        class S(str):
            def __getitem__(self, x):
                return str.__getitem__(self, x)
        self.assertEqual(S("hello")[:4], "hell")
        self.assertEqual(S("hello")[slice(4)], "hell")
        self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
        
        self.assertEqual((1,2,3)[:2], (1,2))
        self.assertEqual((1,2,3)[slice(2)], (1,2))
        self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
        class T(tuple):
            def __getitem__(self, x):
                return tuple.__getitem__(self, x)
        self.assertEqual(T((1,2,3))[:2], (1,2))
        self.assertEqual(T((1,2,3))[slice(2)], (1,2))
        self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
        
        self.assertEqual([1,2,3][:2], [1,2])
        self.assertEqual([1,2,3][slice(2)], [1,2])
        self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
        class L(list):
            def __getitem__(self, x):
                return list.__getitem__(self, x)
        self.assertEqual(L([1,2,3])[:2], [1,2])
        self.assertEqual(L([1,2,3])[slice(2)], [1,2])
        self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
        
        a = L([1,2,3])
        a[slice(1, 3)] = [3,2]
        self.assertEqual(a, [1,3,2])
        a[slice(0, 2, 1)] = [3,1]
        self.assertEqual(a, [3,1,2])
        a.__setitem__(slice(1, 3), [2,1])
        self.assertEqual(a, [3,2,1])
        a.__setitem__(slice(0, 2, 1), [2,3])
        self.assertEqual(a, [2,3,1])

    def test_subtype_resurrection(self):
        

        class C(object):
            container = []

            def __del__(self):
                
                C.container.append(self)

        c = C()
        c.attr = 42

        
        
        
        del c

        support.gc_collect()
        self.assertEqual(len(C.container), 1)

        
        
        del C.__del__

    def test_slots_trash(self):
        
        
        class trash(object):
            __slots__ = ['x']
            def __init__(self, x):
                self.x = x
        o = None
        for i in range(50000):
            o = trash(o)
        del o

    def test_slots_multiple_inheritance(self):
        
        class A(object):
            __slots__=()
        class B(object):
            pass
        class C(A,B) :
            __slots__=()
        if support.check_impl_detail():
            self.assertEqual(C.__basicsize__, B.__basicsize__)
        self.assertHasAttr(C, '__dict__')
        self.assertHasAttr(C, '__weakref__')
        C().x = 2

    def test_rmul(self):
        
        
        class C(object):
            def __mul__(self, other):
                return "mul"
            def __rmul__(self, other):
                return "rmul"
        a = C()
        self.assertEqual(a*2, "mul")
        self.assertEqual(a*2.2, "mul")
        self.assertEqual(2*a, "rmul")
        self.assertEqual(2.2*a, "rmul")

    def test_ipow(self):
        
        
        class C(object):
            def __ipow__(self, other):
                pass
        a = C()
        a **= 2

    def test_ipow_returns_not_implemented(self):
        class A:
            def __ipow__(self, other):
                return NotImplemented

        class B(A):
            def __rpow__(self, other):
                return 1

        class C(A):
            def __pow__(self, other):
                return 2
        a = A()
        b = B()
        c = C()

        a **= b
        self.assertEqual(a, 1)

        c **= b
        self.assertEqual(c, 2)

    def test_no_ipow(self):
        class B:
            def __rpow__(self, other):
                return 1

        a = object()
        b = B()
        a **= b
        self.assertEqual(a, 1)

    def test_ipow_exception_text(self):
        x = None
        with self.assertRaises(TypeError) as cm:
            x **= 2
        self.assertIn('unsupported operand type(s) for **=', str(cm.exception))

        with self.assertRaises(TypeError) as cm:
            y = x ** 2
        self.assertIn('unsupported operand type(s) for **', str(cm.exception))

    def test_mutable_bases(self):
        

        
        class C(object):
            pass
        class C2(object):
            def __getattribute__(self, attr):
                if attr == 'a':
                    return 2
                else:
                    return super(C2, self).__getattribute__(attr)
            def meth(self):
                return 1
        class D(C):
            pass
        class E(D):
            pass
        d = D()
        e = E()
        D.__bases__ = (C,)
        D.__bases__ = (C2,)
        self.assertEqual(d.meth(), 1)
        self.assertEqual(e.meth(), 1)
        self.assertEqual(d.a, 2)
        self.assertEqual(e.a, 2)
        self.assertEqual(C2.__subclasses__(), [D])

        try:
            del D.__bases__
        except (TypeError, AttributeError):
            pass
        else:
            self.fail("shouldn't be able to delete .__bases__")

        try:
            D.__bases__ = ()
        except TypeError as msg:
            if str(msg) == "a new-style class can't have only classic bases":
                self.fail("wrong error message for .__bases__ = ()")
        else:
            self.fail("shouldn't be able to set .__bases__ to ()")

        try:
            D.__bases__ = (D,)
        except TypeError:
            pass
        else:
            
            self.fail("shouldn't be able to create inheritance cycles")

        try:
            D.__bases__ = (C, C)
        except TypeError:
            pass
        else:
            self.fail("didn't detect repeated base classes")

        try:
            D.__bases__ = (E,)
        except TypeError:
            pass
        else:
            self.fail("shouldn't be able to create inheritance cycles")

    def test_builtin_bases(self):
        
        
        builtin_types = [tp for tp in builtins.__dict__.values()
                         if isinstance(tp, type)]
        for tp in builtin_types:
            object.__getattribute__(tp, "__bases__")
            if tp is not object:
                if tp is ExceptionGroup:
                    num_bases = 2
                else:
                    num_bases = 1
                self.assertEqual(len(tp.__bases__), num_bases, tp)

        class L(list):
            pass

        class C(object):
            pass

        class D(C):
            pass

        try:
            L.__bases__ = (dict,)
        except TypeError:
            pass
        else:
            self.fail("shouldn't turn list subclass into dict subclass")

        try:
            list.__bases__ = (dict,)
        except TypeError:
            pass
        else:
            self.fail("shouldn't be able to assign to list.__bases__")

        try:
            D.__bases__ = (C, list)
        except TypeError:
            pass
        else:
            self.fail("best_base calculation found wanting")

    def test_unsubclassable_types(self):
        with self.assertRaises(TypeError):
            class X(type(None)):
                pass
        with self.assertRaises(TypeError):
            class X(object, type(None)):
                pass
        with self.assertRaises(TypeError):
            class X(type(None), object):
                pass
        class O(object):
            pass
        with self.assertRaises(TypeError):
            class X(O, type(None)):
                pass
        with self.assertRaises(TypeError):
            class X(type(None), O):
                pass

        class X(object):
            pass
        with self.assertRaises(TypeError):
            X.__bases__ = type(None),
        with self.assertRaises(TypeError):
            X.__bases__ = object, type(None)
        with self.assertRaises(TypeError):
            X.__bases__ = type(None), object
        with self.assertRaises(TypeError):
            X.__bases__ = O, type(None)
        with self.assertRaises(TypeError):
            X.__bases__ = type(None), O

    def test_mutable_bases_with_failing_mro(self):
        
        class WorkOnce(type):
            def __new__(self, name, bases, ns):
                self.flag = 0
                return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
            def mro(self):
                if self.flag > 0:
                    raise RuntimeError("bozo")
                else:
                    self.flag += 1
                    return type.mro(self)

        class WorkAlways(type):
            def mro(self):
                
                
                
                
                return type.mro(self)

        class C(object):
            pass

        class C2(object):
            pass

        class D(C):
            pass

        class E(D):
            pass

        class F(D, metaclass=WorkOnce):
            pass

        class G(D, metaclass=WorkAlways):
            pass

        
        
        

        E_mro_before = E.__mro__
        D_mro_before = D.__mro__

        try:
            D.__bases__ = (C2,)
        except RuntimeError:
            self.assertEqual(E.__mro__, E_mro_before)
            self.assertEqual(D.__mro__, D_mro_before)
        else:
            self.fail("exception not propagated")

    def test_mutable_bases_catch_mro_conflict(self):
        
        class A(object):
            pass

        class B(object):
            pass

        class C(A, B):
            pass

        class D(A, B):
            pass

        class E(C, D):
            pass

        try:
            C.__bases__ = (B, A)
        except TypeError:
            pass
        else:
            self.fail("didn't catch MRO conflict")

    def test_mutable_names(self):
        
        class C(object):
            pass

        
        mod = C.__module__

        C.__name__ = 'D'
        self.assertEqual((C.__module__, C.__name__), (mod, 'D'))

        C.__name__ = 'D.E'
        self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))

    def test_evil_type_name(self):
        
        
        
        class Nasty(str):
            def __del__(self):
                C.__name__ = "other"

        class C:
            pass

        C.__name__ = Nasty("abc")
        C.__name__ = "normal"

    def test_subclass_right_op(self):
        

        
        

        

        class B(int):
            def __floordiv__(self, other):
                return "B.__floordiv__"
            def __rfloordiv__(self, other):
                return "B.__rfloordiv__"

        self.assertEqual(B(1) // 1, "B.__floordiv__")
        self.assertEqual(1 // B(1), "B.__rfloordiv__")

        

        class C(object):
            def __floordiv__(self, other):
                return "C.__floordiv__"
            def __rfloordiv__(self, other):
                return "C.__rfloordiv__"

        self.assertEqual(C() // 1, "C.__floordiv__")
        self.assertEqual(1 // C(), "C.__rfloordiv__")

        

        class D(C):
            def __floordiv__(self, other):
                return "D.__floordiv__"
            def __rfloordiv__(self, other):
                return "D.__rfloordiv__"

        self.assertEqual(D() // C(), "D.__floordiv__")
        self.assertEqual(C() // D(), "D.__rfloordiv__")

        

        class E(C):
            pass

        self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)

        self.assertEqual(E() // 1, "C.__floordiv__")
        self.assertEqual(1 // E(), "C.__rfloordiv__")
        self.assertEqual(E() // C(), "C.__floordiv__")
        self.assertEqual(C() // E(), "C.__floordiv__") 

    @support.impl_detail("testing an internal kind of method object")
    def test_meth_class_get(self):
        
        

        
        arg = [1, 2, 3]
        res = {1: None, 2: None, 3: None}
        self.assertEqual(dict.fromkeys(arg), res)
        self.assertEqual({}.fromkeys(arg), res)

        
        descr = dict.__dict__["fromkeys"]

        
        self.assertEqual(descr.__get__(None, dict)(arg), res)
        self.assertEqual(descr.__get__({})(arg), res)

        
        try:
            descr.__get__(None, None)
        except TypeError:
            pass
        else:
            self.fail("shouldn't have allowed descr.__get__(None, None)")
        try:
            descr.__get__(42)
        except TypeError:
            pass
        else:
            self.fail("shouldn't have allowed descr.__get__(42)")
        try:
            descr.__get__(None, 42)
        except TypeError:
            pass
        else:
            self.fail("shouldn't have allowed descr.__get__(None, 42)")
        try:
            descr.__get__(None, int)
        except TypeError:
            pass
        else:
            self.fail("shouldn't have allowed descr.__get__(None, int)")

    def test_isinst_isclass(self):
        
        class Proxy(object):
            def __init__(self, obj):
                self.__obj = obj
            def __getattribute__(self, name):
                if name.startswith("_Proxy__"):
                    return object.__getattribute__(self, name)
                else:
                    return getattr(self.__obj, name)
        
        class C:
            pass
        a = C()
        pa = Proxy(a)
        self.assertIsInstance(a, C)  
        self.assertIsInstance(pa, C) 
        
        class D(C):
            pass
        a = D()
        pa = Proxy(a)
        self.assertIsInstance(a, C)  
        self.assertIsInstance(pa, C) 
        
        class C(object):
            pass
        a = C()
        pa = Proxy(a)
        self.assertIsInstance(a, C)  
        self.assertIsInstance(pa, C) 
        
        class D(C):
            pass
        a = D()
        pa = Proxy(a)
        self.assertIsInstance(a, C)  
        self.assertIsInstance(pa, C) 

    def test_proxy_super(self):
        
        class Proxy(object):
            def __init__(self, obj):
                self.__obj = obj
            def __getattribute__(self, name):
                if name.startswith("_Proxy__"):
                    return object.__getattribute__(self, name)
                else:
                    return getattr(self.__obj, name)

        class B(object):
            def f(self):
                return "B.f"

        class C(B):
            def f(self):
                return super(C, self).f() + "->C.f"

        obj = C()
        p = Proxy(obj)
        self.assertEqual(C.__dict__["f"](p), "B.f->C.f")

    def test_carloverre(self):
        
        try:
            object.__setattr__(str, "foo", 42)
        except TypeError:
            pass
        else:
            self.fail("Carlo Verre __setattr__ succeeded!")
        try:
            object.__delattr__(str, "lower")
        except TypeError:
            pass
        else:
            self.fail("Carlo Verre __delattr__ succeeded!")

    def test_carloverre_multi_inherit_valid(self):
        class A(type):
            def __setattr__(cls, key, value):
                type.__setattr__(cls, key, value)

        class B:
            pass

        class C(B, A):
            pass

        obj = C('D', (object,), {})
        try:
            obj.test = True
        except TypeError:
            self.fail("setattr through direct base types should be legal")

    def test_carloverre_multi_inherit_invalid(self):
        class A(type):
            def __setattr__(cls, key, value):
                object.__setattr__(cls, key, value)  

        class B:
            pass

        class C(B, A):
            pass

        obj = C('D', (object,), {})
        try:
            obj.test = True
        except TypeError:
            pass
        else:
            self.fail("setattr through indirect base types should be rejected")

    def test_weakref_segfault(self):
        
        
        import weakref

        class Provoker:
            def __init__(self, referrent):
                self.ref = weakref.ref(referrent)

            def __del__(self):
                x = self.ref()

        class Oops(object):
            pass

        o = Oops()
        o.whatever = Provoker(o)
        del o

    @support.requires_resource('cpu')
    def test_wrapper_segfault(self):
        
        f = lambda:None
        for i in range(1000000):
            f = f.__call__
        f = None

    def test_file_fault(self):
        
        class StdoutGuard:
            def __getattr__(self, attr):
                sys.stdout = sys.__stdout__
                raise RuntimeError(f"Premature access to sys.stdout.{attr}")

        with redirect_stdout(StdoutGuard()):
            with self.assertRaises(RuntimeError):
                print("Oops!")

    def test_vicious_descriptor_nonsense(self):
        

        
        
        

        class Evil(object):
            def __hash__(self):
                return hash('attr')
            def __eq__(self, other):
                try:
                    del C.attr
                except AttributeError:
                    
                    pass
                return 0

        class Descr(object):
            def __get__(self, ob, type=None):
                return 1

        class C(object):
            attr = Descr()

        c = C()
        c.__dict__[Evil()] = 0

        self.assertEqual(c.attr, 1)
        
        support.gc_collect()
        self.assertNotHasAttr(c, 'attr')

    def test_init(self):
        
        class Foo(object):
            def __init__(self):
                return 10
        try:
            Foo()
        except TypeError:
            pass
        else:
            self.fail("did not test __init__() for None return")

    def assertNotOrderable(self, a, b):
        with self.assertRaises(TypeError):
            a < b
        with self.assertRaises(TypeError):
            a > b
        with self.assertRaises(TypeError):
            a <= b
        with self.assertRaises(TypeError):
            a >= b

    def test_method_wrapper(self):
        
        
        l = []
        self.assertTrue(l.__add__ == l.__add__)
        self.assertFalse(l.__add__ != l.__add__)
        self.assertFalse(l.__add__ == [].__add__)
        self.assertTrue(l.__add__ != [].__add__)
        self.assertFalse(l.__add__ == l.__mul__)
        self.assertTrue(l.__add__ != l.__mul__)
        self.assertNotOrderable(l.__add__, l.__add__)
        self.assertEqual(l.__add__.__name__, '__add__')
        self.assertIs(l.__add__.__self__, l)
        self.assertIs(l.__add__.__objclass__, list)
        self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
        
        hash(l.__add__)

    def test_builtin_function_or_method(self):
        
        
        
        l = []
        self.assertTrue(l.append == l.append)
        self.assertFalse(l.append != l.append)
        self.assertFalse(l.append == [].append)
        self.assertTrue(l.append != [].append)
        self.assertFalse(l.append == l.pop)
        self.assertTrue(l.append != l.pop)
        self.assertNotOrderable(l.append, l.append)
        self.assertEqual(l.append.__name__, 'append')
        self.assertIs(l.append.__self__, l)
        
        self.assertEqual(l.append.__doc__, list.append.__doc__)
        
        hash(l.append)

    def test_special_unbound_method_types(self):
        
        self.assertTrue(list.__add__ == list.__add__)
        self.assertFalse(list.__add__ != list.__add__)
        self.assertFalse(list.__add__ == list.__mul__)
        self.assertTrue(list.__add__ != list.__mul__)
        self.assertNotOrderable(list.__add__, list.__add__)
        self.assertEqual(list.__add__.__name__, '__add__')
        self.assertIs(list.__add__.__objclass__, list)

        
        self.assertTrue(list.append == list.append)
        self.assertFalse(list.append != list.append)
        self.assertFalse(list.append == list.pop)
        self.assertTrue(list.append != list.pop)
        self.assertNotOrderable(list.append, list.append)
        self.assertEqual(list.append.__name__, 'append')
        self.assertIs(list.append.__objclass__, list)

    def test_not_implemented(self):
        
        
        import operator

        def specialmethod(self, other):
            return NotImplemented

        def check(expr, x, y):
            try:
                exec(expr, {'x': x, 'y': y, 'operator': operator})
            except TypeError:
                pass
            else:
                self.fail("no TypeError from %r" % (expr,))

        N1 = sys.maxsize + 1    
                                
        N2 = sys.maxsize         
                                
        for name, expr, iexpr in [
                ('__add__',      'x + y',                   'x += y'),
                ('__sub__',      'x - y',                   'x -= y'),
                ('__mul__',      'x * y',                   'x *= y'),
                ('__matmul__',   'x @ y',                   'x @= y'),
                ('__truediv__',  'x / y',                   'x /= y'),
                ('__floordiv__', 'x // y',                  'x //= y'),
                ('__mod__',      'x % y',                   'x %= y'),
                ('__divmod__',   'divmod(x, y)',            None),
                ('__pow__',      'x ** y',                  'x **= y'),
                ('__lshift__',   'x << y',                  'x <<= y'),
                ('__rshift__',   'x >> y',                  'x >>= y'),
                ('__and__',      'x & y',                   'x &= y'),
                ('__or__',       'x | y',                   'x |= y'),
                ('__xor__',      'x ^ y',                   'x ^= y')]:
            rname = '__r' + name[2:]
            A = type('A', (), {name: specialmethod})
            a = A()
            check(expr, a, a)
            check(expr, a, N1)
            check(expr, a, N2)
            if iexpr:
                check(iexpr, a, a)
                check(iexpr, a, N1)
                check(iexpr, a, N2)
                iname = '__i' + name[2:]
                C = type('C', (), {iname: specialmethod})
                c = C()
                check(iexpr, c, a)
                check(iexpr, c, N1)
                check(iexpr, c, N2)

    def test_assign_slice(self):
        
        
        

        class C(object):
            def __setitem__(self, idx, value):
                self.value = value

        c = C()
        c[1:2] = 3
        self.assertEqual(c.value, 3)

    def test_set_and_no_get(self):
        
        
        class Descr(object):

            def __init__(self, name):
                self.name = name

            def __set__(self, obj, value):
                obj.__dict__[self.name] = value
        descr = Descr("a")

        class X(object):
            a = descr

        x = X()
        self.assertIs(x.a, descr)
        x.a = 42
        self.assertEqual(x.a, 42)

        
        class Meta(type):
            pass
        class X(metaclass=Meta):
            pass
        X.a = 42
        Meta.a = Descr("a")
        self.assertEqual(X.a, 42)

    def test_getattr_hooks(self):
        

        class Descriptor(object):
            counter = 0
            def __get__(self, obj, objtype=None):
                def getter(name):
                    self.counter += 1
                    raise AttributeError(name)
                return getter

        descr = Descriptor()
        class A(object):
            __getattribute__ = descr
        class B(object):
            __getattr__ = descr
        class C(object):
            __getattribute__ = descr
            __getattr__ = descr

        self.assertRaises(AttributeError, getattr, A(), "attr")
        self.assertEqual(descr.counter, 1)
        self.assertRaises(AttributeError, getattr, B(), "attr")
        self.assertEqual(descr.counter, 2)
        self.assertRaises(AttributeError, getattr, C(), "attr")
        self.assertEqual(descr.counter, 4)

        class EvilGetattribute(object):
            
            def __getattr__(self, name):
                raise AttributeError(name)
            def __getattribute__(self, name):
                del EvilGetattribute.__getattr__
                for i in range(5):
                    gc.collect()
                raise AttributeError(name)

        self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")

    def test_type___getattribute__(self):
        self.assertRaises(TypeError, type.__getattribute__, list, type)

    def test_abstractmethods(self):
        
        self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
        class meta(type):
            pass
        self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
        class X(object):
            pass
        with self.assertRaises(AttributeError):
            del X.__abstractmethods__

    def test_proxy_call(self):
        class FakeStr:
            __class__ = str

        fake_str = FakeStr()
        
        self.assertIsInstance(fake_str, str)

        
        with self.assertRaises(TypeError):
            str.split(fake_str)

        
        with self.assertRaises(TypeError):
            str.__add__(fake_str, "abc")

    def test_specialized_method_calls_check_types(self):
        
        class Thing:
            pass
        thing = Thing()
        for i in range(20):
            with self.assertRaises(TypeError):
                
                list.sort(thing)
        for i in range(20):
            with self.assertRaises(TypeError):
                
                str.split(thing)
        for i in range(20):
            with self.assertRaises(TypeError):
                
                str.upper(thing)
        for i in range(20):
            with self.assertRaises(TypeError):
                
                str.strip(thing)
        from collections import deque
        for i in range(20):
            with self.assertRaises(TypeError):
                
                deque.append(thing, thing)

    def test_repr_as_str(self):
        
        
        class Foo:
            pass
        Foo.__repr__ = Foo.__str__
        foo = Foo()
        self.assertRaises(RecursionError, str, foo)
        self.assertRaises(RecursionError, repr, foo)

    def test_mixing_slot_wrappers(self):
        class X(dict):
            __setattr__ = dict.__setitem__
            __neg__ = dict.copy
        x = X()
        x.y = 42
        self.assertEqual(x["y"], 42)
        self.assertEqual(x, -x)

    def test_wrong_class_slot_wrapper(self):
        
        
        class A(int):
            __eq__ = str.__eq__
            __add__ = str.__add__
        a = A()
        with self.assertRaises(TypeError):
            a == a
        with self.assertRaises(TypeError):
            a + a

    def test_slot_shadows_class_variable(self):
        with self.assertRaises(ValueError) as cm:
            class X:
                __slots__ = ["foo"]
                foo = None
        m = str(cm.exception)
        self.assertEqual("'foo' in __slots__ conflicts with class variable", m)

    def test_set_doc(self):
        class X:
            "elephant"
        X.__doc__ = "banana"
        self.assertEqual(X.__doc__, "banana")

        with self.assertRaises(TypeError) as cm:
            type(list).__dict__["__doc__"].__set__(list, "blah")
        self.assertIn("cannot set '__doc__' attribute of immutable type 'list'", str(cm.exception))

        with self.assertRaises(TypeError) as cm:
            type(X).__dict__["__doc__"].__delete__(X)
        self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception))
        self.assertEqual(X.__doc__, "banana")

    def test_qualname(self):
        descriptors = [str.lower, complex.real, float.real, int.__add__]
        types = ['method', 'member', 'getset', 'wrapper']

        
        for d, n in zip(descriptors, types):
            self.assertEqual(type(d).__name__, n + '_descriptor')

        for d in descriptors:
            qualname = d.__objclass__.__qualname__ + '.' + d.__name__
            self.assertEqual(d.__qualname__, qualname)

        self.assertEqual(str.lower.__qualname__, 'str.lower')
        self.assertEqual(complex.real.__qualname__, 'complex.real')
        self.assertEqual(float.real.__qualname__, 'float.real')
        self.assertEqual(int.__add__.__qualname__, 'int.__add__')

        class X:
            pass
        with self.assertRaises(TypeError):
            del X.__qualname__

        self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
                          str, 'Oink')

        global Y
        class Y:
            class Inside:
                pass
        self.assertEqual(Y.__qualname__, 'Y')
        self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')

    def test_qualname_dict(self):
        ns = {'__qualname__': 'some.name'}
        tp = type('Foo', (), ns)
        self.assertEqual(tp.__qualname__, 'some.name')
        self.assertNotIn('__qualname__', tp.__dict__)
        self.assertEqual(ns, {'__qualname__': 'some.name'})

        ns = {'__qualname__': 1}
        self.assertRaises(TypeError, type, 'Foo', (), ns)

    def test_cycle_through_dict(self):
        
        class X(dict):
            def __init__(self):
                dict.__init__(self)
                self.__dict__ = self
        x = X()
        x.attr = 42
        wr = weakref.ref(x)
        del x
        support.gc_collect()
        self.assertIsNone(wr())
        for o in gc.get_objects():
            self.assertIsNot(type(o), X)

    def test_object_new_and_init_with_parameters(self):
        
        class OverrideNeither:
            pass
        self.assertRaises(TypeError, OverrideNeither, 1)
        self.assertRaises(TypeError, OverrideNeither, kw=1)
        class OverrideNew:
            def __new__(cls, foo, kw=0, *args, **kwds):
                return object.__new__(cls, *args, **kwds)
        class OverrideInit:
            def __init__(self, foo, kw=0, *args, **kwargs):
                return object.__init__(self, *args, **kwargs)
        class OverrideBoth(OverrideNew, OverrideInit):
            pass
        for case in OverrideNew, OverrideInit, OverrideBoth:
            case(1)
            case(1, kw=2)
            self.assertRaises(TypeError, case, 1, 2, 3)
            self.assertRaises(TypeError, case, 1, 2, foo=3)

    def test_subclassing_does_not_duplicate_dict_descriptors(self):
        class Base:
            pass
        class Sub(Base):
            pass
        self.assertIn("__dict__", Base.__dict__)
        self.assertNotIn("__dict__", Sub.__dict__)

    def test_bound_method_repr(self):
        class Foo:
            def method(self):
                pass
        self.assertRegex(repr(Foo().method),
            r"<bound method .*Foo\.method of <.*Foo object at .*>>")


        class Base:
            def method(self):
                pass
        class Derived1(Base):
            pass
        class Derived2(Base):
            def method(self):
                pass
        base = Base()
        derived1 = Derived1()
        derived2 = Derived2()
        super_d2 = super(Derived2, derived2)
        self.assertRegex(repr(base.method),
            r"<bound method .*Base\.method of <.*Base object at .*>>")
        self.assertRegex(repr(derived1.method),
            r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
        self.assertRegex(repr(derived2.method),
            r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
        self.assertRegex(repr(super_d2.method),
            r"<bound method .*Base\.method of <.*Derived2 object at .*>>")

        class Foo:
            @classmethod
            def method(cls):
                pass
        foo = Foo()
        self.assertRegex(repr(foo.method), 
            r"<bound method .*Foo\.method of <class '.*Foo'>>")
        self.assertRegex(repr(Foo.method), 
            r"<bound method .*Foo\.method of <class '.*Foo'>>")


        class MyCallable:
            def __call__(self, arg):
                pass
        func = MyCallable() 
        instance = object()
        method = types.MethodType(func, instance)
        self.assertRegex(repr(method),
            r"<bound method \? of <object object at .*>>")
        func.__name__ = "name"
        self.assertRegex(repr(method),
            r"<bound method name of <object object at .*>>")
        func.__qualname__ = "qualname"
        self.assertRegex(repr(method),
            r"<bound method qualname of <object object at .*>>")

    @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
    def test_bpo25750(self):
        
        
        
        class Descr:
            __get__ = _testcapi.bad_get

        class X:
            descr = Descr()
            def __new__(cls):
                cls.descr = None
                
                cls.lst = [2**i for i in range(10000)]
        X.descr

    def test_remove_subclass(self):
        
        
        
        
        class Parent:
            pass
        self.assertEqual(Parent.__subclasses__(), [])

        class Child(Parent):
            pass
        self.assertEqual(Parent.__subclasses__(), [Child])

        del Child
        gc.collect()
        self.assertEqual(Parent.__subclasses__(), [])

    def test_attr_raise_through_property(self):
        
        class A:
            def __getattr__(self, name):
                raise ValueError("FOO")

            @property
            def foo(self):
                return self.__getattr__("asdf")

        with self.assertRaisesRegex(ValueError, "FOO"):
            A().foo

        
        class B:
            @property
            def __getattr__(self, name):
                raise ValueError("FOO")

            @property
            def foo(self):
                raise NotImplementedError("BAR")

        with self.assertRaisesRegex(NotImplementedError, "BAR"):
            B().foo


class DictProxyTests(unittest.TestCase):
    def setUp(self):
        class C(object):
            def meth(self):
                pass
        self.C = C

    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                        'trace function introduces __local__')
    def test_iter_keys(self):
        
        it = self.C.__dict__.keys()
        self.assertNotIsInstance(it, list)
        keys = list(it)
        keys.sort()
        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
                                '__weakref__', 'meth'])

    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                        'trace function introduces __local__')
    def test_iter_values(self):
        
        it = self.C.__dict__.values()
        self.assertNotIsInstance(it, list)
        values = list(it)
        self.assertEqual(len(values), 5)

    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
                        'trace function introduces __local__')
    def test_iter_items(self):
        
        it = self.C.__dict__.items()
        self.assertNotIsInstance(it, list)
        keys = [item[0] for item in it]
        keys.sort()
        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
                                '__weakref__', 'meth'])

    def test_dict_type_with_metaclass(self):
        
        class B(object):
            pass
        class M(type):
            pass
        class C(metaclass=M):
            
            pass
        self.assertEqual(type(C.__dict__), type(B.__dict__))

    def test_repr(self):
        
        
        
        r = repr(self.C.__dict__)
        self.assertTrue(r.startswith('mappingproxy('), r)
        self.assertTrue(r.endswith(')'), r)
        for k, v in self.C.__dict__.items():
            self.assertIn('{!r}: {!r}'.format(k, v), r)


class AAAPTypesLongInitTest(unittest.TestCase):
    
    
    
    
    def test_pytype_long_ready(self):
        

        
        
        
        
        class UserLong(object):
            def __pow__(self, *args):
                pass
        try:
            pow(0, UserLong(), 0)
        except:
            pass

        
        
        type.mro(tuple)


class MiscTests(unittest.TestCase):
    def test_type_lookup_mro_reference(self):
        
        
        
        class MyKey(object):
            def __hash__(self):
                return hash('mykey')

            def __eq__(self, other):
                X.__bases__ = (Base2,)

        class Base(object):
            mykey = 'from Base'
            mykey2 = 'from Base'

        class Base2(object):
            mykey = 'from Base2'
            mykey2 = 'from Base2'

        X = type('X', (Base,), {MyKey(): 5})
        
        self.assertEqual(X.mykey, 'from Base')
        
        self.assertEqual(X.mykey2, 'from Base2')


class PicklingTests(unittest.TestCase):

    def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
                      listitems=None, dictitems=None):
        if proto >= 2:
            reduce_value = obj.__reduce_ex__(proto)
            if kwargs:
                self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
                self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
            else:
                self.assertEqual(reduce_value[0], copyreg.__newobj__)
                self.assertEqual(reduce_value[1], (type(obj),) + args)
            self.assertEqual(reduce_value[2], state)
            if listitems is not None:
                self.assertListEqual(list(reduce_value[3]), listitems)
            else:
                self.assertIsNone(reduce_value[3])
            if dictitems is not None:
                self.assertDictEqual(dict(reduce_value[4]), dictitems)
            else:
                self.assertIsNone(reduce_value[4])
        else:
            base_type = type(obj).__base__
            reduce_value = (copyreg._reconstructor,
                            (type(obj),
                             base_type,
                             None if base_type is object else base_type(obj)))
            if state is not None:
                reduce_value += (state,)
            self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
            self.assertEqual(obj.__reduce__(), reduce_value)

    def test_reduce(self):
        protocols = range(pickle.HIGHEST_PROTOCOL + 1)
        args = (-101, "spam")
        kwargs = {'bacon': -201, 'fish': -301}
        state = {'cheese': -401}

        class C1:
            def __getnewargs__(self):
                return args
        obj = C1()
        for proto in protocols:
            self._check_reduce(proto, obj, args)

        for name, value in state.items():
            setattr(obj, name, value)
        for proto in protocols:
            self._check_reduce(proto, obj, args, state=state)

        class C2:
            def __getnewargs__(self):
                return "bad args"
        obj = C2()
        for proto in protocols:
            if proto >= 2:
                with self.assertRaises(TypeError):
                    obj.__reduce_ex__(proto)

        class C3:
            def __getnewargs_ex__(self):
                return (args, kwargs)
        obj = C3()
        for proto in protocols:
            if proto >= 2:
                self._check_reduce(proto, obj, args, kwargs)

        class C4:
            def __getnewargs_ex__(self):
                return (args, "bad dict")
        class C5:
            def __getnewargs_ex__(self):
                return ("bad tuple", kwargs)
        class C6:
            def __getnewargs_ex__(self):
                return ()
        class C7:
            def __getnewargs_ex__(self):
                return "bad args"
        for proto in protocols:
            for cls in C4, C5, C6, C7:
                obj = cls()
                if proto >= 2:
                    with self.assertRaises((TypeError, ValueError)):
                        obj.__reduce_ex__(proto)

        class C9:
            def __getnewargs_ex__(self):
                return (args, {})
        obj = C9()
        for proto in protocols:
            self._check_reduce(proto, obj, args)

        class C10:
            def __getnewargs_ex__(self):
                raise IndexError
        obj = C10()
        for proto in protocols:
            if proto >= 2:
                with self.assertRaises(IndexError):
                    obj.__reduce_ex__(proto)

        class C11:
            def __getstate__(self):
                return state
        obj = C11()
        for proto in protocols:
            self._check_reduce(proto, obj, state=state)

        class C12:
            def __getstate__(self):
                return "not dict"
        obj = C12()
        for proto in protocols:
            self._check_reduce(proto, obj, state="not dict")

        class C13:
            def __getstate__(self):
                raise IndexError
        obj = C13()
        for proto in protocols:
            with self.assertRaises(IndexError):
                obj.__reduce_ex__(proto)
            if proto < 2:
                with self.assertRaises(IndexError):
                    obj.__reduce__()

        class C14:
            __slots__ = tuple(state)
            def __init__(self):
                for name, value in state.items():
                    setattr(self, name, value)

        obj = C14()
        for proto in protocols:
            if proto >= 2:
                self._check_reduce(proto, obj, state=(None, state))
            else:
                with self.assertRaises(TypeError):
                    obj.__reduce_ex__(proto)
                with self.assertRaises(TypeError):
                    obj.__reduce__()

        class C15(dict):
            pass
        obj = C15({"quebec": -601})
        for proto in protocols:
            self._check_reduce(proto, obj, dictitems=dict(obj))

        class C16(list):
            pass
        obj = C16(["yukon"])
        for proto in protocols:
            self._check_reduce(proto, obj, listitems=list(obj))

    def test_special_method_lookup(self):
        protocols = range(pickle.HIGHEST_PROTOCOL + 1)
        class Picky:
            def __getstate__(self):
                return {}

            def __getattr__(self, attr):
                if attr in ("__getnewargs__", "__getnewargs_ex__"):
                    raise AssertionError(attr)
                return None
        for protocol in protocols:
            state = {} if protocol >= 2 else None
            self._check_reduce(protocol, Picky(), state=state)

    def _assert_is_copy(self, obj, objcopy, msg=None):
        
        if msg is None:
            msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
        if type(obj).__repr__ is object.__repr__:
            
            
            
            
            raise ValueError("object passed to _assert_is_copy must " +
                             "override the __repr__ method.")
        self.assertIsNot(obj, objcopy, msg=msg)
        self.assertIs(type(obj), type(objcopy), msg=msg)
        if hasattr(obj, '__dict__'):
            self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
            self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
        if hasattr(obj, '__slots__'):
            self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
            for slot in obj.__slots__:
                self.assertEqual(
                    hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
                self.assertEqual(getattr(obj, slot, None),
                                 getattr(objcopy, slot, None), msg=msg)
        self.assertEqual(repr(obj), repr(objcopy), msg=msg)

    @staticmethod
    def _generate_pickle_copiers():
        
        class PickleCopier:
            "This class copies object using pickle."
            def __init__(self, proto, dumps, loads):
                self.proto = proto
                self.dumps = dumps
                self.loads = loads
            def copy(self, obj):
                return self.loads(self.dumps(obj, self.proto))
            def __repr__(self):
                
                
                
                return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
                        .format(self.proto,
                                self.dumps.__module__, self.dumps.__qualname__,
                                self.loads.__module__, self.loads.__qualname__))
        return (PickleCopier(*args) for args in
                   itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
                                     {pickle.dumps, pickle._dumps},
                                     {pickle.loads, pickle._loads}))

    def test_pickle_slots(self):
        

        
        
        global C
        class C:
            __slots__ = ['a']
        with self.assertRaises(TypeError):
            pickle.dumps(C(), 0)

        global D
        class D(C):
            pass
        with self.assertRaises(TypeError):
            pickle.dumps(D(), 0)

        class C:
            "A class with __getstate__ and __setstate__ implemented."
            __slots__ = ['a']
            def __getstate__(self):
                state = getattr(self, '__dict__', {}).copy()
                for cls in type(self).__mro__:
                    for slot in cls.__dict__.get('__slots__', ()):
                        try:
                            state[slot] = getattr(self, slot)
                        except AttributeError:
                            pass
                return state
            def __setstate__(self, state):
                for k, v in state.items():
                    setattr(self, k, v)
            def __repr__(self):
                return "%s()<%r>" % (type(self).__name__, self.__getstate__())

        class D(C):
            "A subclass of a class with slots."
            pass

        global E
        class E(C):
            "A subclass with an extra slot."
            __slots__ = ['b']

        
        for pickle_copier in self._generate_pickle_copiers():
            with self.subTest(pickle_copier=pickle_copier):
                x = C()
                y = pickle_copier.copy(x)
                self._assert_is_copy(x, y)

                x.a = 42
                y = pickle_copier.copy(x)
                self._assert_is_copy(x, y)

                x = D()
                x.a = 42
                x.b = 100
                y = pickle_copier.copy(x)
                self._assert_is_copy(x, y)

                x = E()
                x.a = 42
                x.b = "foo"
                y = pickle_copier.copy(x)
                self._assert_is_copy(x, y)

    def test_reduce_copying(self):
        
        global C1
        class C1:
            "The state of this class is copyable via its instance dict."
            ARGS = (1, 2)
            NEED_DICT_COPYING = True
            def __init__(self, a, b):
                super().__init__()
                self.a = a
                self.b = b
            def __repr__(self):
                return "C1(%r, %r)" % (self.a, self.b)

        global C2
        class C2(list):
            "A list subclass copyable via __getnewargs__."
            ARGS = (1, 2)
            NEED_DICT_COPYING = False
            def __new__(cls, a, b):
                self = super().__new__(cls)
                self.a = a
                self.b = b
                return self
            def __init__(self, *args):
                super().__init__()
                
                
                self.append("cheese")
            @classmethod
            def __getnewargs__(cls):
                return cls.ARGS
            def __repr__(self):
                return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))

        global C3
        class C3(list):
            "A list subclass copyable via __getstate__."
            ARGS = (1, 2)
            NEED_DICT_COPYING = False
            def __init__(self, a, b):
                self.a = a
                self.b = b
                
                
                self.append("cheese")
            @classmethod
            def __getstate__(cls):
                return cls.ARGS
            def __setstate__(self, state):
                a, b = state
                self.a = a
                self.b = b
            def __repr__(self):
                return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))

        global C4
        class C4(int):
            "An int subclass copyable via __getnewargs__."
            ARGS = ("hello", "world", 1)
            NEED_DICT_COPYING = False
            def __new__(cls, a, b, value):
                self = super().__new__(cls, value)
                self.a = a
                self.b = b
                return self
            @classmethod
            def __getnewargs__(cls):
                return cls.ARGS
            def __repr__(self):
                return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))

        global C5
        class C5(int):
            "An int subclass copyable via __getnewargs_ex__."
            ARGS = (1, 2)
            KWARGS = {'value': 3}
            NEED_DICT_COPYING = False
            def __new__(cls, a, b, *, value=0):
                self = super().__new__(cls, value)
                self.a = a
                self.b = b
                return self
            @classmethod
            def __getnewargs_ex__(cls):
                return (cls.ARGS, cls.KWARGS)
            def __repr__(self):
                return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))

        test_classes = (C1, C2, C3, C4, C5)
        
        pickle_copiers = self._generate_pickle_copiers()
        for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
            with self.subTest(cls=cls, pickle_copier=pickle_copier):
                kwargs = getattr(cls, 'KWARGS', {})
                obj = cls(*cls.ARGS, **kwargs)
                proto = pickle_copier.proto
                objcopy = pickle_copier.copy(obj)
                self._assert_is_copy(obj, objcopy)
                
                
                
                
                if proto >= 2 and not cls.NEED_DICT_COPYING:
                    objcopy.__dict__.clear()
                    objcopy2 = pickle_copier.copy(objcopy)
                    self._assert_is_copy(obj, objcopy2)

        
        for cls in test_classes:
            with self.subTest(cls=cls):
                kwargs = getattr(cls, 'KWARGS', {})
                obj = cls(*cls.ARGS, **kwargs)
                objcopy = deepcopy(obj)
                self._assert_is_copy(obj, objcopy)
                
                
                
                
                if not cls.NEED_DICT_COPYING:
                    objcopy.__dict__.clear()
                    objcopy2 = deepcopy(objcopy)
                    self._assert_is_copy(obj, objcopy2)

    def test_issue24097(self):
        
        class S(str):  
            pass
        class A:
            __slotnames__ = [S('spam')]
            def __getattr__(self, attr):
                if attr == 'spam':
                    A.__slotnames__[:] = [S('spam')]
                    return 42
                else:
                    raise AttributeError

        import copyreg
        expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
        self.assertEqual(A().__reduce_ex__(2), expected)  

    def test_object_reduce(self):
        
        
        object().__reduce__()
        with self.assertRaises(TypeError):
            object().__reduce__(0)
        
        object().__reduce_ex__(0)
        with self.assertRaises(TypeError):
            object().__reduce_ex__()
        with self.assertRaises(TypeError):
            object().__reduce_ex__(None)


class SharedKeyTests(unittest.TestCase):

    @support.cpython_only
    def test_subclasses(self):
        
        class A:
            pass
        class B(A):
            pass

        
        [(A(), B()) for _ in range(30)]

        a, b = A(), B()
        self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
        self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
        
        
        a.x, a.y, a.z, a.w, a.v, a.u = range(6)
        self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
        a2 = A()
        self.assertGreater(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
        self.assertLess(sys.getsizeof(vars(a2)), sys.getsizeof({"a":1}))
        self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))


class DebugHelperMeta(type):
    
    def __new__(mcls, name, bases, attrs):
        if attrs.get('__doc__') is None:
            attrs['__doc__'] = name  
        return type.__new__(mcls, name, bases, attrs)
    def __repr__(cls):
        return repr(cls.__name__)


class MroTest(unittest.TestCase):
    

    def setUp(self):
        self.step = 0
        self.ready = False

    def step_until(self, limit):
        ret = (self.step < limit)
        if ret:
            self.step += 1
        return ret

    def test_incomplete_set_bases_on_self(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if self.step_until(1):
                    assert cls.__mro__ is None
                    cls.__bases__ += ()

                return type.mro(cls)

        class A(metaclass=M):
            pass

    def test_reent_set_bases_on_base(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if cls.__mro__ is not None and cls.__name__ == 'B':
                    
                    if self.step_until(10):
                        A.__bases__ += ()

                return type.mro(cls)

        class A(metaclass=M):
            pass
        class B(A):
            pass
        B.__bases__ += ()

    def test_reent_set_bases_on_direct_base(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                base = cls.__bases__[0]
                if base is not object:
                    if self.step_until(5):
                        base.__bases__ += ()

                return type.mro(cls)

        class A(metaclass=M):
            pass
        class B(A):
            pass
        class C(B):
            pass

    def test_reent_set_bases_tp_base_cycle(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if self.ready:
                    if cls.__name__ == 'B1':
                        B2.__bases__ = (B1,)
                    if cls.__name__ == 'B2':
                        B1.__bases__ = (B2,)
                return type.mro(cls)

        class A(metaclass=M):
            pass
        class B1(A):
            pass
        class B2(A):
            pass

        self.ready = True
        with self.assertRaises(TypeError):
            B1.__bases__ += ()

    def test_tp_subclasses_cycle_in_update_slots(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if self.ready and cls.__name__ == 'C':
                    self.ready = False
                    C.__bases__ = (B2,)
                return type.mro(cls)

        class A(metaclass=M):
            pass
        class B1(A):
            pass
        class B2(A):
            pass
        class C(A):
            pass

        self.ready = True
        C.__bases__ = (B1,)
        B1.__bases__ = (C,)

        self.assertEqual(C.__bases__, (B2,))
        self.assertEqual(B2.__subclasses__(), [C])
        self.assertEqual(B1.__subclasses__(), [])

        self.assertEqual(B1.__bases__, (C,))
        self.assertEqual(C.__subclasses__(), [B1])

    def test_tp_subclasses_cycle_error_return_path(self):
        
        class E(Exception):
            pass
        class M(DebugHelperMeta):
            def mro(cls):
                if self.ready and cls.__name__ == 'C':
                    if C.__bases__ == (B2,):
                        self.ready = False
                    else:
                        C.__bases__ = (B2,)
                        raise E
                return type.mro(cls)

        class A(metaclass=M):
            pass
        class B1(A):
            pass
        class B2(A):
            pass
        class C(A):
            pass

        self.ready = True
        with self.assertRaises(E):
            C.__bases__ = (B1,)
        B1.__bases__ = (C,)

        self.assertEqual(C.__bases__, (B2,))
        self.assertEqual(C.__mro__, tuple(type.mro(C)))

    def test_incomplete_extend(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if cls.__mro__ is None and cls.__name__ != 'X':
                    with self.assertRaises(TypeError):
                        class X(cls):
                            pass

                return type.mro(cls)

        class A(metaclass=M):
            pass

    def test_incomplete_super(self):
        
        class M(DebugHelperMeta):
            def mro(cls):
                if cls.__mro__ is None:
                    with self.assertRaises(AttributeError):
                        super(cls, cls).xxx

                return type.mro(cls)

        class A(metaclass=M):
            pass

    def test_disappearing_custom_mro(self):
        
        class B:
            pass

        class M(DebugHelperMeta):
            def mro(cls):
                del M.mro
                return (B,)

        with self.assertRaises(TypeError):
            class A(metaclass=M):
                pass


if __name__ == "__main__":
    unittest.main()