python-2.x

Python object cache

…衆ロ難τιáo~ 提交于 2019-11-29 05:14:10
I tried a bit of code but it seems to cause issues: class Page: cache = [] """ Return cached object """ def __getCache(self, title): for o in Page.cache: if o.__searchTerm == title or o.title == title: return o return None """ Initilize the class and start processing """ def __init__(self, title, api=None): o = self.__getCache(title) if o: self = o return Page.cache.append(self) # Other init code self.__searchTerm = title self.title = self.someFunction(title) Then I try: a = Page('test') b = Page('test') print a.title # works print b.title # AttributeError: Page instance has no attribute

Why does id() of an unbound method in Python 2 change for every access

这一生的挚爱 提交于 2019-11-29 04:17:55
Python 2.6.5 (r265:79063, Oct 1 2012, 22:07:21) [GCC 4.4.3] >>> class myclass: ... def func(self): ... pass >>> dd = myclass.func >>> ee = myclass.func >>> cc = myclass.func >>> ff = myclass.func >>> ss = myclass.func >>> uu = myclass.func >>> pp = myclass.func >>> >>> >>> id(dd) ; id(cc) ; id(ee) ; id(ff) ; id(ss) ; id(uu) ; id(pp) 3074535252L 3074534772L 3074522444L 3074531732L 3074497588L 3073003604L 3073003724L Why is the ID of the unbound method different each time? Shouldn't it be same ? This is because the methods on a class (old or new) work really like attributes with the descriptor _

isinstance() and issubclass() return conflicting results

做~自己de王妃 提交于 2019-11-29 03:02:57
>>> class Hello: pass and >>> isinstance(Hello,object) True >>> issubclass(Hello,object) False >>> a = Hello() >>> isinstance(a,object) True How do you explain isinstance(Hello,object) returns True whilst issubclass(Hello,object) returns False It's because you are using old-style classes so it doesn't derive from object . Try this instead: class Hello(object): pass >>> issubclass(Hello,object) True Old-style classes are deprecated and you shouldn't use them any more. In Python 3.x all classes are new-style and writing (object) is no longer required. The accepted answer is correct, but seems to

Making io.BufferedReader from sys.stdin in Python2

南楼画角 提交于 2019-11-29 03:02:47
How can I make a BufferedReader object from a standard file object, like sys.stdin or what you get from 'open'? (Background: I need a peek() method, which the standard file objects fail at having. Any suggestions to solve this issue are also welcome.) I'd have sort of expected this to work, but it doesn't: >>> import sys >>> import io >>> io.BufferedReader(sys.stdin) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'file' object has no attribute 'readable' (This is Python 2.7) Hah, got it, at least for anything that has a file descriptor. stream = sys

Performance: Python 3.x vs Python 2.x [closed]

梦想的初衷 提交于 2019-11-29 01:54:51
问题 Closed . This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 4 years ago . On a question of just performance, how does Python 3 compare to Python 2.x? 回答1: 3.0 is slower than 2.5 on official benchmarks. From "What’s New in Python 3.0": The net result of the 3.0 generalizations is that Python 3.0 runs the pystone benchmark around 10% slower than Python 2

Are there dictionary comprehensions in Python? (Problem with function returning dict)

不想你离开。 提交于 2019-11-29 01:51:18
问题 I know about list comprehensions, what about dictionary comprehensions? Expected Output: >>> countChar('google') {'e': 1, 'g': 2, 'l': 1, 'o': 2} >>> countLetters('apple') {'a': 1, 'e': 1, 'l': 1, 'p': 2} >>> countLetters('') {} Code (I'm a beginner): def countChar(word): l = [] #get a list from word for c in word: l.append(c) sortedList = sorted(l) uniqueSet = set(sortedList) return {item:word.count(item) for item in uniqueSet } What is the problem with this code? Why do I get this

An equivalent to string.ascii_letters for unicode strings in python 2.x?

泄露秘密 提交于 2019-11-29 01:42:53
In the "string" module of the standard library, string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase is 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' Is there a similar constant which would include everything that is considered a letter in unicode? You can construct your own constant of Unicode upper and lower case letters with: import unicodedata as ud all_unicode = ''.join(unichr(i) for i in xrange(65536)) unicode_letters = ''.join(c for c in all_unicode if ud.category(c)=='Lu' or ud.category(c)=='Ll') This makes a string 2153 characters long (narrow

Check for mutability in Python?

不问归期 提交于 2019-11-29 01:39:03
问题 Consider this code: a = {...} # a is an dict with arbitrary contents b = a.copy() What role does mutability play in the keys and values of the dicts? How do I ensure changes to keys or values of one dict are not reflected in the other? How does this relate to the hashable constraint of the dict keys? Are there any differences in behaviour between Python 2.x and Python 3.x? How do I check if a type is mutable in Python? 回答1: 1) Keys must not be mutable, unless you have a user-defined class

Correctly extract Emojis from a Unicode string

百般思念 提交于 2019-11-28 23:10:07
I am working in Python 2 and I have a string containing emojis as well as other unicode characters. I need to convert it to a list where each entry in the list is a single character/emoji. x = u'😘😘xyz😊😊' char_list = [c for c in x] The desired output is: ['😘', '😘', 'x', 'y', 'z', '😊', '😊'] The actual output is: [u'\ud83d', u'\ude18', u'\ud83d', u'\ude18', u'x', u'y', u'z', u'\ud83d', u'\ude0a', u'\ud83d', u'\ude0a'] How can I achieve the desired output? ivan_pozdeev First of all, in Python2, you need to use Unicode strings ( u'<...>' ) for Unicode characters to be seen as Unicode characters.

Unicode literals that work in python 3 and 2

空扰寡人 提交于 2019-11-28 22:11:04
问题 So I have a python script that I'd prefer worked on python 3.2 and 2.7 just for convenience. Is there a way to have unicode literals that work in both? E.g. #coding: utf-8 whatever = 'שלום' The above code would require a unicode string in python 2.x ( u'' ) and in python 3.x that little u causes a syntax error. 回答1: Edit - Since Python 3.3, the u'' literal works again, so the u() function isn't needed. The best option is to make a method that creates unicode objects from string objects in