Next / Previous / Contents / Shipman's homepage

11.17. BirdId.parse(): Parse a code from a string

This static method takes a simple or compound code as a string and returns a BirdId.

abbr.py
# - - -   B i r d I d . p a r s e   - - -

    def parse ( txny, s ):
        """Parse a bird code from a string.
        """

First we check to see if the last character is "?", and remove it and set q to "?" if so. Otherwise we set q to None.

abbr.py
        #-- 1 --
        if  s[-1] == '?':
            s = s[:-1]
            q = '?'
        else:
            q = None

The general approach here is to use regular expressions to recognize the first or only bird code, optionally followed by a relationship code and a second bird code.

abbr.py
        #-- 2 --
        # [ if s starts with pattern RE_ABBR ->
        #     abbr   :=  matching part of s
        #     abbr2  :=  None
        #     rel    :=  None
        #   else -> raise ValueError ]
        m = RE_ABBR.match ( s )
        if  m is None:
            raise ValueError, ( "Not a valid BirdId: '%s'" % s )
        abbr = m.group()
        rest = s [ m.end() : ]

        #-- 3 --
        # [ if rest is empty ->
        #     return a new simple BirdId made from abbr
        #   else -> I ]
        if  len(rest) == 0:
            return BirdId ( txny, abbr, None, None, q )

        #-- 4 --
        # [ if rest starts with pattern RE_REL ->
        #     rel    :=  the matching part of rest
        #     final  :=  rest past the matching part
        #   else -> raise ValueError ]
        m = RE_REL.match ( rest )
        if  m is None:
            raise ValueError, ( "Expecting a relationship code:"
                "'%s'" % rest )
        rel = m.group()
        final = rest [ m.end() : ]

        #-- 5 --
        # [ if final starts with pattern RE_ABBR ->
        #     abbr2  :=  matching part
        #     tail   :=  part of final past the match
        #   else -> raise ValueError ] 
        m = RE_ABBR.match ( final )
        if  m is None:
            raise ValueError, ( "Expecting 2nd abbr: '%s'" %
                                final )
        abbr2 = m.group()
        tail = final [ m.end() : ]

        #-- 6 --
        if  len(tail.strip()) > 0:
            raise ValueError, ( "Garbage after 2nd abbr: '%s'" %
                                tail )
        else:
            return BirdId ( txny, abbr, rel, abbr2, q )

    parse = staticmethod ( parse )