Search code examples
pythonmaintainability

Is there any more compact way of writing that statement?


I had to write a script that generates some fixture file with increasing fake MAC addresses.

To do that, I decided to have some fun and try to make it as compact as I could. I ended up with:

def mac_address(i):
    return ':'.join(['%02x'] * 6) % tuple([(i >> (8 * j)) & 0xFF for j in reversed(range(6))])

Which actually works pretty well. Obviously, writing this that way is the best way to get slapped by the future person that must work on it, but I did it for the fun (and wrote a more readable version in comment).

But now I'm curious, can you think of any more compact way of writing that ? (That is without removing the spaces).


Solution

  • What about

    ':'.join('%02x' % (i>>(8*j) & 0xFF) for j in reversed(range(6)))
    

    That is more compact and easier to understand.