pythonpython-2.x

How to cast to long depending on Python version?


I'm dealing with numbers, that may be too large for int as understood by Python-2.x, so my code's been casting them to long.

In Python-3.x there is no such thing, and one is simply supposed to use int. However, the code needs to work with both Python-2 and 3 (for as long RHEL8 is a thing), so I tried the following trick:

    if sys.version_info[0] >= 3:
        long = int
    ...
    foo = (long)(bar)

This works in Python-3.x, but in Python-2.x it breaks with: local variable 'long' referenced before assignment. Why wouldn't it just continue to use the built-in type long -- as it did before I inserted the above two lines into the function?

Update, the actual loop, parses the output of Linux stat-utility:

        if sys.version_info[0] >= 3:
                long_t = int
                output = output.decode(locale.getpreferredencoding())
        else:
                long_t = long

...
        for section in [output[x:x + 5] for x in range(0, len(output), 5)]:
                stats = [f.split() for f in section]
                path = stats[0][1].strip('"')
                result[path] = {}
                for (field, type, x, y) in [
                        ('id', str, 1, 1),
                        ('namelen', int, 1, 3),
                        ('type', str, 1, 5),
                        ('blocksize', int, 2, 2),
                        ('fblocksize', int, 2, 6),
                        ('blockstotal', long_t, 3, 2),
                        ('blocksfree', long_t, 3, 4),
                        ('blocksavailable', long_t, 3, 6),
                        ('inodestotal', long_t, 4, 2),
                        ('inodesfree', long_t, 4, 4)
                ]:
                        result[path][field] = (type)(stats[x][y])

Solution

  • So, as work-around, I introduced a separate variable, long_t:

        if sys.version_info[0] >= 3:
            long_t = int
        else:
            long_t = long
        ...
        foo = (long_t)(bar)
    

    This works with both Python-versions, but I still don't understand, why this was necessary...