something wrong with isinstance

maksym.kaban at gmail.com maksym.kaban at gmail.com
Thu Feb 12 12:53:04 EST 2009


Hi there.
now i'm a complete newbie for python, and maybe my problem is stupid
but i cannot solve it myself

i have an object of class GeoMap which contains lists with objects of
GeoMapCell (i will not explain what they should do, hope its not
important). Then i want to serialize these objects to json notation.
So i imported json module and as shown in docs for it extended
JSONEncoder class.  Look at the code below

##main module
from worldmap import GeoMap, GeoMapCell

import testdata
import json

class GeoMapEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, GeoMap):
            return None
        return json.JSONEncoder.default(self, obj)

def main():
    print(json.dumps(2 + 5j, cls=ComplexEncoder))

    geomap = testdata.createTestMap()
    print(json.dumps(geomap, cls=GeoMapEncoder))
    pass

if __name__ == '__main__':
    main()

===========

##worldmap module
class GeoMap:
    cells = []
    activerow = 0
    activecol = 0

    def addCell(self, acell):
        if len(self.cells) == 0:
          self.cells.append([])
          self.activerow = 0
        acell.col = self.activerow
        acell.row = self.activecol
        self.cells[self.activerow].append(acell)
        self.activecol += 1

    def addRow(self):
        self.cells.append([])
        self.activerow += 1;
        self.activecol = 0;

class GeoMapCell:
    neighbours = (None, None, None, None, None, None, )
    col = 0
    row = 0

The problem is in here.

class GeoMapEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, GeoMap):  ## <=======   isinstance doesnot
work as i expected
            return None
        return json.JSONEncoder.default(self, obj)

 Though obj is object of GeoMap class, isinstance returns False. Where
was i mistaken. If i shouldn't use isinstance, then what function
would check class of object?

Oh, maybe its important. I'm working on WinXP SP3, Python 3.0, IDE -
PyScript



More information about the Python-list mailing list