[Qgis-developer] (First?) API break

Giuseppe Sucameli brush.tyler at gmail.com
Tue Dec 13 15:27:45 EST 2011


Hi all,

On Wed, Dec 7, 2011 at 5:22 PM, Marco Hugentobler
<marco.hugentobler at sourcepole.ch> wrote:
> I broke the 1.x API.

finally good news, or maybe not... :)


On Tue, Dec 13, 2011 at 1:34 PM, Pirmin Kalberer <pi_ml at sourcepole.com> wrote:
> If a method is called only once, one could also write
> if hasattr(composerView, "addComposerShape"):
> ...

Using hasattr is very general and works in almost all the cases.

I didn't like the try - import - except block,
it may be a good option if you have to switch between functions,
classes or modules.

>> try:
>>     from qgis.core import newFunctionName as function
>> except:
>>     from qgis.core import oldFunctionName as function

But if you call a method within that block it could throw different
kind of exceptions (even user defined ones), so you should catch the
AttributeError only to really understand if the method is available.
On the contrary, if you don't call the method within the block but
just use the block to get the method (i.e. storing it in a variable),
than it's the same of calling the hasattr function.

I remember that when at the Wroclaw HF I added the
addPluginToDatabaseMenu method some people got a TypeError
probably due to a PyQt bug:

TypeError: 'sip.methoddescriptor' object is not callable

The solution was using hasattr [1] instead of the
try - except AttributeError block and it seems to work fine until now :)


Anyway, particular cases (e.g. a function is moved between classes
keeping its arguments like the changes made in QgsComposerView)
can be handle using a lot of other ways in python.

A very compat (and nice too) solution is to use the getattr's default third
parameter:
"""
getattr(composerView, 'addComposerShape', composition.addComposerShape)
"""

<crazy mode on>
Another way may be to add a fake attribute to the new class object
that points to the method on the old class object
"""
if not hasattr(composition, 'addComposerShape'):
    composition.addComposerShape = composerView.addComposerShape
"""
and then calling it as you call the API2.0 method :)
"""
composition.addComposerShape(item)
"""
<crazy mode off>
... but this works fine only if the composerView is not deleted before you
call the fake method on the composition :(


It's time to go eat something.
Bye.

[1] http://hub.qgis.org/projects/quantum-gis/wiki/Database#Put-a-plugin-into-Database-menu

-- 
Giuseppe Sucameli


More information about the Qgis-developer mailing list