7 ms·
The Python problem is amusing. Python 3 has three representations of strings internally (1-byte, 2-byte, and 4-byte) and promotes them to a wider form when nece
by Animats 10y ago
The Python problem is amusing. Python 3 has three representations of strings internally (1-byte, 2-byte, and 4-byte) and promotes them to a wider form when necessary. This is mostly to support string indexing. It probably would have been better to use UTF-8, and create an index array for the string when necessary.
You rarely need to index a string with an integer in Python. FOR loops don't need to. Regular expressions don't need to. Operations that return a position into the string could return an opaque type which acts as a string index. That type should support adding and subtracting integers (at least +1 and -1) by progressing through the string. That would take care of most of the use cases. Attempts to index a string with an int would generate index arrays internally. (Or, for short strings, just start at the beginning every time and count.)
Windows and Java have big problems. They really are 16-bit char based. It's not Java's fault; they standardized when Unicode was 16 bits.
- dietrichepp 10y agoThere are a couple cases for string indexing, usually involving parsing or regular expressions. You might want to slice the quotes off of a quoted string, or slice from one match of a regular expression to a match of a different regular expression starting at a different index. These come up infrequently enough that it doesn't make sense to make a better API just for these use cases, but frequently enough that it would be a serious impediment if we didn't do some kind of string indexing. I agree, however, that it's completely irrelevant whether the indexes correspond to code units (i.e. byte offsets in UTF-8) or whether they correspond to code points (how it works in Python currently), as long as we have some way to store, compare, and otherwise manipulate locations within a string. Some Rust developers at one point proposed making string indexes their own (opaque) type, as you suggest, so that they couldn't be confused with integers used for other purposes. The extra complexity of such an API meant that this proposal was never really taken seriously, and it only prevents a small category of programming errors. You might be interested in looking at some string APIs which are mostly without string indexing, like Haskell's Data.Text, which is one of the most well-designed string APIs ever made. https://hackage.haskell.org/package/text-1.2.2.1/docs/Data-Text.html https://hackage.haskell.org/package/text-1.2.2.1/docs/Data-T... As for Windows, my Windows apps use UTF-8 everywhere, and then convert to wchar_t at the last possible moment when interacting with the Windows API. I believe this is what UTF-8 Everywhere suggests.
- Avernar 10y ago> You might want to slice the quotes off of a quoted string That's why I really like dealing with UTF-8. As you said you can just index by byte instead of having to worry about code point boundries. This is because a code point will never match inside a larger code point. So if I search for a one byte quote character it will never match the second, third or fourth bytes in a larger code point. Same with other control characters. Works when searching for 2 or 3 byte code points as well.
- Animats 10y agoThe advantage of an opaque type is that you should be able to add one to it and advance one rune. Go copies the string functions from C, but doesn't (at least as of last year) offer "advance one rune" and "back up one rune" functions.
- Avernar 10y agoIf by rune you mean code point that doesn't really gain you anything. If you are searching for something it's faster to just scan a byte at a time. If you want to split the string into "characters" you need to do it a the grapheme level (multiple code points) and for that you need to use a unicode library. But that adds overhead when you're just scanning. A JSON or XML scanner does not need the added overhead of advancing by code point or grapheme.
- dietrichepp 10y agoI don't understand the argument for "characters = grapheme clusters". From my perspective, there are a lot of different ways you'd want to iterate over a string. Grapheme cluster breaks, tailored grapheme cluster breaks, word breaks, line breaks, code points, code units… all of these make sense in some context. However, there are precious few times that I've wanted to iterate over grapheme clusters, so telling people that they should do that instead of something else doesn't make sense to me. (I mean, what problem is so common that we would want to iterate this way by default?) For parsing, it often makes sense to iterate over code points or code units, since many languages are defined in terms of code points (and you can translate that to code units, for performance). XML 1.1, JavaScript, Haskell, etc... many languages are defined in terms of the underlying code points and their character classes in the Unicode standard. JSON and XML 1.0 are not everything.
- chubot 10y agoYeah, I didn't really understand this until I heard Go/Plan 9 guys ranting about this. In other words, char* IS unicode if you use utf-8. Otherwise you need wchar_t and all that junk. I think Python got unicode in the same era as Java, so it's understandable that Python 2 doesn't work like this. But if they are going to break the whole world for unicode, I also think it would have been better to do something like Go does (e.g. the rune library).
- nailer 10y agoI haven't done Python for a while, so maybe it's changed, but I thought the new Python 3 strings werre index by byte rather than character, and it was 'as designed' despite being very non-intuitive (unlike the rest of Python). Edit: see pjscott's comment below - it's by code point, not byte, but still not by character.
- Animats 10y agoNo, Python 3 indexes by character, not byte. $ python3 Python 3.4.3 (default, Oct 14 2015, 20:28:29) >>> s = "オンライン" >>> s 'オンライン' >>> len(s) 5 >>> s [0] 'オ' >>> s [1] 'ン' >>> s [2] 'ラ' >>> s[3] 'イ' >>> s[4] 'ン'
- pjscott 10y agoIt's important to be insufferably pedantic about this: they index by code point, which is almost but not quite what people expect a character to be. $ python3 >>> "위키백과"[1] '키' >>> "위키백과"[1] # Should be identical, right? 'ᅱ'
- kbenson 10y ago> It's important to be insufferably pedantic about this That is perhaps the most succinct and accurate way I've heard to explain and justify why you're sounding like a wet blanket to people that may not understand, while acknowledging that you know how you sound, but there is a reason for it. I expect to use this in the future.
- kazinator 10y agoSame with English, sort of. What is "difficult"[2]? Is it 'f'? Or the ligature `ffi`? :)
- schoen 10y agoThat's an awesome example! To show more of how it works for Western language speakers who might be confused, how about c = "é" c[0], c[1] It's the same phenomenon with Latin characters. (Extra bonus: for me, the combining acute accent character then combines in the terminal with the apostrophe that Python uses to delimit the string!) Another idea to see the effect is "a" + "é"[1]. (The result is 'á'... and as in your examples, a precomposed "̈́é" is also available which doesn't exhibit any of these phenomena.)
- johncolanduoni 10y agoI think it's even better to take this one step further and have your default "character" actually be a grapheme[1]. In almost any case where you're dealing with individual character boundaries you want to split things on the grapheme level, not the code-point level. This doesn't matter much for (normalized) western European text, but if the language in question needs to use separate diacritical code points you'll likely end up with hanging accents in the like. Swift is the only language I know of that has grapheme clusters as the default unit of character, I'd love to see it in more places. [1]: http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
- lelf 10y agoPerl6 does support them natively too.
- SwellJoe 10y agoPerl has historically had excellent Unicode support. I remember going from Perl to Python (like a decade ago), and being annoyed at how messy Unicode support still was. Ruby, too, lacked good Unicode support, for many years after Perl had it pretty good. But, Perl 6 definitely gets it more right than other implementations I've seen.
- MrBuddyCasino 10y agoNever understood that either. Why is this so rare? Even in technical discussions like this one, some people will look at you funny upon hearing this suggestion.
- jcranmer 10y agoNavigating a UTF-8 string on codepoint level is a fairly simple algorithm, since UTF-8 is self-synchronizing. This means it can easily be done without relying on external libraries or data files. It's also stable with respect to Unicode version--it always produces the same result independent of what version of the Unicode tables you use. Moving to grapheme cluster boundaries means that the algorithm may work incorrectly if you input a string of Unicode N+1 to an implementation that only supports Unicode N. It also makes the "increment character" function very complicated. In the UTF-8 version, this looks roughly like: char *advance(char *str) { uint8_t c = (uint8_t)*str; /* Count the number of leading 1's */ int num1s = __builtin_clz(~c) - 24; if (num1s == 0) return str + 1; return str + num1s; } Grapheme-based indexing looks like this: char *advance_grapheme(char *str) { while (true) { uint32_t codepoint = read_codepoint(str); str = advance(str); uint32_t nextCodepoint = read_codepoint(str); /* This is typically something like table[table2[codepoint >> 4] * 16 + codepoint & 15]; */ GraphemeClusterBreak left = lookupProp(codepoint); GraphemeClusterBreak right = lookupProp(nextCodepoint); /* Several rules based on left versus right... */ } return str; } See the vast difference in the two implementations? It's a lot of complexity, and it's worth asking if that complexity needs to be built into the main library (strings are a fundamental datatype in any language). It's also important to note that it's questionable whether such a feature implemented by default is going to actually fix naive programmers' code--if you read UTR #29 carefully, you'll notice that something like क्ष will consist of two grapheme clusters (क् and ष), which is arguably incorrect. Internationalization is often tied heavily to GUI and, especially for problems like grapheme clusters, it arguably makes more sense for toolkits to implement and deal with the problems themselves and provide things like "text input widget" primitives to programmers rather than encouraging users to try to implement it themselves.
- the_mitsuhiko 10y ago> The Python problem is amusing. Python 3 has three representations of strings internally (1-byte, 2-byte, and 4-byte) and promotes them to a wider form when necessary. This is mostly to support string indexing. It probably would have been better to use UTF-8, and create an index array for the string when necessary. It's especially amusing because on Python 3 strings internally cache their utf-8 equivalent if it was used once.
- Animats 10y agoI didn't know that. That's funny. They really are doing this the hard way.
- int_19h 10y agoIt really is the hard way. For the curious, read through the comment here describing the data layout and invariants: https://github.com/python/cpython/blob/master/Include/unicodeobject.h#L213 https://github.com/python/cpython/blob/master/Include/unicod...
- paulddraper 10y agoUsing raw bytes makes it possible to create corrupted strings. Slicing is not a safe operation. Python 3 doesn't have this issue.
- Avernar 10y agoIt's very easy to not get corrupted strings when byte indexing into UTF-8. In a while loop, if the index is not at the end of the string and the top two bits of the character at the index are both one, advance the index by one. Or throw an invalid index exception if the top to bits are one if that makes more sense for the language you're using.
- imron 10y agoIn a while loop, if the index is not at the end of the string and the top two bits of the character at the index are both one, advance the index by one. So what you're saying, is that it's very easy to get corrupted strings by anyone who doesn't have an understanding of utf-8 at the bit-level - which in my experience seems to be the majority of programmers.
- Avernar 10y agoNot at all. The language/library impementor should handle the details. My example was the argument checking of the slice function. And indexing by code points doesn't solve the problem either. The majority of programmers don't know what a grapheme is or how to collate or sort unicode strings.
- imron 10y agoExcept what happens in the real world is that people who are used to indexing and slicing ASCII strings however they please don't think "I should use a library for this", instead they just keep indexing and slicing as per usual and don't think anything of it until their Chinese customers start complaining of random program crashes, or missing text - which the developer then has difficulty trying to reproduce because hey, it works for them. My only gripe with your argument is that I don't think it's easy to avoid corrupted text in modern text processing - which is precisely why there are libraries for it because it's actually really easy to get it wrong - even if you know what you're doing.
- tracker1 10y agoLikewise, I wish JS had just changed the internal representation of strings to UTF8, and accepted that some older code might break instead of adding in the new string/regex bits. It would have made far more code simple start working with large/multibyte/international characters than it ever would have broken.
- 0x4a42 10y agoWouldn't it be possible by using a global switch (ie: see "use strict" as an example). You could just switch to the default character encoding without breaking existings js websites/apps?
- IndianAstronaut 10y agoSeems like ago handles this well with its utf 8 runes.