Python Version 2 versus 3

ParaView is working towards full Python 3 support. To that end, python code should be written so it is compatible with Python 2.7 and Python 3.5.

Here are the changes we have needed making the transition to Python 3.

Exceptions

raise RuntimeError, "failed"

is replaced by:

raise RuntimeError("failed")

Handling exceptions as objects must use the as keyword:

except AttributeError as attrErr:

Iterables

To create an iterable, Python 3 needs a __next__() method. Assign the Python 2 next() method to it:

__next__ = next # Python 3.x compatibility

Iterators, not lists

Several methods now return an iterable object, not a list. Examples include:

  • range(), map(), filter(), zip()
  • dictionary’s keys() values(), and items() methods

If you need a list, just wrap the return in a list:

list(array_colors.keys())

Dictionaries also lost the iterkeys(), iteritems() and itervalues() methods. Simply use keys or items() to get values instead.

for key, value in kwargs.iteritems():
    self.analysis[key] = value

becomes:

for key in kwargs:
    self.analysis[key] = kwargs[key]

or:

for key, value in kwargs.items():
    self.analysis[key] = value

Submodule import

The only valid syntax in Python 3 for relative submodule import is:

from .some_module import *

Be explicit when importing submodules whenever possible.

New modules

Any new modules or significant work on old code should add:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

to the top, to ensure forward compatibility with Python 3.