1

After reading Mapping rpy2 objects to arbitrary python objects I thought the following would allow the conversion of Python None to R NULL:

import rpy2.robjects.conversion as cv
import rpy2.robjects as robjs
from rpy2.robjects import default_converter
from rpy2.robjects.packages import importr

r_base = importr("base")


def _none2null(none_obj):
    return robjs.r("NULL")


none_converter = cv.Converter("None converter")
none_converter.py2rpy.register(None, _none2null)

with cv.localconverter(default_converter + none_converter):
    filesl = r_base.list_files(pattern=None)

However, it fails with the Trace:

NotImplementedError: Conversion 'py2rpy' not defined for objects of type '<class 'NoneType'>'

How can this be handled?

3
  • 2
    Does this answer your question? Convert NULL from Python to R using rpy2 Commented Jan 18, 2021 at 22:43
  • No, unfortunately. Using robjs.NULL in the converter function gives the same result Commented Jan 18, 2021 at 23:46
  • This is a good question as rpy2 user may wish to have their Nones auto-converted to NA, NULL or another R construct. Converter is the proper pattern here and is distinct from manual conversion as in the question linked by @PacketLoss Commented Jan 20, 2021 at 13:34

1 Answer 1

1

The Converter.register() method accepts type of an object to convert as the first argument, but you passed an instance. None is an instance of NoneType:

NoneType = type(None)
NoneType() is None   # True

and you need to define conversion for NoneType, so you can just use:

none_converter.py2rpy.register(type(None), _none2null)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is very useful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.