`iteritems()` calls are incompatible with Python 3.x

Issue #295 invalid
Ed Schofield created an issue

There seem to be a few calls to the iteritems() method in the rpy2 codebase. These are not compatible with Python 3.x for dict-like objects.

Here is one example. I am exploring the functionality available in rpy2.robjects.pandas2ri to convert data frames between R and Pandas:

>>> env = data(rpackages.datasets).fetch('trees')
>>> df = env['trees']
>>> import rpy2.robjects.pandas2ri as rpyp
>>> rpyp.py2ri_pandasdataframe(df)

/Users/schofield/anaconda/lib/python3.4/site-packages/rpy2/robjects/pandas2ri.py in py2ri_pandasdataframe(obj)
     35 def py2ri_pandasdataframe(obj):
     36     od = OrderedDict()
---> 37     for name, values in obj.iteritems():
     38         if values.dtype.kind == 'O':
     39             od[name] = StrVector(values)

AttributeError: 'DataFrame' object has no attribute 'iteritems'

This is with rpy2 2.6.1, Python 3.4.3, and R 3.2.1.

RPy2 already uses six; this provides a Py2/3 compatible iteritems() function that RPy2 could use.

There are also various references to iteritems() method calls in the docs:

host:rpy2 schofield$ hg grep iteritems doc
doc/robjects_functions.rst:2342:              for k, v in kwargs.iteritems:
doc/porting-to-rpy2.rst:2268:   for k, v in edsummary.iteritems():
doc/vector.rst:2184:or any Python object implementing the method :meth:`iteritems`
doc/source/porting-to-rpy2.rst:2182:   for k, v in edsummary.iteritems():
doc/source/robjects_functions.rst:1682:          for k, v in kwargs.iteritems:
doc/source/vector.rst:1682:or any Python object implementing the method :meth:`iteritems`
doc/source/robjects.rst:1228:          for k, v in kwargs.iteritems:

I suggest simply replacing these with items() for maximum compatibility and simplicity.

Comments (7)

  1. Ed Schofield reporter
    • edited description

    Update: after changing the offending iteritems() call to items() in my own installation, I realise that the call above to py2ri_pandasdataframe was perhaps never supposed to work. This works instead:


    So this may be more of a documentation bug; conversions of DataFrames between R and Pandas with the new pandas2ri module are not yet documented.

  2. Laurent Gautier
    • changed status to open

    Thanks for the report. While rpy2 is developed for python 3, compatibility with 2.7 is ensured by six. This function should have a test.

  3. Laurent Gautier

    I am marking this as invalid (as things turns out to be working as expected with Python 3).

    The method iteritems() used is the one provided by pandas data frames. The specific place you point out in the code is only used with such objects (check the rpy2 doc about the conversion system - it is using single dispatch).

  4. Log in to comment