Skip to content

Replace use of mult-line assert statements #1515

Closed

Description

@peterjc

Biopython has lots of assert statements, many of which are in code for parsing files and might be better turned into explicit error raising code:

$ grep --include '*.py' -rn ' assert ' Bio BioSQL | wc -l
     629

Note there are some which are really in-line self tests, which I am more comfortable with, but this is still not ideal:

$ grep --include '*.py' -rn '^assert' Bio BioSQL | wc -l
      82

In order to enable flake8 check E127, I would particularly like to fix the multi-line assert statements. Some of these are complicated checks, but most have an assert message which makes them the best candidates for turning into explicit exceptions:

$ grep --include '*.py' -rn ' assert .*\\$' Bio BioSQL | wc -l
     130

For example, the first of these is in Bio/AlignIO/__init__.py at currently at line 236:

    assert isinstance(count, int), "Internal error - the underlying %s " \
           "writer should have returned the alignment count, not %s" \
           % (format, repr(count))

That should probably be something like this - also note I am avoiding the unnessary use of the slash line continuation characters here:

    if not isinstance(count, int):
        raise RuntimeError("Internal error - the underlying %s "
                           "writer should have returned the alignment count, not %s"
                           % (format, repr(count))

This issues is a tracking issue to coordinate clean up of these multi-line assert statements which would better be written as explicit exceptions. This is hopefully a beginner friendly task, aimed mainly at potential new contributors.

If you would like to contribute, please comment here saying which parts of the code you are going to work on to avoid duplicated effort (e.g. one or two directories at a time).

Activity

  1. added
    good first issue
    on Jan 24, 2018
  2. MarkusPiotrowski commented on Jan 24, 2018

    @MarkusPiotrowski
    Contributor

    I also want to shortly point out that asserts are not the tool to inform the user about possible errors. Asserts are for the programmer to check for conditions that should never occur, and if they occur, then there is a problem with my code. E.g. my intention and expectation is that count is always an int. If it isn't I have missed something crucial.
    If an error is likely, e.g. missing files, missing rights to write to a file, wrong user input, etc., then raising an exception is the intended way to inform the user.

  3. siongkong commented on Jan 24, 2018

    @siongkong
    Contributor

    I replaced the multiline assert statements in the HMM module, PR in #1516.

  4. peterjc commented on Jan 25, 2018

    @peterjc
    MemberAuthor

    @MarkusPiotrowski you're right, there is a spectrum here. See also https://wiki.python.org/moin/UsingAssertionsEffectively

    From memory, most of the asserts in our parser code are defensive coding which could be triggered by bad input. Many of those ought to be exceptions.

    Even for the Biopython programmer's sanity checks, there is an argument for using exceptions as python -O ... would turn asserts off?

  5. bvaisvil commented on Apr 4, 2018

    @bvaisvil
    Contributor

    If no one has started on Bio/AlignIO, I can start tackling that.

  6. bvaisvil commented on Apr 13, 2018

    @bvaisvil
    Contributor

    @peterjc I have a quick question. I've changed the multi-line assert statements in Bio/AlignIO. Should I make a pull request for that?

    There are quite a few more assert statements that could be converted into exceptions. My thought here is to specifically address the multiline assert statements first so the flake8 check could be turned on. Then one could make a second pass at the other assert statements to see if they shouldn't actually be exceptions.

  7. peterjc commented on Apr 13, 2018

    @peterjc
    MemberAuthor

    @bvaisvil Yes please, a pull request on AlignIO would be great.

  8. bvaisvil commented on Apr 19, 2018

    @bvaisvil
    Contributor

    Next I'll work on Bio/Alphabet through Bio/Cluster

  9. 7 remaining items

  10. peterjc commented on Aug 22, 2018

    @peterjc
    MemberAuthor

    Closed via #1748, there are a few remaining multi-line asserts (mostly commented out):

    $ grep --include '*.py' -rn ' assert .*\\$' Bio BioSQL 
    Bio/bgzf.py:625:        # assert virtual_offset == self.tell(), \
    Bio/codonalign/codonseq.py:94:            #    assert  len(self) % 3 == 0, \
    Bio/File.py:315:            # assert length or format in ["sff", "sff-trim"], \
    Bio/GenBank/Scanner.py:1209:            # assert line[29:33] in [' bp ', ' aa ',' rc '] , \
    Bio/Graphics/BasicChromosome.py:580:# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \
    Bio/Graphics/BasicChromosome.py:582:# assert _spring_layout([0.10,0.12,0.13,0.14,0.5,0.75, 1.0], 0, 1, 0.1) == \
    Bio/SearchIO/BlatIO.py:327:        assert len(psl['tseqs']) == len(psl['qseqs']) == \
    Bio/Seq.py:1488:        # assert new_length == len(("X"*old_length)[index]), \
    Bio/SeqIO/InsdcIO.py:676:        # assert line[12:28].rstrip() == locus, \
    Bio/SeqIO/InsdcIO.py:679:        # assert line[29:40].lstrip() == str(len(record)), \
    Bio/SubsMat/__init__.py:265:        assert non_sym is None or isinstance(non_sym, float) or \
    BioSQL/Loader.py:442:                assert taxonomic_record[0]["TaxId"] == str(ncbi_taxon_id), \
    

    However, flake8 E127 now passes, and we now enforce this as of e70ad42

    $ flake8 --select E127 Bio,BioSQL
    
  11. peterjc commented on Aug 22, 2018

    @peterjc
    MemberAuthor

    That was premature, reverted in f93043f

    Something odd in my local testing - see https://travis-ci.org/biopython/biopython/builds/419192810 which has a few E127 (and loads of E128) errors.

  12. nimne commented on Aug 22, 2018

    @nimne
    Contributor

    I have a branch that passes E127 and E128 checks. Most of the changes were really minor (adding/removing spaces).

    The changes that I wasn't sure how to approach best were in Bio/SearchIO/_model/hsp.py.

    Things like this:

    query_strand = property(fget=_query_strand_get, fset=_query_strand_set,
            doc="""Query sequence strand, defaults to None""")
    

    are corrected to this:

    query_strand = property(fget=_query_strand_get, fset=_query_strand_set,
                            doc="""Query sequence strand, defaults to None""")
    

    which makes them really long in some cases. Any thoughts?

  13. peterjc commented on Aug 23, 2018

    @peterjc
    MemberAuthor

    Having looked at the work in progress, I'm a bit surprised how much funny indentation was left - and look forward to a pull request cleaning this up. My only real point was I'd prefer not to introduce unnecessary slash line continuation - this can almost always be avoided (sometimes with the addition of brackets).

    Regarding the property definitions in SearchIO, I think the longer lines are still an improvement, and if they are really long the string can be split.

    Note that example (and most like it) do not need to be triple quoted as they are single lines with no line breaks. i.e. This is better:

    query_strand = property(fget=_query_strand_get, fset=_query_strand_set,
                            doc="Query sequence strand, defaults to None.")

    This also makes it neater to split the string over multiple lines if needed - something like this:

    query_strand = property(fget=_query_strand_get, fset=_query_strand_set,
                            doc="Query sequence strand, defaults to None except "
                                 "on days ending with the letter y.")

    Note I've also added the missing trailing full stop - these doc strings become the property's docstring, so ought to follow the PEP257 style conventions.

    Update: I logged PyCQA/pydocstyle#328 on the property function doc argument validation.

  14. nimne commented on Aug 24, 2018

    @nimne
    Contributor

    Thanks for the feedback. I agree, there are usually better alternatives than the slash line continuation.

    I changed the triple quotes which made breaking up the long lines simple, and I added a full stop where needed.

    I need to look over the changes carefully and I'll submit a pull request soon.

  15. added a commit that references this issue on Aug 24, 2018
  16. peterjc commented on Aug 24, 2018

    @peterjc
    MemberAuthor

    We're now enforcing flake8 E127 and E128 on Bio and BioSQL, so I'm going to close this issue now.

    I've filed a new issue for enforcing flake8 E127 and E128 on Tests, #1769.

    @nimne if you want to work on that too, please comment on the new issue to avoid any duplication of effort. Thank you!

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementStylegood first issue

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions