4

I was running the 2to3 tool on various scripts I'd written to get an idea of what I will need to change to port these to Python 3 (though I will be doing it by hand in the end).

While doing so, I ran into an odd change 2to3 made in one of my scripts:

-def open_pipe(pipe, perms=0644):
+def open_pipe(pipe, perms=0o644):

Um... Why did 2to3 add a "o" in the middle of my "perms" integer?

That's line 41 from the original source found here: https://github.com/ksoviero/Public/blob/master/tempus.py

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
Soviero
  • 1,774
  • 2
  • 13
  • 23

3 Answers3

4

Try typing 0644 in your python2 shell. It will give you a different number because it is octal. In python3, the 0o signifies an octal number.

python2:

>>> 0644
420
>>> 

python3:

>>> 0644
  File "<stdin>", line 1
    0644
       ^
SyntaxError: invalid token
>>> 0o644
420
>>> 

New in python3:

Octal literals are no longer of the form 0720; use 0o720 instead.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Actually: the `0o` indicates an octal number, because `o644` is considered an identifier not a numeric literal. It might be helpful to mention also `0b` for binary literals and `0x` for hex literals. – Bakuriu Jun 12 '14 at 14:43
3

According to What's New In Python 3.0 - Integers:

Octal literals are no longer of the form 0720; use 0o720 instead.

falsetru
  • 357,413
  • 63
  • 732
  • 636
2

The old notation octal with a single 0 prefix is not allowed anymore in Python 3. To explicitly give an octal value, you need to prefix the number by a 0o:

$ python
Python 2.7.3 (default, Dec 18 2012, 13:50:09)
>>> 0644
420
>>>

$ python3
Python 3.2.3 (default, Jul 23 2012, 16:48:24)
>>> 0644
  File "<stdin>", line 1
    0644
       ^
SyntaxError: invalid token
>>> 0o644
420

According to the documentation, linked above:

Octal literals are no longer of the form 0720; use 0o720 instead.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97