Issue
How do I correctly define __repr__
for my map class?
class map(object):
"""Find data folders that could be imported and return as list"""
def __init__(self,height=400,zoom=0):
"""Initialize the map"""
if zoom == 0:
z = get_map_zoom()
else:
z = zoom
self.map = Map(center=get_map_center(), zoom=z)
self.map.layout.height = f'{height}px'
def __repr__(self):
return self.map
def add_layer(self,tableName:str,style_name='default',geomColumn:str = 'geom'):
"""Get GeoJSON data from database and add as layer to map"""
data = db.execute(f'SELECT ST_AsGeojson(ST_Transform({geomColumn},4326)) from {tableName} order by random() limit 5000;')
style = get_style(style_name)
geo_json = GeoJSON(style=style,data={'type': "FeatureCollection", 'features': [json.loads(row[0]) for row in data]})
self.map.add_layer(geo_json)
From Jupyter I am generating the map like this:
from modules import map
m = map.map()
m.add_layer('geo.service_area','service_area')
m.add_layer('rawgeo.ways',geomColumn='the_geom')
display(m)
But TypeError: __repr__ returned non-string (type Map)
error occurs on display(m)
.
I am able to make it work if I use display(m.map)
instead.
Solution
The __repr__
method must return a string. From the docs (some emphasis mine):
object.__repr__(self)
Called by the repr() built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines
__repr__()
but not__str__()
, then__repr__()
is also used when an “informal” string representation of instances of that class is required.
Edit: As @khelwood suggests you can return repr(self.map)
in the __repr__
method.
Answered By - Alex
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.