Friday, March 4, 2011

What are some strategies to write python code that works in CPython, Jython and IronPython

Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?

From stackoverflow
  • If you do find you need to write unique code for an environment, use pythons

    import mymodule_jython as mymodule
    
    import mymodule_cpython as mymodule
    

    have this stuff in a simple module (''module_importer''?) and write your code like this:

    from module_importer import mymodule
    

    This way, all you need to do is alter module_importer.py per platform.

    minty : So Daren, is there a way to make module_importer import the right variable dynamically based on some environment variable etc.
    Daren Thomas : Sorry, I am drawing a blank here. This would be an excelent SO question though: "How to dynamically find out if we are running Jython, CPython or IronPython?". Then, you could just do it in ifs...
    J.F. Sebastian : Python's module `os` can be used as an example. It provides OS routines e.g., `os.unlink`, `os.rename`, etc depending on what system you're on.
  • @Daren Thomas: I agree, but you should use the platform module to determine which interpreter you're running.

    Cyberdrow : As far as I know 'platform' is not available in IronPython (2.0.1). 'os' isn't either.
  • I write code for CPython and IronPython but tip should work for Jython as well.

    Basically, I write all the platform specific code in separate modules/packages and then import the appropriate one based on platform I'm running on. (see cdleary's comment above)

    This is especially important when it comes to the differences between the SQLite implementations and if you are implementing any GUI code.

  • The #1 thing IMO: Focus on thread safety. CPython's GIL makes writing threadsafe code easy because only one thread can access the interpreter at a time. IronPython and Jython are a little less hand-holding though.

  • I'm pretty sure you already know this but unfortunately Jython can't load c extension modules.

  • There are two major issues at play here...

    Firstly, to my knowledge, only CPython has RAII - you have to close your own resources in Jython, Ironpython, etc.

    And Secondly, as has been mentioned, is thread safety.

0 comments:

Post a Comment