python-2.x

Why is Python 3 (or later) better than Python 2?

别来无恙 提交于 2019-12-09 16:11:45
问题 I learned Python as my first serious (non BASIC) language about 10 years ago. Since then, I have learned lots of others, but I tend to 'think' in Python. When I look at the list of changes I do not see one I need this feature. I usually say to myself, hmm that would been a good way of doing it, but why change it now? Things like changing the default floor division could be a real pain to change for big projects. It seems like the major players are dragging their feet. What is the key feature

Convert PILLOW image into StringIO

折月煮酒 提交于 2019-12-09 05:39:41
问题 I'm writing a program which can receive images in a variety of common image formats but needs to examine them all in one consistent format. It doesn't really matter what image format, mainly just that all of them are the same. Since I need to convert the image format and then continue working with the image, I don't want to save it to disk; just convert it and continue on. Here's my attempt using StringIO: image = Image.open(cStringIO.StringIO(raw_image)).convert("RGB") cimage = cStringIO

What does the “variable //= a value” syntax mean in Python? [duplicate]

自作多情 提交于 2019-12-08 17:00:14
问题 This question already has answers here : What does //= in python do? [duplicate] (3 answers) Closed 3 years ago . I came across with the code syntax d //= 2 where d is a variable. This is not a part of any loop, I don't quite get the expression. Can anybody enlighten me please? 回答1: // is a floor division operator. The = beside it means to operate on the variable "in-place". It's similar to the += and *= operators, if you've seen those before, except for this is with division. Suppose I have

How to detect Python Version 2 or 3 in script?

别等时光非礼了梦想. 提交于 2019-12-08 16:23:00
问题 I've written some scripts, which run either only with Version 2.x or some only with Version 3.x of Python. How can I detect inside the script, if it's started with fitting Python Version? Is there a command like: major, minor = getPythonVersion() 回答1: sys.version_info provides the version of the used Python interpreter: >>> import sys >>> sys.version_info sys.version_info(major=2, minor=7, micro=6, releaselevel='final', serial=0) >>> sys.version_info[0] 2 For details see https://docs.python

Putting two keys with the same hash into a dict

喜夏-厌秋 提交于 2019-12-08 15:02:37
问题 >>> one_decimal = Decimal('1') >>> one_complex = complex(1,0) >>> d = {one_decimal: '1D', one_complex: '1C'} >>> len(d) 2 >>> map(hash, d) [1, 1] Above, I create a dict with a hash collision, and two slots occupied. >>> d[1] '1D' >>> d[1+0j] '1C' How is that getitem handled for the integer 1 ? And how does the indexing manage to resolve the correct value for a complex literal indexing? Python 2.7.12 / Linux. 回答1: As the accepted answer mentioned by @CoryKramer states, equality of hashes does

How to test exceptions with doctest in Python 2.x and 3.x?

一笑奈何 提交于 2019-12-08 15:00:34
问题 I defined an exception class SpamException in a module spam . Now I want to test a function spam_function , that raises this exception. So I wrote the following doctest. >>> spam_function() Traceback (most recent call last): .... SpamException The test succeeds on Python 2.x, but on Python 3.x the test fails. The following test works on Python 3.x. >>> spam_function() Traceback (most recent call last): .... spam.SpamException The notable difference here is the inclusion of the module name in

How to write exception reraising code that's compatible with both Python 2 and Python 3?

こ雲淡風輕ζ 提交于 2019-12-08 14:28:41
问题 I'm trying to make my WSGI server implementation compatible with both Python 2 and Python 3. I had this code: def start_response(status, response_headers, exc_info = None): if exc_info: try: if headers_sent: # Re-raise original exception if headers sent. raise exc_info[0], exc_info[1], exc_info[2] finally: # Avoid dangling circular ref. exc_info = None elif headers_set: raise AssertionError("Headers already set!") headers_set[:] = [status, response_headers] return write ...with the relevant

Logical mistake in this code?

白昼怎懂夜的黑 提交于 2019-12-08 12:18:07
问题 The code is simple and you will be able to tell what it does once you see it. n = int(input()) if(n%2!=0): print 'Weird' elif(n%2==0): if(n>=2 & n<=5): print 'Not Weird' elif(n>=6 & n<=20): print 'Weird' elif(n>20): print 'Not Weird' It works fine, but it shows errors for 2 cases only. When input is 18 , its says 'Not Weird' whereas the output should be 'Weird' . The same thing is happening when the input is 20 . Its probably a silly mistake or something but I just can't seem to put my finger

binary search implementation with python

Deadly 提交于 2019-12-08 07:33:59
问题 I think I did everything correctly, but the base case return None, instead of False if the value does not exists. I cannot understand why. def binary_search(lst, value): if len(lst) == 1: return lst[0] == value mid = len(lst)/2 if lst[mid] < value: binary_search(lst[:mid], value) elif lst[mid] > value: binary_search(lst[mid+1:], value) else: return True print binary_search([1,2,4,5], 15) 回答1: You need to return the result of the recursive method invocation: def binary_search(lst, value):

How to use the __subclasscheck__ magic method?

╄→гoц情女王★ 提交于 2019-12-08 06:05:18
问题 How can we make a class who lies about who he has subclassed? After reading the doc I've attempted this: >>> class AllYourBase(type): ... @classmethod ... def __subclasscheck__(cls, other): ... return True ... >>> class AllYour(object): ... __metaclass__ = AllYourBase Now, this class should report that all your base are belong to him. But it didn't work: >>> issubclass(AllYour, int) False Why not? 回答1: If you want AllYour to claim to be a subclass of every class, that isn't possible. _