ResMar ResMar - 12 days ago 5
Python Question

Seemingly immutable dict in object instance

If I run the following

cartopy
code:

import cartopy.crs as ccrs
globe = ccrs.LambertCylindrical()
print(globe.proj4_params)
globe.proj4_params['a'] = 5
print(globe.proj4_params)


I get:

{'proj': 'cea', 'lon_0': 0.0, 'a': 57.29577951308232, 'ellps': 'WGS84'}
{'proj': 'cea', 'lon_0': 0.0, 'a': 57.29577951308232, 'ellps': 'WGS84'}


Impying that the
proj4_params
property is immutable.

But it's just a bog standard
dict
:

print(type(globe.proj4_params))

<class 'dict'>


Which, since it's implemented in C, can't be overwritten to have this kind of behavior (at least not safely).

Ok, but the code for this class is dead simple, so there's something wrong with my understanding. Can someone explain to me why I am getting this behavior?

Edit:

The following:

projection.proj4_params = dict(projection.proj4_params)


Results in:

*** AttributeError: attribute 'proj4_params' of 'cartopy._crs.CRS' objects is not writable

Answer

You could ensure your params are a dictionary by converting it to one first.

params = dict(globe.proj4_params)

Then if you print

print type(params)

<type 'dict'>

Notice the <type 'dict'> instead of the <class 'dict'> in your question. The dict you're using may be a custom class that's immutable but uses the same dict name.