Varable parsing error with python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Feb 10 18:55:17 EST 2015


OmPs wrote:

> On 10 Feb 2015 13:59, "OmPs" <torque.india at gmail.com> wrote:

>> Tried that as well getting the same error.
> 
> I feel its something to do with variable substitution.

Python doesn't do variable substitution. At least not the way I think of it.
What do you mean by "variable substitution"?

Instead of "feeling" what the problem is, let's do some old-fashioned
debugging. Start by reading through the code, and in your head (or on
paper) trace through the possible lines that may be reached. The
_getPackgeVersion function has only 11 lines, it isn't hard. Here is your
function again:


def _getPackgeVersion(xmlfile, p):
    package = str(p)
    if isinstance(fpmdict["application"]["package"], list):
        for i in fpmdict["application"]["package"]:
            if i["@name"] == p:
                _pkgVersion = i["version"]
    else:
        _pkgversion = fpmdict["application"]["package"]["version"]
        return _pkgVersion


I can immediately see four problems:

(1) One branch of the "if isinstance" fails to return. So if the function
takes that branch, it will finish the loop, then exit the if...else clause,
then hit the end of the function and return None.

(2) Sometimes that branch may fail to set the _pkgVersion variable at all,
if none of the "@name" keys equal p.

(3) The other branch fails to set the _pkgVersion variable. Python is
case-sensitive, so _pkgversion and _pkgVersion are different variables.

(4) Your package variable is never used.

I don't know how to fix problem #2 since I don't know what behaviour would
be useful to you. So I'll just leave that for you. I can fix problems #1 #3
and #4:

def _getPackgeVersion(xmlfile, p):
    if isinstance(fpmdict["application"]["package"], list):
        for i in fpmdict["application"]["package"]:
            if i["@name"] == p:
                _pkgVersion = i["version"]
    else:
        _pkgVersion = fpmdict["application"]["package"]["version"]
    return _pkgVersion


Now we can see that if _getPackgeVersion still returns None, the only way it
can do so is if the "version" key is set to have None as a value.

Are you sure that there is a "version" key set?



I can see another problem, earlier in your code:


for i in doc.get("application").get("instance", None):
    ...


That does not do what you expect. If there is no "instance" key, the second
get will return None, which is not iterable:

py> for i in None:
...     pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable




-- 
Steven




More information about the Python-list mailing list