2

What are the design issues driving Python to not support built in unsigned types?

I know that in Python an int is an abstraction of an integer value, but why can it not represent the abstraction fixed-byte-size integer?

Engineero
  • 12,340
  • 5
  • 53
  • 75
vilanova
  • 77
  • 1
  • 10
  • You can use `ctypes` if you feel you need this functionality. https://stackoverflow.com/questions/19716315/how-to-create-a-fixed-size-unsigned-integer-in-python In general Python tries to abstract away from details like the size of a data type. – Cory Kramer Oct 10 '15 at 17:42
  • Neither does PHP or Java. would be curious to know why. Probably design decision. – Ali Gajani Oct 10 '15 at 17:43
  • 1
    Because python is focused on ease of use much more than efficiency. In Java for example you have to decide between byte, short, int, long, and sometimes even BigInteger. In python ints are the equivalent of BigInteger - they are arbitrary precision. This is less efficient but the designer(s) preferred the tradeoff. – Alex Hall Oct 10 '15 at 17:43

2 Answers2

1

In a non-Python like language like C, the unsigned type is very useful if you want control over the exact range and wrapping of your numbers.

In Python, as Alex Hall mentioned in the comment, ints have unlimited precision. Therefore the distinction between signed and unsigned does not really have any meaning.

If you are looking to optimize performance of your code and are willing to give up the flexibility and power of Python, you could use Cython and annotate specific variables as "unsigned int". Have a look at http://docs.cython.org/src/userguide/language_basics.html.

Jonah Graham
  • 7,890
  • 23
  • 55
  • Good answer. I'd just like to amplify your point "willing to give up the flexibility and power of Python", which could alternately be read "don't do this in Python because it makes bad Python". You were more diplomatic than I. – msw Oct 10 '15 at 19:15
  • The meaning would be type-safety. So for example, if you have a parameter "length of something", sure it would not make sense for it to be negative. – Hi-Angel Mar 03 '21 at 13:59
0

For the same reason that PHP or Java doesn't. From here, about Java:

Gosling: For me as a language designer, which I don't really count myself as these days, what "simple" really ended up meaning was could I expect J. Random Developer to hold the spec in his head. That definition says that, for instance, Java isn't -- and in fact a lot of these languages end up with a lot of corner cases, things that nobody really understands. Quiz any C developer about unsigned, and pretty soon you discover that almost no C developers actually understand what goes on with unsigned, what unsigned arithmetic is. Things like that made C complex. The language part of Java is, I think, pretty simple. The libraries you have to look up.

So it's really about simplicity.

If you feel like you really need this feature, you can always use ctypes.