python-2.x

How do I properly override __setattr__ and __getattribute__ on new-style classes in Python?

那年仲夏 提交于 2019-11-28 19:07:51
I want to override my Python class's __getattribute__ and __setattr__ methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For __getattribute__ , it seems that I can request the default behavior simply by raising AttributeError . However, how can I achieve the same in __setattr__ ? Here is a trivial example, implementing a class with immutable fields "A", "B", and "C". class ABCImmutable(SomeSuperclass): def __getattribute__(self, name): if name in ("A", "B", "C"): return "Immutable value of %s" % name else:

How can I denote unused function arguments?

梦想的初衷 提交于 2019-11-28 18:31:52
When "deconstructing" a tuple, I can use _ to denote tuple elements I'm not interested in, e.g. >>> a,_,_ = (1,2,3) >>> a 1 Using Python 2.x, how can I express the same with function arguments? I tried to use underscores: >>> def f(a,_,_): return a ... File "<stdin>", line 1 SyntaxError: duplicate argument '_' in function definition I also tried to just omit the argument altogether: >>> def f(a,,): return a File "<stdin>", line 1 def f(a,,): return a ^ SyntaxError: invalid syntax Is there another way to achieve the same? Here's what I do with unused arguments: def f(a, *unused): return a A

StringIO and compatibility with 'with' statement (context manager)

核能气质少年 提交于 2019-11-28 18:28:09
问题 I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below. What I want to do is not have to write to disk with some content that I generate in order to use this legacy function, so I though I could use StringIO to create an object in place of the physical filename. However, this does not work, as you can see below. I thought StringIO was the way to go with this. Can anyone tell me if there is a

TypeError: super() takes at least 1 argument (0 given) error is specific to any python version?

穿精又带淫゛_ 提交于 2019-11-28 18:08:39
I'm getting this error TypeError: super() takes at least 1 argument (0 given) using this code on python2.7.11: class Foo(object): def __init__(self): pass class Bar(Foo): def __init__(self): super().__init__() Bar() The workaround to make it work would be: class Foo(object): def __init__(self): pass class Bar(Foo): def __init__(self): super(Bar, self).__init__() Bar() It seems the syntax is specific to python 3. So, what's the best way to provide compatible code between 2.x and 3.x and avoiding this error happening? Yes, the 0-argument syntax is specific to Python 3, see What's New in Python 3

What is `1..__truediv__` ? Does Python have a .. (“dot dot”) notation syntax?

走远了吗. 提交于 2019-11-28 14:58:02
问题 I recently came across a syntax I never seen before when I learned python nor in most tutorials, the .. notation, it looks something like this: f = 1..__truediv__ # or 1..__div__ for python 2 print(f(8)) # prints 0.125 I figured it was exactly the same as (except it's longer, of course): f = lambda x: (1).__truediv__(x) print(f(8)) # prints 0.125 or 1//8 But my questions are: How can it do that? What does it actually mean with the two dots? How can you use it in a more complex statement (if

I am attempting to print only a selected amount of Pi, it returns with an error of \"Decimal has no attribute: __getitem__

被刻印的时光 ゝ 提交于 2019-11-28 14:53:04
def pi(): prompt=">>> " print "\nWARNING: Pi may take some time to be calculated and may not always be correct beyond 100 digits." print "\nShow Pi to what digit?" n=raw_input(prompt) from decimal import Decimal, localcontext with localcontext() as ctx: ctx.prec = 10000 pi = Decimal(0) for k in range(350): pi += (Decimal(4)/(Decimal(8)*k+1) - Decimal(2)/(Decimal(8)*k+4) - Decimal(1)/(Decimal(8)*k+5) - Decimal(1)/(Decimal(8)*k+6)) / Decimal(16)**k print pi[:int(n)] pi() Traceback (most recent call last): File "/Users/patrickcook/Documents/Pi", line 13, in <module> pi() File "/Users/patrickcook

Why can't I use yield with return?

北城余情 提交于 2019-11-28 14:15:41
问题 I would like you to consider the following code: def func(alist): if len(alist) == 1: return arg * 2 for item in alist: yield item * 2 When I run it, I get this error: SyntaxError: 'return' with argument inside generator Now, I realize that I cannot do this. However, I would like to know why. What exactly is going on behind the scenes that is causing Python to throw the SyntaxError ? 回答1: Python has to decide whether a function is a generator at bytecode compilation time. This is because the

True=False assignment in Python 2.x [duplicate]

断了今生、忘了曾经 提交于 2019-11-28 13:19:27
Possible Duplicate: Why can’t Python handle true/false values as I expect? Seems a stupid question, but why is the following statement in Python not explicitly forbidden? >> True=False >> True False How is True and False handled by Python interpreter? True , just like str or any other builtin, is just a name that exists in the scope by default. You can rebind it like any other such name. Python actually has very few reserved words . All the rest are subject to redefinition. It's up to you to be careful! >>> True = False False In the above assignment, True is just a variable like any other

Something wrong with scikits.talkbox with Python3?

ⅰ亾dé卋堺 提交于 2019-11-28 12:39:15
问题 I am migrating a Python program from 2.10 to 3.6. The packages scikits.talkbox is part of it. However, I cannot figure out how to use it any more. The installation from pip seems to work fine but I cannot import it. Has anyone faced this problem before ? [manjaro@manjaro-pc ~]$ python --version Python 3.6.0 [manjaro@manjaro-pc ~]$ sudo pip install scikits.talkbox Collecting scikits.talkbox Using cached scikits.talkbox-0.2.5.tar.gz Requirement already satisfied: numpy in /usr/lib/python3.6

Getting a Python function to cleanly return a scalar or list, depending on number of arguments

走远了吗. 提交于 2019-11-28 12:33:34
Disclaimer: I'm looking for a Python 2.6 solution, if there is one. I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values: >>> a = foo(1) 2 >>> b, c = foo(2, 5) >>> b 3 >>> c 6 To be clear, this is in an effort to make some function calls simply look nicer than: a, = foo(1) or a = foo(1)[0] Right now, the inelegant solution is something along these lines: def foo(*args): results = [a + 1 for a in args] return results if len(results) > 1 else results[0] Is there any syntactic sugar (or functions) that would make