30 ms·
Key differences between Python 2.7.x and Python 3.x (2014)
- riazrizvi 10y ago> Python 2 has ASCII str() types, separate unicode(), but no byte type. Actually Py2's str class is a double-duty str/byte class such that some methods behave like str and others like byte. py2>> len('¡no') #string len=3 #encoded UTF-8 byte array len=4 4 #always gives bytes.len not str.len (see http://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface/34688434#34688434 http://stackoverflow.com/questions/5471158/typeerror-str-doe...)
- kzrdude 10y agoNo need to get too much into the meaning of the length of a str. It's neat to know the definition but neither choice gives you a good “string length” for real text. Case in point: len("é") == 2, so even with unicode strings we don't have length as a character count. As an english speaking person, I can clearly point at é and call it one character, but Python 2 or Python 3 doesn't agree. Rather, their str `len` doesn't agree with that, and that's fine. It's not a character count!
- dom0 10y agoThat one is maybe not the best example, since len(unicodedata.normalize('NFC', "é")) == 1 Though I don't know any "normal" character that requires composition ad-hoc that could serve as a better example.
- kzrdude 10y agoI think it's a fine example since the decomposed version clearly exists and can arrive as data into your program in a number of ways. That said, the grapheme cluster note will have examples of extended notions of characters that can't be represented by an equivalent single codepoint. There are some korean and indic examples and also emoji http://unicode.org/reports/tr29/ http://unicode.org/reports/tr29/ Oh and something that stirs the heart of us hackers: \r\n is a single grapheme!
- greglindahl 10y agoThis (different forms and no automatic normalization) is a "feature" of Unicode. It would be wrong of Python to try to cover it up.
- kzrdude 10y agoYes, so it's wrong for anyone to pretend len() or even indexing of a str is about characters, it's about codepoints of the string.
- wruza 10y agoIMO, len("") should raise OperationHasNoCommonSenseTodayException, just to not confuse unicode newbies. Modern text is not an array, it is a format, a complex format. Zero-width, double-width monotypes, combining, direction marks, normalization, etc. Almost no one wants to know about codepoint details when working with "just input strings", and those who want may use special namespaces for that. There is no point in making len() an alias for unicode.volatile_number_of_distinct_code_points(). visually_empty(s) is okay, len(s) is probably not.
- mrout 10y agoThey're all valid measurements. The length of a string could be measured in bytes (which doesn't require you to know the encoding), code points (which doesn't require huge Unicode grapheme clustering tables), grapheme clusters (which doesn't require a font) or even pixels (which does require a font).
- int_19h 10y agoThe best thing a language (or library) can do is to not bless any single one of these as the default. Strings shouldn't have a length at all. They should provide properties/methods/accessors like byte_count, codepoint_count, grapheme_count etc. Make the user of the API think every time they're asking for a length of the string - which one do they actually need? Which one is the best for whatever they're trying to do?
- user5994461 10y agoß é à ç ñ How about these?
- derefr 10y ago"Character count" (i.e. grapheme cluster count) only exists once you apply a font—because of ligature rules and some other stuff. Do you want your programming-language stdlib String class to require a font metrics library? (This isn't a rhetorical question; you can go either way. Objective C cares about grapheme clusters, and so needs to know about fonts.)
- mrout 10y agoI disagree. A grapheme cluster and a glyph are different things. The former is not dependent on the font. 'fi' is two grapheme clusters even if the font renders it as a single glyph. 'é' is a single grapheme cluster even if the font renders it as two glyphs: 'e ́'
- derefr 10y agoConsider the https://en.wikipedia.org/wiki/Regional_Indicator_Symbol https://en.wikipedia.org/wiki/Regional_Indicator_Symbol s. In every way that matters, these "act as" one 'character': you can't set your cursor position to be between them; backspacing one should delete both; the flag takes up one terminal col (even if it is rendered as two) such that "\033[1Dx" (cursor-left 1, print "x") will overwrite the whole flag, etc. But it's the font that controls those semantics—because it's the font that knows what flags do or do not exist. For any pair of RIS codepoints that doesn't form a flag (in the opinion of a given font), they behave like two separate characters. Thus: one grapheme cluster, or two, depending on the font. And another example—this one much less "idiomatic", but not specifically decried by the Unicode committee: http://kudakurage.com/ligature_symbols/ http://kudakurage.com/ligature_symbols/ That's a font, making entirely-arbitrary clusters out of codepoints. As far as I am aware, it's fully within its rights as a font to do so. There's nothing in the Unicode standard saying that the code-points ['f', 'i', 'l', 'e'], put in a row, can't combine to form a single grapheme cluster. They don't have combining behavior themselves, but—unlike, say, things in the Unicode "Separator" class—they don't have any property that says they don't combine with anything.
- mrout 10y ago
- Animats 10y agoPython 3's "bytes" type can't quite decide whether it's an array of small integers or a string. > a = bytes([97,98,99]) > print(a) b'abc' > a[0] 97 You can use regular expressions on a "bytes" object, as well as most of the string operations, such as ".center()" The "bytes" type in Python 3 still does double duty as an ASCII str/byte class.
- jjawssd 10y agoPython 3: In this case print(a) calls a.__str__() which happens to default to calling a.__repr__() because a doesn't have an __str__ attribute. a[0] is equivalent to a.__getitem__(0) That's because the __repr__ of a bytes object instance formats the result into a human readable representation of the data which should ideally be identical to the syntax needed to create the instance, whereas the __getitem__ method returns a "real" and machine usable representation. Try it... >>> a b'abc' >>> a.__str__() "b'abc'" >>> a.__repr__() "b'abc'" >>> a.__getitem__(0) 97
- minimaxir 10y agoHit an interesting issue when trying to make my urllib2 Python code behave the same way under both Python 2.7 and 3.6, which is fortunately documented: https://docs.python.org/2/library/urllib2.html https://docs.python.org/2/library/urllib2.html > Note: The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3. The best-but-silly solution I found without introducing a dependency was: try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request
- orf 10y agoUse six for this. They provide stable import paths for stdlib modules that have moved. > from six.moves import urllib
- murtnowski 10y agoWhy is this still a thing?
- thomastjeffery 10y agoLibraries and pypy.
- BuckRogers 10y agoThis has ruined Python for me. Gone on far too long and Python3 ended up being technical churn anyway rather than technical innovation. Not worth the break. I ended up replacing Python.
- Mizza 10y agoBut where did you go? I've been dragged kicking and screaming into Python 3, (which I still hate), but I don't see any higher ground to swim too.
- dheera 10y agoCurious, what do you hate about Python 3, or is it just hating the migration process? (As someone who has to deal with a lot of Unicode content, I consider Python 3 a blessing, but curious.)
- convolvatron 10y agoi dont do a lot of python, and i think 3 is an improvement but for me the real nightmare is all of the libraries. some have 2 and 3 support, some only 2, some with a 3 fork thats not maintained, etc etc. every time i try to start a project using 3 i end up wasting a lot of time and going back to 2 anyways
- 52-6F-62 10y agoThis is my major confusion as well. It seems not worth it to begin work in an older version because debt is inherent right at the start, and updating code (for a new language version) is a personal peeve (or irritant). It's irrational, so don't ask, but I avoid it everywhere I can. Of course, diving into the newer version also adds a lot of debt, and possibly a total impasse, due to the lack of libraries that have made the update. I guess it will be quite some time before it becomes foolish to still cling to py2
- cthalupa 10y ago
- pmoriarty 10y agoWhy hasn't the Python community moved on to Python 3 yet?
- jjawssd 10y agoMost of it has, and it is good to document upgrade pathways for 2 to 3 migrations. Some of those migrations require 2 and 3 compatible code. I also highly recommend using the six library.
- bedros 10y agoI'm using Django 1.8 first with Python 2.7 then migrated the code to 3.4 with no problems
- wolf550e 10y agoYou can migrate to Django 1.11, it's also LTS like 1.8.
- sprash 10y agoBecause it is a serious regression.
- yzmtf2008 10y agoThat's an opinion, not a fact.
- sprash 10y agoPerformance can be measured. The rest is indeed opinion. The opinion of the python community after almost 10 (!) years after after the first release is quiet obvious: 3.x sucks! I just don't know from where all the 3.x apologist appear as soon as there is a discussion. There always appears to be an inherent need to somehow defend this complete failure.
- rckclmbr 10y ago
- elnygren 10y agoPython3 is a totally different beast nowadays from Python2. The reason is async/await. It can handle Node.js style event loop / asynchronous code very well -- with uvloop, python 3.5+ is actually faster than Node.js (close to Go). https://magic.io/blog/uvloop-blazing-fast-python-networking/ https://magic.io/blog/uvloop-blazing-fast-python-networking/ IMHO: after 3.5, we are clearly in the next iteration of the language.
- deleted 10y ago[deleted]
- kccqzy 10y agoI haven't written Python in a few years, and recently when I needed to read some Python code thinking it would be familiar, I am completely unprepared to see async/await peppered everywhere. It is indeed a big change.
- deleted 10y ago[deleted]
- omginternets 10y ago>is actually faster than Node.js Uhhh I call BS until proven otherwise. Maybe the event loop is faster, but I'm willing to bet the callback code is slower.
- nicoburns 10y ago> Maybe the event loop is faster, but I'm willing to bet the callback code is slower. This is exactly the case, and the slowdown is pretty noticeable IMO. Still, python 3 is a whole lot better at this than python 2.
- xapata 10y agoDepends on many things. What task are you trying to accomplish?
- omginternets 10y ago
- mnm1 10y ago"I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use." I would like to consider python for my next project, but this is extremely short sighted advice which begs the very real question: why should I consider python at all for a new, multi year project when there is no clear path forward for the language and there hasn't been in a decade? Also, how can you ask someone who is new to the language to just choose? To me that seems insane. They have nothing to base their choice on, yet this choice will decide the future and success of the app. No pressure. But to be honest, and I know this is not the community's intention, the python 2/3 split is about as unwelcome a reception to a programming language as I can imagine. Is there a more logical way to choose? Finally, I've now seen clients demand rewrites of python 2 code because of (probably bullshit) concerns around its obsolescence and lack of security. Now these clients generally don't know python from their ass and I doubt they have valid technical concerns but as invalid as their concerns probably are, it's still a major issue of your big clients threaten to leave unless you rewrite all your python 2 to 3. Anyone faced this?
- SmirkingRevenge 10y agoThe link appears to be a few years old now, so its advice here I think is a bit out of date. And some might argue it would have been out of date in 2014 as well. It should probably be updated to say that unless you have a VERY strong reason to use 2.7, use 3. And even then, probably still use 3, because your reasons probably aren't as strong as you think they are. EDIT: Generally the strong reasons most people had for using py2.7 for new projects were some variant of: "X, Y and Z libraries I need only support 2.7". But now and days, that actually stands as more of a reason to find alternate libraries.
- Animats 10y agoThe last two things I have on Python 2 are: - code that has to run on HostGator shared hosting. They only support Python 3.2, the "maximally incompatible" version. - code that has to run on ROS, the Robot Operating System. ROS is a huge collection of packages from various sources glued together by a message passing system. Efforts to convert all those packages to run under Python 3 have been underway for years, but aren't done yet.
- lvh 10y ago> Python 2 has ASCII str() types, separate unicode(), but no byte type. This is incorrect in at least two ways: - Python 2.7.x str is _not_ ASCII! "\xff" is totally valid, but not a valid ASCII string. - Python 2.7.x has bytearray.
- kortex 10y ago> I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. No. 3.x is right, unless you have a darn good reason. Darn good reasons: 1. A library or legacy codebase is in 2.x, or a system will only support it, and it is impractical to refactor to 3.x 2. You are being paid to specifically write in 2.x. Often, this is because of reason 1. It's pretty simple, really.
- redsymbol 10y agoTo people whining "why hasn't Python's community moved to 3 yet": It has. I teach online advanced-Python programming workshops every month. The audience of each is 50-100 working developers from around the world, every one of whom use Python in their day-to-day work. I start each class by polling who's using Python 2 vs. Python 3. A year ago, about 20% said they use Python 3, 80% Python 2. In the last 2 months, it's consistently 60%-70% Python 3. Python's community has already plowed through the sigmoidal inflection point to 3; most just don't realize it. The linked article is years old.
- Radim 10y ago"I teach online advanced-Python programming workshops every month... In the last 2 months, it's consistently 60%-70% Python 3." So you're basing your conclusion on a sample of two? :) I teach advanced Python (and machine learning) courses too, albeit in corporate settings (groups of ~15, rather than 100), and it's still very much <20% for Python 3 there.
- redsymbol 10y agoPoorly worded. I taught 4 classes in March and 4 in April, over 500 unique engineers total (some were in more than 1 class). There's definitely going to be pockets of resistance. My attendees are a very wide-spectrum sample from many different companies and industries and even countries, so I have some faith in the trend that's showing up. Could be that there's some bias in my students for sure. Regardless, the ratio I've been seeing has been steadily increasing month after month since late last year.
- nnd 10y ago>>> round(15.5) 16.0 >>> round(16.5) 16.0 I wonder what's the logic behind this.
- matt_wulfeck 10y agoThe likelihood of the current 2.x codebase being ported to 3.x is lower than new code being written in a new language. It will be ported to a new language, such as Golang. The vast majority of Python developers will only be writing and maintaining Python 2 code, because the vast majority of Python code is 2.x and will never migrate.
- thehardsphere 10y agoHow on Earth does it make more sense to re-write an entire working program in an entirely new language than it does to simply update from Python 2.7 to Python 3? I mean, if the complaint is that it's too hard to make set of specific changes to a Python 2 program to make it a Python 3 program, how is it going to be easier to re-write in a new language when that's going to be a significantly more difficult project?
- matt_wulfeck 10y agoBecause no sane person wants to do the investment unless is provided material benefits. 2->3 provides no such material benefits, which is why they're being so aggressive about EOL timetables.
- thehardsphere 10y ago1. 10 years is not aggressive for an EOL timetable. 2. What is the material benefit to rewriting the whole thing from scratch in any language, just to get around an EOL timetable?
- Double_a_92 10y agoThe print command needs brackets. :^)