Skip to content

Remove use of Bio._py3k (Python 2 / 3 compatibility) #2420

Closed

Description

@peterjc

As of Biopython 1.76 (released December 2019), we are dropping Python 2 support and focusing on Python 3.6 or later. This means we no longer need our (internal) Python 2 vs 3 compatibility library Bio._py3k (which is a bit like the third party library six).

This issue is suitable and specifically targeting first time contributors.

There are lots of cases:

$ grep _py3k Bio*/*.py Bio/*/*.py Bio/*/*/*.py
Bio/File.py:from Bio._py3k import basestring
Bio/MarkovModel.py:        from Bio._py3k import StringIO
Bio/Seq.py:from Bio._py3k import range
Bio/Seq.py:from Bio._py3k import basestring
...

Example One

Taking the first example, from Bio._py3k import basestring we see that this is defined under Python 3 as an alias of str:

https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L56

    # Lots of our Python 2 code uses isinstance(x, basestring)
    # which after 2to3 becomes isinstance(x, str)
    basestring = str
    unicode = str

Therefore the fix for Bio/File.py is to remove the from Bio._py3k import basestring line, and update where basestring was used to instead use str, which in this case means editing one line:

if isinstance(handleish, basestring):

with:

if isinstance(handleish, str):

Example Two

Taking the second example, Bio/MarkovModel.py has from Bio._py3k import StringIO which we find on Python 3 can just be replaced with from io import StringIO

https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L130

Contributing

Could any newcomer wanting to work on this first comment on this issue saying which file(s) they are going to start with (e.g. Bio/File.py, or BioSQL/) to avoid duplication of effort.

(Update: The consensus was to switch to be function or constant instead, since they generally require the same technique/fix each time)

Then read https://github.com/biopython/biopython/blob/master/CONTRIBUTING.rst and setup flake8 on your machine.

Then make a pull request making the necessary changes so that those files no longer import from Bio._py3k. Once that's done, you could pick some more to work on.

Eventually there will be nothing using Bio._py3k and that code itself can be removed, and this issue closed.

Activity

  1. added
    good first issue
    on Dec 20, 2019
  2. Dsujan commented on Dec 24, 2019

    @Dsujan
    Contributor

    I would be starting in BioSQL/

  3. Dsujan commented on Dec 25, 2019

    @Dsujan
    Contributor

    @peterjc What to do incase of methods?
    Example:
    https://github.com/biopython/biopython/blob/biopython-176/BioSQL/Loader.py#L564

    from Bio._py3k import _is_int_or_long
    ...
    L564 -> assert _is_int_or_long(parent_taxon_id), repr(parent_taxon_id)
    

    uses the _is_init_or_long method declared in Bio._py3k for assertion

    https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L91
    https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L176

    Python 3 doesn't have longs, so should we drop the assertion and also in other similar cases where methods are used fro _py3k what should be done?

  4. peterjc commented on Dec 25, 2019

    @peterjc
    MemberAuthor

    Python 3 doesn't separate int and long, just use isinstance(parent_taxon_id, int) instead.

  5. added a commit that references this issue on Dec 25, 2019
  6. Dsujan commented on Dec 26, 2019

    @Dsujan
    Contributor

    @peterjc I am new to this code base so I am little bit confused.
    In _py3k there are many Private functions for encoding/decoding. Like:

    https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L64
    https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L158

    And used like this:

    from Bio._py3k import _bytes_bytearray_to_str as bytearray_to_str
    
    def execute_and_fetch_col0(self, sql, args=None):
            """Return a list of values from the first column in the row."""
            out = super(MysqlConnectorAdaptor, self).execute_and_fetch_col0(sql, args)
            return [bytearray_to_str(column) for column in out]
    

    What should be done in these cases?

  7. peterjc commented on Dec 26, 2019

    @peterjc
    MemberAuthor

    I think _bytes_bytearray_to_str is only used here in the MysqlConnectorAdaptor class in BioSQL. It is defined as follows for Python 3:

        def _bytes_bytearray_to_str(s):
            """If s is bytes or bytearray, convert to a unicode string (PRIVATE)."""
            if isinstance(s, (bytes, bytearray)):
                return s.decode()
            return s

    So, moving this definition into BioSQL/BioSeqDatabase.py might be the best short term solution.

  8. Dsujan commented on Dec 26, 2019

    @Dsujan
    Contributor

    @peterjc Please review #2440
    Now I would be working in Tests/

  9. lorforlinux commented on Dec 26, 2019

    @lorforlinux
    Contributor

    Started working on functions in Bio/
    (🍄 = working on it, ✔️ = done)

    Function Status
    raise_from ✔️
    StringIO ✔️
    urlretrieve ✔️
    urlopen ✔️
    Request ✔️
    urlparse ✔️
    urlcleanup ✔️
    urlencode ✔️
    quoteURLError ✔️
    HTTPError ✔️
  10. peterjc commented on Dec 26, 2019

    @peterjc
    MemberAuthor

    That seems like a few, and covers quite a range. I wonder in hindsight if I should have suggested people work on a functions/constants basis rather than a module by module basis? Oh well, this way you'll all learn more about Python 2 vs Python 3.

  11. lorforlinux commented on Dec 26, 2019

    @lorforlinux
    Contributor

    @peterjc After I started doing it I was thinking of the same, I guess I should do it on a function basis rather than a module. Also, can you please check the code below and tell me if it is the right way of doing it.

    image

  12. peterjc commented on Dec 26, 2019

    @peterjc
    MemberAuthor

    @deepaklorkhatri007 For this line:

    https://github.com/biopython/biopython/blob/biopython-176/Bio/Align/__init__.py#L1359

    In Python 3 we'd just do this:

    raise IndexError("index out of range") from None

    This explicitly discards the traceback context (this was inside a try/except with a StopIteration error).

  13. lorforlinux commented on Dec 26, 2019

    @lorforlinux
    Contributor

    @peterjc thanks for clarifying the change needed, I have one more question, to check if the code is valid I should be running the test file$ python test_align.pyand for formatting and code style, I should be using $ flake8 right?

  14. peterjc commented on Dec 26, 2019

    @peterjc
    MemberAuthor

    @deepaklorkhatri007 Depending which code you are editing, there may be more than one test covering it - run_tests.py would take longer but cover everything (see also the testing chapter in the Tutorial).

    And yes, please do run flake8 locally with all the plugins listed on https://github.com/biopython/biopython/blob/master/CONTRIBUTING.rst - the git pre-commit hook helps here.

    Together that will catch most of the possible failures the automated testing with TravisCI and AppVeyor would pick up (and more since they don't run the online tests needing network access, like some of the BLAST tests you ought to run if you're editing Bio.Blast files).

  15. 22 remaining items

  16. peterjc commented on Jan 8, 2020

    @peterjc
    MemberAuthor

    The final bit to deal with is _binary_to_string_handle used in three of our online functions to convert binary network handles into text handles. On the subject of encodings (see also #2512), and online resources:

    https://github.com/biopython/biopython/blob/biopython-176/Bio/_py3k/__init__.py#L111

                # The W3C recommendation is:
                # When no explicit charset parameter is provided by the sender,
                # media subtypes of the "text" type are defined to have a default
                # charset value of "ISO-8859-1" when received via HTTP.
                # "ISO-8859-1" is also known as 'latin-1'
                # See the following for more detail:
                # https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1

    We might want to rename and move this to Bio/_utils.py if there is no concise equivalent in the standard library?

  17. peterjc commented on Jan 8, 2020

    @peterjc
    MemberAuthor

    Didn't mean to close this via #2513, still have _binary_to_string_handle to deal with.

  18. removed
    good first issue
    on Jan 8, 2020
  19. reopened this on Jan 8, 2020
  20. mdehoon commented on Jan 8, 2020

    @mdehoon
    Contributor

    We might want to rename and move this to Bio/_utils.py if there is no concise equivalent in the standard library?

    In my experience, utility modules like Bio/_utils.py tend to disappoint in the end (see ParserSupport for an older example). They tend to get underused (because people are unaware of them, and anyway will first look at the standard library and find there what they need), tend to become overengineered (to accommodate all different applications), and after a while we decide to remove them again (costing time and effort in deprecation warnings etc.).

    The _binary_to_string_handle function is currently being used in Bio/KEGG and Bio/TogoWS (once each), and four times in Bio/ExPASy. For Bio.ExPASy at least, it's easy to just replace _binary_to_string_handle with the code explicitly. Most of the lines in _binary_to_string_handle would not apply there anyway. This has the added benefit of the code being easier to read for the next person looking at this code.

  21. peterjc commented on Jan 8, 2020

    @peterjc
    MemberAuthor

    I don't understand what you mean about most of the lines not applying?

    The KEGG, TogoWS and ExPASy usage (and historic Entrez usage) is all the same - wrapping a binary network handle to give a unicode text handle. The key point is following the W3C recommendation quoted earlier, we determine the encoding from the HTTP headers if possible, defaulting to latin-1. The secondary functionality was to ensure the .url attribute was still available on the wrapped handle.

    If we know the encoding used by each site in advanced, then yes, the code is greatly simplified. But do we? What made you assume UTF8 for Entrez? This was something I missed in reviewing #2461 where as part of the Python 3 updates, you switched to use:

        subtype = handle.headers.get_content_subtype()
        if subtype == "plain":
            url = handle.url
            handle = io.TextIOWrapper(handle, encoding="utf8")
            handle.url = url
        return handle
    

    I note the Python urllib example also assumes a UTF8 encoding, rather than checking the sever's headers, but stated that the example site used that encoding:

    https://docs.python.org/3/library/urllib.request.html#examples

    Unless that W3C encoding advice has been superseded, I think KEGG, TogoWS, ExPASy and Entrez should all use the same helper function here.

    If we could just assume UTF8, then there is less call for a shared helper function.

  22. mdehoon commented on Jan 9, 2020

    @mdehoon
    Contributor

    If we could just assume UTF8, then there is less call for a shared helper function.

    We can. KEGG, TogoWS, ExPASy, and Entrez all report utf-8 in handle.headers.get_content_charset(). Even if some day they report latin-1, my first instinct would be that this is a bug and the contents is actually in UTF-8.

    The other part of _binary_to_string_handle is to add the url as an attribute. Here you can drop the try: except: block since the handle was opened by urlopen. Then _binary_to_string_handle becomes trivial.

  23. peterjc commented on Jan 9, 2020

    @peterjc
    MemberAuthor

    On that basis (that all four relevant online servers declare UTF8), then I agree - do you want to make that pull request, or perhaps write it up as an issue suitable for a new contributor? Or I could implement it.

  24. mdehoon commented on Jan 9, 2020

    @mdehoon
    Contributor

    See #2521

  25. added a commit that references this issue on Jan 9, 2020
  26. peterjc commented on Jan 9, 2020

    @peterjc
    MemberAuthor

    And that job is done - thank you everyone 🎉

  27. mdehoon commented on Jan 10, 2020

    @mdehoon
    Contributor

    Somebody should also go over the Tutorial and remove references to Python 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions