IndexError: list index out of range

2016-12-12 Thread Elnaz
hi
i am begginer in python. I have written a code and given this error:
IndexError: list index out of range

In my program, I have h=32 bits input. i divide this 32 bits to 4*8 block and 
every 8-block is n. so n=0:7;(h=int(n/4))
I want to rotate 0 to 7 bits for 2 bits: 0,1,2,3,4,5,6,7--->2,3,4,5,6,7
Iwrite this code:
def rottwo(self, X, n, r):
assert r >= 1
temp = [None]*n
for i in range(n-r) :
temp[i] = X[i+r]
for i in range(n-r,n) :
temp[i] = X[i-n+r]
return temp
this function work correctly. but I also want to rotate 24 to 31 bits for 5 
bits: 24,25,26,27,28,29,30,31-->29,30,31,24,25,26,27,28

when I write this code:
def rotfive(self, X, n, r):
   assert r >= 1
   temp = [None]*n
   for i in range(n-r) :
temp[i+24] = X[i+3*n+r]
   for i in range(n-r,n) :
temp[i+24] = X[i+2*n+r]
   return temp 
beacase temp is of size n I cannot access index 3*n+i. index on the list temp 
should be less than equal to n-1 . 
I son't know how I must correct this
Is there any one to help me?
thanks in advanse.
-- 
https://mail.python.org/mailman/listinfo/python-list


Nested functions, how do they work (stack related)

2016-12-12 Thread Veek M
I was reading the wiki on 'Call stack' because I wanted to understand 
what a traceback object was. My C/C++ isn't good enough to deal with raw 
python source since I have no background in CS. Also, you just can't 
dive into the python src - it takes a good deal of reading and 
background.. (the types will be confusing for a start)

https://en.wikipedia.org/wiki/Call_stack

'Programming languages that support nested subroutines also have a field 
in the call frame that points to the stack frame of the latest 
activation of the procedure that most closely encapsulates the callee, 
i.e. the immediate scope of the callee. This is called an access link or 
static link (as it keeps track of static nesting during dynamic and 
recursive calls) and provides the routine (as well as any other routines 
it may invoke) access to the local data of its encapsulating routines at 
every nesting level. 

Some architectures, compilers, or optimization cases store one link for 
each enclosing level (not just the immediately enclosing), so that 
deeply nested routines that access shallow data do not have to traverse 
several links; this strategy is often called a "display".'

1. What is the difference between a 'call frame' and a 'stack frame' in 
the above context? I know that a stack frame is all the data related to 
one - CALL foo; 

2. He's saying that within the 'call frame' (whatever that is) there's 
an address to one of the previous stack frames of the wrapper function ? 
What does all that mean in terms of nested functions? Access link? How 
are nested function stacks setup..

3. What exactly is a traceback object - we know that an instance object 
is a dictionary and some glue logic that allows you to pretend that 
methods are stored within the instance and call using x.sin(self) etc.
But I was reading: pydoc traceback AND:
http://effbot.org/librarybook/traceback.htm

'Extract the raw traceback from the current stack frame'
A stack frame contains (from wiki) the parameters, local variables, next 
instruction address so.. what's a raw traceback - does the default 
exception handler realize 'okay error' and then walk the stack and 
extract data and prettify it for display and build a magical traceback 
object? Is this documented for dummies what exactly it does?
(i know that's what it's doing but I HAVE NO CLUE so.. are there books 
on this)

How exactly does an exception fit in with tracebacks? How does all this 
fit in with nested functions? 

4. When you call a nested function (decorator), it generally returns a 
wrapper function but I thought he was just returning a reference to a 
function object but obviously since it can see it's environment, how is 
the stack being setup?


-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Method to know if object support being weakreferenced ?

2016-12-12 Thread Gregory Ewing

Matthias Bussonnier wrote:

I search for a method
capable of telling me whether an object can be weakreferenced.


Objects that can be weakly referenced have a __weakref__ attribute.
So you could use hasattr(obj, '__weakref__').

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Gregory Ewing

Ned Batchelder wrote:

if a C++ constructor raises an exception, will the corresponding destructor
be run, or not? (No, because it never finished making an object of type T.)


So it just leaks any memory that's been allocated by
the partially-run constructor?

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Chris Angelico
On Tue, Dec 13, 2016 at 4:45 PM, Steven D'Aprano
 wrote:
> I don't understand the point of bringing up Javascript. Ben has already said
> that we shouldn't feel the need to mindlessly copy C++ terminology. Is it your
> position that we *should* copy Javascript terminology? Why Javascript and not
> C++ or ObjectiveC? Even when it goes against the obvious English mnemonic?

I'm saying that ALL these terminology debates are needlessly pedantic.
Whatever word you use, you're going to have to explain the Python
semantics as distinct from everyone else's, so don't sweat it. Whether
we call __init__ the constructor or initializer, there is going to be
someone out there who misinterprets it. Go with whatever, pick the
easiest to explain (which is probably "__new__ is allocator, __init__
is initializer"), and don't try to burden the terms alone with the job
of explaining Python's semantics.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Method to know if object support being weakreferenced ?

2016-12-12 Thread Steven D'Aprano
On Tuesday 13 December 2016 15:57, Matthias Bussonnier wrote:

[...]
> I could of course write a function that try/except and return False/True
> depending on the result, but that seem suboptimal as how can I know that the
> TypeError does come from not being able to take a weak reference ? And not
> from something else ?

Do you mean something like this?

try:
proxy = weakref.proxy(obj)
except TypeError:
proxy = None


Where else could it come from?

> The common Idiom in CPython, at the C layer seem to be
> PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob)). So I can (and did) write a C-extension
> that expose such a function, but it does seem silly that no one else did that
> before me, and that no one seemed to have encountered the problem before.
> 
> So am I missing something ? Is such a function not useful ?  Is there any
> reason not to have it in the stdlib ?

You could try raising a feature request on the bug tracker.



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Steven D'Aprano
On Tuesday 13 December 2016 10:23, Chris Angelico wrote:

> On Tue, Dec 13, 2016 at 10:17 AM, Ben Finney 
> wrote:
>> If the differences didn't matter I would agree that “overly pedantic” is
>> fair. But those differences trip up newcomers. Thinking of
>> ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
>> from – am I not meant to be constructing it? — and to attempt to return
>> that instance. And when the time comes to lean about ‘__new__’ the
>> confusion continues, because the newcomer has been told that something
>> *else* is the constructor, so what's this?
> 
> In JavaScript, it's normal to talk about "calling a function as a
> constructor". When you do, there is a 'this' object before you start.
> Should we tell the JavaScript folks to be more pedantic, because
> 'this' should end up existing? 

You've ignored Ben's critical point that if we call __init__ the "constructor", 
what do we call __new__? (Perhaps we should call __new__ the "initialiser" for 
maximum confusion.)

I don't understand the point of bringing up Javascript. Ben has already said 
that we shouldn't feel the need to mindlessly copy C++ terminology. Is it your 
position that we *should* copy Javascript terminology? Why Javascript and not 
C++ or ObjectiveC? Even when it goes against the obvious English mnemonic?

__init__ is the INITialiser (it initialises an existing instance);

__new__ creates/constructs a NEW instance


> Does it really even matter when memory
> gets allocated and the object's identity assigned? 

Actually, yes it does. Try constructing an immutable object like a subclass of 
float, str or int from the __init__ method. Attaching attributes to the 
instance doesn't count.


class PositiveInt(int):
def __init__(self, arg):
arg = abs(arg)
return super().__init__(self, arg)


So much fail...



> Before __init__
> gets called, the object isn't "truly there" - its fundamental
> invariants may not yet have been established, and key attributes might
> not have been set up.

"Fundamental invariants" is tricky though -- are they *truly* fundamental? This 
is Python -- I can easily make a Python-based class that lacks the attributes 
that its methods assume will be there, or delete them after creation.

But there is one thing which truly is fundamental: the instance creation, the 
moment that object.__new__ returns a new instance. Before calling that, the 
instance genuinely doesn't exist; after object.__new__ returns, it genuinely 
does. (Even if it isn't fully initialised.)

Unlike __init__, object.__new__ is atomic: it either succeeds, or it doesn't. 
So object.__new__ really is the constructor of instances, and so following 
standard practice, MyClass.__new__ which inherits from object ought to be 
called the same thing. (Even if it is no longer atomic, due to being written in 
Python.)


> Once __init__ finishes, there is an expectation
> that attributes and invariants are sorted out.
> 
> This is like the old "Python doesn't have variables" thing.
> Ultimately, every language has slightly different semantics (otherwise
> they'd be trivial transformations, like Ook and Brainf*), so you have
> to learn that the "constructor" might have slightly different
> semantics. Accept it - embrace it. Learn it.

We're not debating what other languages should call __new__ and __init__ or 
whatever their equivalents are. We're debating what Python should call them.

For some prior art, consider ObjectiveC. To create a new instance of a class, 
you call:

[[MyClass alloc] init]

where alloc is the "allocator" (it basically just allocates memory, and very 
little else) and init is the "initialiser" (because it initialises the newly 
created instance.

In more modern versions of ObjectiveC, there's a short-cut:

[MyClass new]

where new calls alloc then init for you.

In Ruby, people think of two distinct things as the "constructor", depending on 
what you are doing. [Source: my resident Ruby expert at work.] If you are 
talking about *writing* a class, the constructor is the initialize method:

class MyClass
def initialize
...
end
end

But if you are talking about *creating an instance* it is the new method:

MyClass.new

which itself automatically calls initialize behind the scenes. (I'm told that 
it is possible to override new, but nobody does it.)


It seems to me that both of these are quite similar to Python's model.



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Steven D'Aprano
On Tuesday 13 December 2016 12:12, Ned Batchelder wrote:

> On Monday, December 12, 2016 at 6:17:43 PM UTC-5, Ben Finney wrote:
>> Ned Batchelder  writes:
>> 
>> > Claiming that __init__ isn't a constructor seems overly pedantic to
>> > me.
>> 
>> Whereas to me, claiming that ‘Foo.__init__’ is a constructor seems
>> needlessly confusing.
>> 
> ...
>> * A constructor should return the instance. ‘Foo.__init__’ does not do
>>   that; ‘Foo.__new__’ does.
> 
> This seems like an odd thing to insist on. C++ and Java constructors
> don't return the instance.

I'm not sure what you mean by that. I think they do, at least in C++.

Normally in C++ you would create an instance like this:

MyClass obj(arg);


In Python terms, that would be written as: `obj = MyClass(arg)`.


But one can also create "anonymous objects" which aren't assigned to a named 
variable:

something.method( MyClass(args) );


Doesn't that count as "returning an instance"?


> C++ allocators return the instance.

As I understand it, C++ allocators are specialist methods used in the standard 
library for container classes which allocate storage, i.e. the equivalent of 
Python lists and dicts.

http://en.cppreference.com/w/cpp/concept/Allocator

As far as I can tell, they aren't relevant to "simple" record- or struct-like 
objects.


> I'm happy to call __new__ an allocator. It serves exactly the same
> role in Python as allocators do in C++: its job is to create the raw
> material for the object, and they very rarely need to be written.

I think that last part is wrong in Python. Any time you are creating an 
immutable class -- and some of us do that a lot -- you generally need to write 
__new__. That makes __new__ very different from C++ allocators, and more like 
C++ constructors.

On the other hand, __new__ seems to be quite similar to ObjectiveC's `alloc`, 
which is called the allocator, and __init__ similar to ObjectiveC's init, which 
is the initialiser!

ObjectiveC also has a new method, which just calls alloc then init.


>> If the differences didn't matter I would agree that “overly pedantic” is
>> fair. But those differences trip up newcomers. Thinking of
>> ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
>> from – am I not meant to be constructing it? — and to attempt to return
>> that instance.
> 
> Creating objects is confusing, but beginners don't come to Python
> with an expectation of what a "constructor" is.  Filling in the
> attributes of an object is just as clearly a kind of construction
> as allocating memory.


Remember that in Python __new__ can do a lot more than just allocate memory.

It just seems really weird to describe __init__ as a constructor when it 
initialises an existing instance: "initialiser" just seems to be the obvious 
term for it. (Do I really need to spell it out? __INIT__/INITialiser.)

Python's object creation model seems to be a lot closer to that of ObjectiveC 
or C++ than Javascript, so copying Javascript's terminology seems risky to me.



-- 
Steven
"Ever since I learned about confirmation bias, I've been seeing 
it everywhere." - Jon Ronson

-- 
https://mail.python.org/mailman/listinfo/python-list


Method to know if object support being weakreferenced ?

2016-12-12 Thread Matthias Bussonnier
Hi all, 

I was recently had to use weakreferences, using the weakref module, and came 
across the fact that some object cannot be weakreferenced. If you try to do so 
you get greated by a TypeError, which is a totally expected and documented 
behavior. 

As I tend to prefer the "Look before you leap" approach I search for a method 
capable of telling me whether an object can be weakreferenced. Which I failed 
to found. 

I could of course write a function that try/except and return False/True 
depending on the result, but that seem suboptimal as how can I know that the 
TypeError does come from not being able to take a weak reference ? And not from 
something else ?

The common Idiom in CPython, at the C layer seem to be 
PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob)). So I can (and did) write a C-extension 
that expose such a function, but it does seem silly that no one else did that 
before me, and that no one seemed to have encountered the problem before. 

So am I missing something ? Is such a function not useful ?  Is there any 
reason not to have it in the stdlib ?

Thanks.
-- 
M
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Ned Batchelder
On Monday, December 12, 2016 at 6:17:43 PM UTC-5, Ben Finney wrote:
> Ned Batchelder  writes:
> 
> > Claiming that __init__ isn't a constructor seems overly pedantic to
> > me.
> 
> Whereas to me, claiming that ‘Foo.__init__’ is a constructor seems
> needlessly confusing.
> 
...
> * A constructor should return the instance. ‘Foo.__init__’ does not do
>   that; ‘Foo.__new__’ does.

This seems like an odd thing to insist on. C++ and Java constructors
don't return the instance.  C++ allocators return the instance. 
I'm happy to call __new__ an allocator. It serves exactly the same
role in Python as allocators do in C++: its job is to create the raw
material for the object, and they very rarely need to be written.

> 
> If the differences didn't matter I would agree that “overly pedantic” is
> fair. But those differences trip up newcomers. Thinking of
> ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
> from – am I not meant to be constructing it? — and to attempt to return
> that instance.

Creating objects is confusing, but beginners don't come to Python
with an expectation of what a "constructor" is.  Filling in the 
attributes of an object is just as clearly a kind of construction
as allocating memory.

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python constructors have particular semantics, and ‘Foo.__init__’ doesn't qualify (was: The right way to 'call' a class attribute inside the same class)

2016-12-12 Thread Juan C.
I agree with you, I'll post here the same thing I said in there for
another member:

On Mon, Dec 12, 2016 at 6:59 PM, Thomas 'PointedEars' Lahn
 wrote:
> 
>

Using the Python official doc link you provided, it clearly states
that `__new__` is the one called to "create a new instance of class
[...] The return value of __new__() should be the new object instance
(usually an instance of cls)."

On the other hand, `__init__` is "called after the instance has been
created (by __new__()), but before it is returned to the caller."

Here we have the same mindset regarding `__new__` vs `__init__`:

- http://python-textbok.readthedocs.io/en/1.0/Classes.html
"Note: __init__ is sometimes called the object’s constructor, because
it is used similarly to the way that constructors are used in other
languages, but that is not technically correct – it’s better to call
it the initialiser. There is a different method called __new__ which
is more analogous to a constructor, but it is hardly ever used."

- http://www.python-course.eu/python3_object_oriented_programming.php
"We want to define the attributes of an instance right after its
creation. __init__ is a method which is immediately and automatically
called after an instance has been created. [...] The __init__ method
is used to initialize an instance."

- https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#Python
"In Python, constructors are defined by one or both of __new__ and
__init__ methods. A new instance is created by calling the class as if
it were a function, which calls the __new__ and __init__ methods. If a
constructor method is not defined in the class, the next one found in
the class's Method Resolution Order will be called."

- http://www.diveintopython3.net/iterators.html
"The __init__() method is called immediately after an instance of the
class is created. It would be tempting — but technically incorrect —
to call this the “constructor” of the class. It’s tempting, because it
looks like a C++ constructor (by convention, the __init__() method is
the first method defined for the class), acts like one (it’s the first
piece of code executed in a newly created instance of the class), and
even sounds like one. Incorrect, because the object has already been
constructed by the time the __init__() method is called, and you
already have a valid reference to the new instance of the class."

In general, the idea is simple, `__new__` constructs and `__init__`
initializes, this is what I believe in, after all the name `__init__`
already tell us that it's a *init* ialiser...

It doesn't matter if Java, C#, Javascript,  have
different approaches, I'm programming (or at least, trying to :p) in
Python, so I'll follow what the official doc and the vast majority of
books/courses/etc say.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python constructors have particular semantics, and ‘Foo.__init__’ doesn't qualify (was: The right way to 'call' a class attribute inside the same class)

2016-12-12 Thread Ben Finney
Chris Angelico  writes:

> On Tue, Dec 13, 2016 at 10:17 AM, Ben Finney  
> wrote:
> > If the differences didn't matter I would agree that “overly
> > pedantic” is fair. But those differences trip up newcomers. Thinking
> > of ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute
> > came from – am I not meant to be constructing it? — and to attempt
> > to return that instance. And when the time comes to lean about
> > ‘__new__’ the confusion continues, because the newcomer has been
> > told that something *else* is the constructor, so what's this?
>
> In JavaScript [different semantics apply].
>
> Ultimately, every language has slightly different semantics […], so
> you have to learn that the "constructor" might have slightly different
> semantics.

Please read again the message you extracted that quote from. I already
said I'm not claiming some other programming language's semantics should
dictate Python's.


What I'm saying is that in Python, there *already are* different
semantics for a constructor, and they don't match the semantics of
‘Foo.__init__’.

In Python, a constructor for a class is a class method. ‘Foo.__new__’ is
a constructor. ‘Foo.__init__’ is an instance method, so it's not a
constructor.

In Python, a constructor for a class makes the instance where it didn't
already exist. ‘Foo.__new__’ is a constructor. ‘Foo.__init__’ requires
the instance to already be constructed, so it's not a constructor.

In Python, a constructor for a class returns a new instance of that
class. ‘Foo.__new__’ is a constructor. ‘Foo.__init__’ must return None,
so it's not a constructor.

In Python, a custom constructor for a class follows the above
descriptions. ‘datetime.fromtimestamp’ is a constructor.
‘datetime.__init__’ is not.


None of this argues from the semantics of other programming languages,
so telling me other languages have different semantics is not a response
to this argument.

I'm showing that Python classes *already have* constructors, and
‘Foo.__init__’ doesn't qualify because it doesn't have the semantics of
Python constructors.

-- 
 \ “I've always wanted to be somebody, but I see now that I should |
  `\   have been more specific.” —Jane Wagner, via Lily Tomlin |
_o__)  |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Chris Angelico
On Tue, Dec 13, 2016 at 10:17 AM, Ben Finney  wrote:
> If the differences didn't matter I would agree that “overly pedantic” is
> fair. But those differences trip up newcomers. Thinking of
> ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
> from – am I not meant to be constructing it? — and to attempt to return
> that instance. And when the time comes to lean about ‘__new__’ the
> confusion continues, because the newcomer has been told that something
> *else* is the constructor, so what's this?

In JavaScript, it's normal to talk about "calling a function as a
constructor". When you do, there is a 'this' object before you start.
Should we tell the JavaScript folks to be more pedantic, because
'this' should end up existing? Does it really even matter when memory
gets allocated and the object's identity assigned? Before __init__
gets called, the object isn't "truly there" - its fundamental
invariants may not yet have been established, and key attributes might
not have been set up. Once __init__ finishes, there is an expectation
that attributes and invariants are sorted out.

This is like the old "Python doesn't have variables" thing.
Ultimately, every language has slightly different semantics (otherwise
they'd be trivial transformations, like Ook and Brainf*), so you have
to learn that the "constructor" might have slightly different
semantics. Accept it - embrace it. Learn it.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Ben Finney
Ned Batchelder  writes:

> Claiming that __init__ isn't a constructor seems overly pedantic to
> me.

Whereas to me, claiming that ‘Foo.__init__’ is a constructor seems
needlessly confusing.

* Classes already have a constructor, ‘Foo.__new__’. If we call
  something else the constructor, what do we call ‘__new__’? Are they
  both constructors?

* A constructor for Foo should start from “no instance” and result in
  “an instance of Foo”. ‘Foo.__init__’ does not do that; ‘Foo.__new__’
  does.

* A constructor should return the instance. ‘Foo.__init__’ does not do
  that; ‘Foo.__new__’ does.

If the differences didn't matter I would agree that “overly pedantic” is
fair. But those differences trip up newcomers. Thinking of
‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
from – am I not meant to be constructing it? — and to attempt to return
that instance. And when the time comes to lean about ‘__new__’ the
confusion continues, because the newcomer has been told that something
*else* is the constructor, so what's this?

> What's true is that Python's constructors (__init__) are different than
> C++ constructors.  In C++, you don't have an object of type T until the
> constructor has finished. In Python, you have an object of type T before
> __init__ has been entered.

I'm not going to argue that C++ should define terminology for other
languages. But “constructor” should have a close correlation with the
normal English-language meaning of the term.

That meaning matches ‘Foo.__new__’, which makes that method a
constructor. It does not match ‘Foo.__init__’, which makes that method
not a constructor.

> The reason to call __init__ a constructor is because of what is the
> same between C++ and Python: the constructor is where the author of
> the class can initialize instances of the class.

So you've just described what ‘Foo._init__’ does: it initialises the
existing instance. That's why it is better to call it the “initialiser”,
a term we already have and use correctly.

-- 
 \ “DRM doesn't inconvenience [lawbreakers] — indeed, over time it |
  `\ trains law-abiding users to become [lawbreakers] out of sheer |
_o__)frustration.” —Charles Stross, 2010-05-09 |
Ben Finney

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Steve D'Aprano
On Tue, 13 Dec 2016 07:15 am, Ned Batchelder wrote:

> Claiming that __init__ isn't a constructor seems overly pedantic to me.
> What's true is that Python's constructors (__init__) are different than
> C++ constructors.  In C++, you don't have an object of type T until the
> constructor has finished. In Python, you have an object of type T before
> __init__ has been entered.
> 
> The reason to call __init__ a constructor is because of what is the same
> between C++ and Python: the constructor is where the author of the class
> can initialize instances of the class.

That logic would have been more convincing back in the days of classic
classes in Python 1.5 or 2.0, less so after class/type unification where we
have an actual constructor __new__ that creates the instance.

The section of the docs that deal with object customization takes an
agnostic position, referring only to the "class constructor EXPRESSION"
(i.e. MyClass(spam, eggs) or equivalent):

https://docs.python.org/2/reference/datamodel.html#object.__init__

and similarly in __new__ (this time the v3 docs, just because):

https://docs.python.org/3/reference/datamodel.html#object.__new__


so if you want to be pedantic, one might argue that Python has a concept
of "object/class constructor expressions", MyClass(spam, eggs), but not of
constructor method(s). But that seems even stranger than insisting that:

- __new__ is the constructor method;
- __init__ is the initializer method.


Another way of naming things is to say that:

- __new__ is the allocator;
- __init__ is the initializer;
- the two together, __new__ + __init__, make up the constructor.

Not to be confused with the constructor expression, MyClass(spam, eggs), or
the alternative constructor, MyClass.make_instance(...).

Naming things is hard.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Mon, Dec 12, 2016 at 6:59 PM, Thomas 'PointedEars' Lahn
 wrote:
> 

Using the Python official doc link you provided, it clearly states
that `__new__` is the one called to "create a new instance of class
[...] The return value of __new__() should be the new object instance
(usually an instance of cls)." On the other hand, `__init__` is
"called after the instance has been created (by __new__()), but before
it is returned to the caller."

Here we have the same mindset regarding `__new__` vs `__init__`:

- http://python-textbok.readthedocs.io/en/1.0/Classes.html
"Note: __init__ is sometimes called the object’s constructor, because
it is used similarly to the way that constructors are used in other
languages, but that is not technically correct – it’s better to call
it the initialiser. There is a different method called __new__ which
is more analogous to a constructor, but it is hardly ever used."

- http://www.python-course.eu/python3_object_oriented_programming.php
"We want to define the attributes of an instance right after its
creation. __init__ is a method which is immediately and automatically
called after an instance has been created. [...] The __init__ method
is used to initialize an instance."

- https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#Python
"In Python, constructors are defined by one or both of __new__ and
__init__ methods. A new instance is created by calling the class as if
it were a function, which calls the __new__ and __init__ methods. If a
constructor method is not defined in the class, the next one found in
the class's Method Resolution Order will be called."

- http://www.diveintopython3.net/iterators.html
"The __init__() method is called immediately after an instance of the
class is created. It would be tempting — but technically incorrect —
to call this the “constructor” of the class. It’s tempting, because it
looks like a C++ constructor (by convention, the __init__() method is
the first method defined for the class), acts like one (it’s the first
piece of code executed in a newly created instance of the class), and
even sounds like one. Incorrect, because the object has already been
constructed by the time the __init__() method is called, and you
already have a valid reference to the new instance of the class."


In general, the idea is simple, `__new__` constructs and `__init__`
initializes, this is what I believe in, after all the name `__init__`
already tell us that it's a *init* ialiser...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Ned Batchelder
On Monday, December 12, 2016 at 4:31:00 PM UTC-5, Gregory Ewing wrote:
> Ned Batchelder wrote:
> > In C++, you don't have an object of type T until the
> > constructor has finished. In Python, you have an object of type T before
> > __init__ has been entered.
> 
> That distinction seems a bit pedantic as well. Inside a C++
> constructor you have access to something having all the
> fields and methods of an object of type T, they just
> haven't been filled in yet.

I agree the distinction is pedantic. It does matter sometimes, such as:
if a C++ constructor raises an exception, will the corresponding destructor
be run, or not? (No, because it never finished making an object of type T.)

But in any case, all the more reason not to let C++ semantics govern
Python vocabulary.

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Steve D'Aprano
On Tue, 13 Dec 2016 03:17 am, Chris Angelico wrote:

> You could check "foo" in self.__dict__, but I don't know of any
> real-world situations where you need to.

vars(self) is probably the better way to access self's namespace, rather
than directly self.__dict__. Unfortunately vars() doesn't understand
__slots__, which I think is an oversight.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Gregory Ewing

Ned Batchelder wrote:

In C++, you don't have an object of type T until the
constructor has finished. In Python, you have an object of type T before
__init__ has been entered.


That distinction seems a bit pedantic as well. Inside a C++
constructor you have access to something having all the
fields and methods of an object of type T, they just
haven't been filled in yet.

It's a bit like asking at what point between conception and
birth a baby starts to exist.

--
Greg

--
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Thomas 'PointedEars' Lahn
Juan C. wrote:

> On Mon, Dec 12, 2016 at 12:34 PM, Thomas 'PointedEars' Lahn
>  wrote:
>> To call something means generally in programming, and in Python, to
>> execute it as a function instead: In the code above, the class object
>> referred to by “Box” is called twice in order to instantiate twice
>> (calling a class object in Python means to instantiate it, implicitly
>> calling its constructor method, “__init__”, if any), and the global
>> “print” function is called three times.
> 
> Since we are talking about Python terminology I believe that calling
> `__init__` a constructor is also wrong. I've already seem some
   ^
> discussions regarding it and the general consensus is that `__init__`
> shouldn't be called constructor as it isn't really a constructor (like
> Java/C# constructors). […]

IBTD:

,-
| 
| constructor
| 
| (programming)   1. In object-oriented languages, a function provided by a 
   
| class to initialise a newly created object. The constructor function 
  ^^
| typically has the same name as the class. It may take arguments, e.g. to 
| set various attributes of the object or it may just leave everything 
  
| undefined to be set elsewhere.
| 
| A class may also have a destructor function that is called when objects of 
| the class are destroyed.

Free On-line Dictionary of Computing, Last updated: 2014-10-04.

In Python, a class’s __init__() is called after its __new__() [1], and 
“typically” means “not always” (for another example, in clean PHP code the 
constructor’s name is “__construct”).



[In fact, there are constructors in object-oriented programming languages 
with prototype-based inheritance, like implementations of ECMAScript Ed. 1 
to 7 (except 4), too.]

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Ned Batchelder
On Monday, December 12, 2016 at 12:58:30 PM UTC-5, Juan C. wrote:
> Since we are talking about Python terminology I believe that calling
> `__init__` a constructor is also wrong. I've already seem some
> discussions regarding it and the general consensus is that `__init__`
> shouldn't be called constructor as it isn't really a constructor (like
> Java/C# constructors). Some source:
> 
> - 
> http://stackoverflow.com/questions/4859129/python-and-python-c-api-new-versus-init
> - http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init

Claiming that __init__ isn't a constructor seems overly pedantic to me.
What's true is that Python's constructors (__init__) are different than
C++ constructors.  In C++, you don't have an object of type T until the
constructor has finished. In Python, you have an object of type T before
__init__ has been entered.

The reason to call __init__ a constructor is because of what is the same
between C++ and Python: the constructor is where the author of the class
can initialize instances of the class.

There are many programming languages, and they have similar overlapping
constructs, but there are differences among the constructs.  It's a
challenge to decide when those differences are great enough to use a
different name, and when those differences are slight enough to just note
them as a difference.

As an example, people are happy to use the word "function" for things in
Python, C, C++, Java, JavaScript, and Haskell, despite the huge differences
in how they behave.  The commonalities, especially in how these constructs
are used by developers to express themselves, are similar enough that
we call them all "functions."  It seems to me that we can do the same
for "constructor."

--Ned.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SIP install error on windows

2016-12-12 Thread Phil Thompson
On 12 Dec 2016, at 7:29 pm, Xristos Xristoou  wrote:
> 
> 
> hello i want to install sip on windows bit using python 
> 32 bit.
> i download sip from this link https://www.riverbankcomputing.com
> i try to install from cmd line :
> 
> C:\WINDOWS\system32>cd C:\Users\username\Desktop\sip-4.17
> 
> C:\Users\username\Desktop\sip-4.17>python configure.py install
> and take that error any idea ?
> 
> This is SIP 4.17 for Python 2.7.11 on win32.
> Error: Unsupported macro name specified. Use the --show-build-macros flag to
> see a list of supported macros.

Try the documentation...

http://pyqt.sourceforge.net/Docs/sip4/installation.html

Phil
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SIP install error on windows

2016-12-12 Thread Xristos Xristoou
Τη Δευτέρα, 12 Δεκεμβρίου 2016 - 9:29:38 μ.μ. UTC+2, ο χρήστης Xristos Xristoou 
έγραψε:
> hello i want to install sip on windows bit using python 
>  32 bit.
> i download sip from this link https://www.riverbankcomputing.com
> i try to install from cmd line :
> 
> C:\WINDOWS\system32>cd C:\Users\username\Desktop\sip-4.17
> 
> C:\Users\username\Desktop\sip-4.17>python configure.py install
> and take that error any idea ?
> 
> This is SIP 4.17 for Python 2.7.11 on win32.
> Error: Unsupported macro name specified. Use the --show-build-macros flag to
> see a list of supported macros.

yes but i dont have python 3 i need use python 2.7
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SIP install error on windows

2016-12-12 Thread Phil Thompson
On 12 Dec 2016, at 7:38 pm, Bob Gailer  wrote:
> 
> On Dec 12, 2016 2:30 PM, "Xristos Xristoou"  wrote:
>> 
>> 
>> hello i want to install sip on windows bit using python
>> 32 bit.
>> i download sip from this link https://www.riverbankcomputing.com
>> i try to install from cmd line :
>> 
>> C:\WINDOWS\system32>cd C:\Users\username\Desktop\sip-4.17
>> 
>> C:\Users\username\Desktop\sip-4.17>python configure.py install
>> and take that error any idea ?
> The instructions at Riverbank for installing sip tell me to use pip3
> install. I suggest you try that.

Not for Python v2.

Phil
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SIP install error on windows

2016-12-12 Thread Bob Gailer
On Dec 12, 2016 2:30 PM, "Xristos Xristoou"  wrote:
>
>
> hello i want to install sip on windows bit using python
>  32 bit.
> i download sip from this link https://www.riverbankcomputing.com
> i try to install from cmd line :
>
> C:\WINDOWS\system32>cd C:\Users\username\Desktop\sip-4.17
>
> C:\Users\username\Desktop\sip-4.17>python configure.py install
> and take that error any idea ?
The instructions at Riverbank for installing sip tell me to use pip3
install. I suggest you try that.
>
> This is SIP 4.17 for Python 2.7.11 on win32.
> Error: Unsupported macro name specified. Use the --show-build-macros flag
to
> see a list of supported macros.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


SIP install error on windows

2016-12-12 Thread Xristos Xristoou

hello i want to install sip on windows bit using python 
 32 bit.
i download sip from this link https://www.riverbankcomputing.com
i try to install from cmd line :

C:\WINDOWS\system32>cd C:\Users\username\Desktop\sip-4.17

C:\Users\username\Desktop\sip-4.17>python configure.py install
and take that error any idea ?

This is SIP 4.17 for Python 2.7.11 on win32.
Error: Unsupported macro name specified. Use the --show-build-macros flag to
see a list of supported macros.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread John Gordon
In  "Juan C." 
 writes:

> The instructor said that the right way to call a class attribute is to use
> 'Class.class_attr' notation, but on the web I found examples where people
> used 'self.class_attr' to call class attributes.

Class instances may override class attributes by creating local attributes
of the same name, in which case Class.class_attr and self.class_attr may
not be equal, so you'd have to use the correct one for your needs.

If you're sure that an instance does not override the class attribute,
then you can use whichever one you prefer.  self.class_attr may be more
convenient because you don't have to provide a specific class name.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Mon, Dec 12, 2016 at 12:34 PM, Thomas 'PointedEars' Lahn
 wrote:
> First of all, the proper term for what you are doing there is _not_ “call”;
> you are _accessing_ an attribute instead.

Indeed, `accessing` seems better. I was looking for a better word but
couldn't find at the moment.

> To call something means generally in programming, and in Python, to execute
> it as a function instead: In the code above, the class object referred to by
> “Box” is called twice in order to instantiate twice (calling a class object
> in Python means to instantiate it, implicitly calling its constructor
> method, “__init__”, if any), and the global “print” function is called three
> times.

Since we are talking about Python terminology I believe that calling
`__init__` a constructor is also wrong. I've already seem some
discussions regarding it and the general consensus is that `__init__`
shouldn't be called constructor as it isn't really a constructor (like
Java/C# constructors). Some source:

- 
http://stackoverflow.com/questions/4859129/python-and-python-c-api-new-versus-init
- http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Django broken pipe error

2016-12-12 Thread justin walters
On Mon, Dec 12, 2016 at 7:27 AM, roma  wrote:

> Thanks Justin,
>
> I believe, the whole database story has no influence on the broken pipe
> error. I've commented out the whole block and leave only return line:
> return HttpResponse(res, content_type="text/plain; charset=utf-8")
> The error is still present. And I have no influence on that.
>
> I call python from js client:
>
> var newTrendReport = new App.TrendReport();
> newTrendReport.set('search_phrase', search_phrase);
> newTrendReport.set('time_from', time_from);
> newTrendReport.set('time_to', time_to);
> newTrendReport.set('time_scale', time_scale);
> newTrendReport.set('category', category);
> newTrendReport.startExport(
>
> function(response){
> console.log("Successfully calculated trend report.");
> App.trendPage = new App.TrendPageView();
> App.trendPage.render(response);
> },
> );
>
> go throw:
>
> App.TrendReport = Backbone.Model.extend({
> urlRoot: "/api/trend_reports/",
> defaults: {
> search_phrase: "",
> time_from: "",
> time_to: "",
> time_scale: "",
> category: ""
> },
>
> startExportSuffix: "/export_report/",
>
> startExport: function( successCallback, errorCallback ) {
> console.log("start trend calculation");
> var that = this;
> var ajaxUrl = this.startExportSuffix;
> var options = {
> method: "POST",
> data: this.attributes,
> contentType: "application/json;charset=UTF-8",
> dataType: "json",
>
> error: errorCallback,
> success: successCallback
> };
> console.log("start trend export sync");
> App.ajax(ajaxUrl, options);
> }
>
> });
>
> and come in export_report method.
>
> My urls.py:
>
> url(r'^export_report', ensure_csrf_cookie(views.export_report),
> name="export_report"),
> --
> https://mail.python.org/mailman/listinfo/python-list
>

I'm not super familiar with the way backbone does http requests, but
something seems off about the startExport function.
It seems to me that you are sending a post request to "/export_report/"
which is an endpoint that I'm guessing is nested
in an include from "/api/trend_reports/". However, it looks like the error
you're getting above says you aren't sending
the request to "https://root.com/api/trend_reports/export_report/";.
Instead, you are sending the request to "https://root.com/export_report/"; .
Though, I'm also not sure that's the case because that would normally throw
a 404.

I also noticed that you set content type to 'application/json' in your js,
but the view function returns a 'text/plain' content type. Is
There a reason for this?

The data key in your js http function is set to the attributes variable
which, as far as I can tell, does not exist.

There's a lot going on here, but I think you can probably narrow it down to
something in your backbone code or the way
backbone handles http requests as the error you are getting is caused by
the client prematurely closing the socket.
It's possible backbone will stop reading the response since it isn't the
same content-type as the request.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Juan C.
On Sun, Dec 11, 2016 at 11:34 PM, Steve D'Aprano
 wrote:

> So... in summary:
>
>
> When *assigning* to an attribute:
>
> - use `self.attribute = ...` when you want an instance attribute;
>
> - use `Class.attribute = ...` when you want a class attribute in
>   the same class regardless of which subclass is being used;
>
> - use `type(self).attribute = ...` when you want a class attribute
>   in a subclass-friendly way.
>
>
> When *retrieving* an attribute:
>
> - use `self.attribute` when you want to use the normal inheritance
>   rules are get the instance attribute if it exists, otherwise a
>   class or superclass attribute;
>
> - use `type(self).attribute` when you want to skip the instance
>   and always return the class or superclass attribute.

Thanks, that seems simple enough.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Chris Angelico
On Tue, Dec 13, 2016 at 1:34 AM, Thomas 'PointedEars' Lahn
 wrote:
> ³  How can one tell the difference in Python between a pre-initialized,
>inherited attribute value and one own that is just equal to the inherited
>one?  In ECMAScript, this.hasOwnProperty("foo") would return “false” if
>the property were inherited, “true” otherwise.  But in Python,
>hasattr(self, "foo") returns “True” regardless whether the “foo”
>attribute of the calling instance has been assigned a value explicitly.
>What is the Python equivalent of ECMAScript’s
>Object.prototype.hasOwnProperty() method?

You could check "foo" in self.__dict__, but I don't know of any
real-world situations where you need to.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Thomas 'PointedEars' Lahn
Thomas 'PointedEars' Lahn wrote:

> Note that (AIUI) in this example the instances of the class referred by
> “C” do not have an *own* “foo” property in the beginning, so until bar()
> is called on them, they inherit that property (and its value) from that
> class.³

For proper *Python* terminology, s/property/attribute/g here (see below).

> […]
> 
> […]
> ³  How can one tell the difference in Python between a pre-initialized,
>inherited attribute value and one own that is just equal to the
>inherited one?  In ECMAScript, this.hasOwnProperty("foo") would return
>“false” if the property were inherited, “true” otherwise.  But in
>Python, hasattr(self, "foo") returns “True” regardless whether the
>“foo” attribute of the calling instance has been assigned a value
>explicitly.  What is the Python equivalent of ECMAScript’s
>Object.prototype.hasOwnProperty() method?

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The right way to 'call' a class attribute inside the same class

2016-12-12 Thread Thomas 'PointedEars' Lahn
Juan C. wrote:

> I'm watching a Python course and was presented a topic regarding classes.
> One of the examples were:
> 
> box.py
> 
> class Box:
> serial = 100
> 
> def __init__(self, from_addr, to_addr):
> self.from_addr = from_addr
> self.to_addr = to_addr
> self.serial = Box.serial
> Box.serial += 1
> 
> 
> from box import *
> 
> a = Box('19 Beech Ave. Seattle, WA 98144', '49 Carpenter Street North
> Brunswick, NJ 08902')
> b = Box('68 N. Church Dr. Vicksburg, MS 39180', '8 Lake Forest Road
> Princeton, NJ 08540')
> 
> print(a.serial)  # print: 100
> print(b.serial)  # print: 101
> print(Box.serial)  # print: 102
> 
> 
> The instructor said that the right way to call a class attribute is to use
> 'Class.class_attr' notation, but on the web I found examples where people
> used 'self.class_attr' to call class attributes. I believe that using the
> first notation is better ('Class.class_attr'), this way the code is more
> explicit, but is there any rules regarding it?

First of all, the proper term for what you are doing there is _not_ “call”;  
you are _accessing_ an attribute instead.

To call something means generally in programming, and in Python, to execute 
it as a function instead: In the code above, the class object referred to by 
“Box” is called twice in order to instantiate twice (calling a class object 
in Python means to instantiate it, implicitly calling its constructor 
method, “__init__”, if any), and the global “print” function is called three 
times.

Second, you do not appear to be aware that the notations

  C.foo

and

  self.foo

within a method of the class object referred to by “C” are _not_ equivalent:

“C” is _not_ a "more explicit" way to access the class than “self”; it is 
referring to a *different* (type of) *object* instead, a *class* object.  
(This is different in Python than in, for example, PHP.)

Assignment to “C.foo” modifies an attribute named “foo” of the class object 
referred to “C”, i.e. it modifies the value of that attribute *for all 
instances of that class* (but see below).

Assignment to “self.foo” modifies only the “foo” attribute *of a particular 
instance* of the class, or adds an attribute of that name to it; namely, the 
instance on which the method was called that modifies/adds the “foo” 
attribute (referred to by the formal parameter “self” of the method¹).

$ python3 -c '
class C:
foo = 23

def bar (self):
self.foo = 42

def baz (self):
C.foo = 42

print(C.foo)
o = C()
o2 = C()   
print(C.foo, o.foo, o2.foo)
o.bar()
print(C.foo, o.foo, o2.foo)
o.baz()
print(C.foo, o.foo, o2.foo)
'
23
23 23 23
23 42 23
42 42 42


To illustrate, the (simplified) UML diagrams² for the state of the program 
after each relevant executed chunk of code (as always recommended, use a 
fixed-width font for display):

#
class C:
foo = 23

def bar (self):
self.foo = 42

def baz (self):
C.foo = 42

#

  ,-.
C --> : :type   :
  :=:
  : +foo : int = 23 :
  :-:
  : +bar()  :
  : +baz()  :
  `-'

#
o = C()
#

  ,-.
C --> : :type   :
  :=:
  : +foo : int = 23 :
  :-:
  : +bar()  :
  : +baz()  :
  `-'
   ^
   :
,-.
o > : :__main__.C :
:-:
`-'

#
o2 = C()   
#

,---.
C > : :type :
:===:
: +foo : int = 23   :
:---:
: +bar():
: +baz():
`---'
  ^   ^   
  :   :
   ,-. ,-.
o ---> : :__main__.C : : :__main__.C : <--- o2
   :-: :-:
   `-' `-'

#
o.bar()
#

,-.
C > : :type   :
:=:
: +foo : int = 23 :
:-:
: +bar()  :
: +baz()  :
`-'
^ ^
: :
   ,-. ,-.
o ---> : :__main__.C

Re: Django broken pipe error

2016-12-12 Thread roma
On Wednesday, December 7, 2016 at 6:15:41 PM UTC+1, justin walters wrote:
> On Wed, Dec 7, 2016 at 1:08 AM,  wrote:
> 
> > Thank you Justin,
> >
> > I'm on the dev server and should present results in this way.
> >
> > Yes, I use manage.py runserver --insecure to start the server (from
> > PyCharm).
> >
> > My views.py call:
> >
> > @detail_route(methods=['post'], permission_classes=[permissions.AllowAny])
> > def export_report(request):
> > body_unicode = request.body.decode('utf-8')
> > body_str = body_unicode.encode('ascii','ignore')
> > attr_list = body_str.split('&')
> > attr_dict = {}
> > if (len(attr_list) > 0):
> > for attr in attr_list:
> >...
> >key = key_value_pair[0]
> >attr_dict[key] = key_value_pair[1]
> > trend = trends.calculate_trend(
> > attr_dict['search_phrase']
> > , attr_dict['time_from']
> > , attr_dict['time_to']
> > , attr_dict['time_scale']
> > )
> > attr_dict['trend'] = trend
> > res = str(json.dumps(attr_dict))
> > return HttpResponse(res, content_type="text/plain; charset=utf-8")
> >
> > and trend calculation in trends.py with database calls:
> >
> > def calculate_trend(query_phrase, time_from, time_to, time_scale):
> > # check in database if trend already exists
> > try:
> > db_trend = Trend.objects.get(pk=query_phrase)
> > if db_trend.from_time.strftime("%Y-%m-%d") == time_from \
> > and db_trend.to_time.strftime("%Y-%m-%d") == time_to \
> > and db_trend.granularity == time_scale:
> > logger.info("trend already exists.")
> > existing_trend_dict = ast.literal_eval(db_trend.content)
> > return existing_trend_dict
> > except Trend.DoesNotExist:
> > logger.info("It is a new trend search.")
> > trend_dict = {}
> > start_time = pd.Timestamp(value[0])
> > end_time = pd.Timestamp(value[-1])
> > freq = ... get frequency using pandas lib
> > trend_dict[key] = freq
> > json_trend_content = trend_dict_to_sorted_json_str(trend_dict)
> > trend = Trend(
> > phrase=query_phrase,
> > content=json_trend_content,
> > from_time=time_from,
> > to_time=time_to,
> > granularity=time_scale,
> > )
> > if trend is not None:
> > try:
> > db_trend = Trend.objects.get(pk=query_phrase)
> > db_trend.delete()
> > logger.info("delete old trend: %s. " % trend)
> > except Trend.DoesNotExist:
> > logger.info("create trend: %s. " % trend)
> > trend.save()
> > return trend_dict
> >
> > Thank you in advance!
> >
> > Roman
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >
> 
> 
> It looks like you can probably get rid of the try/except block at the end
> of the calculate_trend
> method as any existing Trend object will have already been caught in the
> first try/except block.
> 
> >From what I'm reading here:
> http://stackoverflow.com/questions/11866792/how-to-prevent-errno-32-broken-pipe
> ,
> this issue can be caused by the client closing the connection before
> sendall() finishes writing. Can you estimate
> how long it takes for a request to this endpoint takes to resolve? If it's
> a long time(maybe due to the pandas call?),
> your browser/client may be timing out. It could be because it takes a while
> for the Db to find an existing Trend object
> as well.
> 
> I can't give you any advice on how to fix it exactly, but I can tell you
> what the problem is: The client is closing the
> connection before socket.sendall() has finished writing to the socket. My
> guess is that the calculate_trend() method
> takes a long time to complete and the client is timing out.

Thanks Justin,

I believe, the whole database story has no influence on the broken pipe error. 
I've commented out the whole block and leave only return line:
return HttpResponse(res, content_type="text/plain; charset=utf-8") 
The error is still present. And I have no influence on that.

I call python from js client:

var newTrendReport = new App.TrendReport();
newTrendReport.set('search_phrase', search_phrase);
newTrendReport.set('time_from', time_from);
newTrendReport.set('time_to', time_to);
newTrendReport.set('time_scale', time_scale);
newTrendReport.set('category', category);
newTrendReport.startExport(

function(response){
console.log("Successfully calculated trend report.");
App.trendPage = new App.TrendPageView();
App.trendPage.render(response);
},
);

go throw:

App.TrendReport = Backbone.Model.extend({
urlRoot: "/api/trend_reports/",
defaults: {
search_phrase: "",
time_from: "",
time_to: "",
time_scale: "",
category: ""
},

startExportSuffix: "/export_report/",

start