Re: loading trees...

2016-06-13 Thread dieter
Fillmore  writes:

> Hi, problem for today. I have a batch file that creates "trees of data".
> I can save these trees in the form of python code or serialize them with 
> something
> like pickle.
>
> I then need to run a program that loads the whole forest in the form of a 
> dict()
> where each item will point to a dynamically loaded tree.
>
> What's my best way to achieve this? Pickle? or creating curtom python code?

Not sure about the "best". But one possibility would be to use the
"ZODB" ("Zope Object DataBase").

The "ZODB" allows you to store rooted graph like data structures
(among them forests) persitently. Nodes in this graph are loaded
dynamically (and cached).

It would be a bit difficult to use Python "dict"s directly, but
the ZODB comes with "dict" like data structures which play well
with the ZODB persistency (e.g. "BTrees.OOBTree").

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


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread dieter
alanquei...@gmail.com writes:

> I'm trying to override methods inherited from a superclass by methods defined 
> in a mixin class.
> Here's an sscce:
> https://bpaste.net/show/6c7d8d590658 (never expires)
>
> I've had problems finding the proper way to do that, since at first the base 
> class wasn't to the right and I've assumed the correct order was from left to 
> right.

The class' MRO ("Method Resolution Order") determines in which
order attributes are looked up.
Either, you must order your base classes in such a way that the MRO
controlled lookup finds the methods you want to be used or
you must explicitely put a definition for those methods in your
derived class (it may have the form "overridden_method = 
.overridden_method").

The rules to determine the MRO are complex. The "inspect" module contains
a function ("get_mro") to show the MRO of a given class. Use it
to get your inheritance order right.

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


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Peter Otten
alanquei...@gmail.com wrote:

> Hello there.
> 
> I'm trying to override methods inherited from a superclass by methods
> defined in a mixin class. Here's an sscce:
> https://bpaste.net/show/6c7d8d590658 (never expires)

> #the following represents classes I don't have control over
> class Base(object):
> def methodX(self):
> print "methodX class Base"
> 
> class A(Base): #inherits methodX
> pass
> 
> class A2(Base): #inherits methodX
> pass
> 
> class A3(Base): #inherits methodX
> pass
> 
> #the following represents classes I have control over
> class B(object):
> def methodX(self):
> print "methodX class B"
> 
> class Z(B,A):
> def methodXfromA(self):
> A.methodX(self)
> 
> class Z2(B,A2):
> pass
> 
> class Z3(B,A3):
> pass
> 
> #what I need is to be able to quickly create these Z classes and override 
the
> #methodX by the functionality in class B, while still being able to call
> #class A.methodX
> 
> Z().methodX();
> Z2().methodX();
> Z3().methodX();
 


> I've had problems finding the proper way to do that, since at first the
> base class wasn't to the right and I've assumed the correct order was from
> left to right. It was previously suggested on IRC that the mixin should be
> a subclass of "Base"; that worked but I wasn't happy with it because the B
> class basically serves the purpose of "holding" a list of methods to be
> inherited and that should override the methods inherited from the "A"
> classes, so I didn't see why it should derive from "Base".
> 
> I eventually found in an article that the problem was the ordering of the
> superclasses I was deriving from, which should be from right to left, the
> only article I could find that states that is this one:
> https://www.ianlewis.org/en/mixins-and-python
> 
> Every single example of mixins in Python that I've read -except that one-
> (and I've seen literally dozens) has the base class to the left, although
> the other classes aren't overriding any methods (at least in most of
> them).
> 
> That bpaste code is working perfectly for me and makes sense, but I don't
> really like it, and the people on IRC couldn't convince me the code is
> fine.

But the code is fine. Write unit tests to ensure that the correct method is 
called.

Usually you use mixins to add methods. In that case the order of base 
classes doesn't matter.
 
> I haven't used Python for some time so I don't feel confident to judge
> that code, and perhaps there's a better way to achieve that result.
> However, what really scared me is the obscurity of the mixins usage in
> Python, and the fact that every example except that single one gets it
> "wrong", including from notable pythonistas.
> 
> Perhaps you guys could help me either convincing me that the bpaste code
> is OK, or perhaps coming up with a better solution for that problem. What
> matters to me is code re-usability in this case. I surely could
> re-implement the overrides in all "Z" classes separately, but that's what
> I'm trying to avoid. The requirements are: 1. I can't touch the "classes I
> don't have control over" (as per comment in code). 2. I don't want to pass
> the superclasses as parameters in the constructor. I see how you could
> solve the problem that way, but that would only increase the complexity of
> the code (PEP20). 3. I absolutely need to override methodX, I can't use
> composition and access the members another way unless I override methodX
> and access them there. This is to interface properly with other modules.
> 4. I need to be able to access A#.methodX in the "Z" classes methods. 5. I
> want to avoid using a factory. It's one of the most over-used patterns in
> my opinion, and I really don't like that.

That looks like you are actively excluding most alternatives ;)

Here's one option that should also work (though I'm not sure if that is what 
you mean with point 2 of your list):

def subclass(base):
class Z(base):
def methodX(self):
print "overridden methodX"
return Z

Z = subclass(A)
Z2 = subclass(A2)

> Please note that the bpaste code is just an example. The real problem is
> much bigger and involves multiple methods to override and more classes, so
> the solution has to scale accordingly.


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


Re: base64.b64encode(data)

2016-06-13 Thread Steven D'Aprano
On Mon, 13 Jun 2016 03:33 pm, Random832 wrote:

> Why do you say these things like you assume I will agree with them.


Because I gave you the benefit of the doubt that you were a reasonable
person open to good-faith discussion, rather than playing John Cleese's
role in your own personal version of the Argument Sketch :-)

I don't mind if you say "Well I'm a telecommunications engineer, and when we
talk about text protocols, this is what I mean." If I ever find myself in a
forum of telco engineers, I'll learn to use their definition too.

But this is a Python forum, and Python 3 is a language that tries very, very
hard to keep a clean separation between bytes and text, where text is
understood to mean Unicode, not a subset of ASCII-encoded bytes. Python 2
was quite happy to let the two categories bleed into each other, with
disastrous effects.

When I first started using computers, the PC world assumed that "text" meant
an ASCII-compatible subset of bytes. One character = one byte, and 'A'
meant byte 0x41 (in hex; in decimal it would be 65). Most of our wire
protocols make that same assumption, and some older file formats (like
HTML) do the same. They're remnants from a bygone age where you could get
away with calling the sequence of bytes 

48 65 6C 6C 6F 20 57 6F 72 6C 64 21

"text", because everyone[1] agreed on the same interpretation of those
bytes, namely "Hello World!". But that's no longer the case, and hasn't
been for, well to be honest it was *never* the case that 0x48 unambiguously
meant 'H', and it is certainly not the case now.

The bottom line is that critical use-cases for base64 involve transmitting
bytes, not writing arbitrary Unicode, and that's why the base64 module is
treated as a bytes to bytes transformation in Python. You can argue with me
all you like, but the docs explicitly call it this:

https://docs.python.org/3/library/codecs.html#binary-transforms

and even in Python 2 it is called "str to str", where str is understood to
be bytes-string, not Unicode:

https://docs.python.org/2/library/codecs.html#standard-encodings



And besides I've only paid for the ten minute argument.





[1] Apart from those guys using IBM mainframes. And people in foreign parts,
where they speak weird outlandish languages with bizarre characters, like
England. And users of earlier versions of ASCII, or users of variants of
ASCII that differ ever so slightly differently.


-- 
Steven

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


passing dictionay as argument

2016-06-13 Thread Arshpreet Singh
I have to pass dictionary as function argument for following code:


import authorize

authorize.Configuration.configure(
authorize.Environment.TEST,
'api_login_id',
'api_transaction_key',
)

result = authorize.Transaction.sale({
'amount': 40.00,

'credit_card': {
'card_number': '4111',
'expiration_date': '04/2014',
'card_code': '343',
}

})

result.transaction_response.trans_id



I want to define 'credit-card' dictionary as argument in the function as 
follows but it returns syntax error:



# define dictionary outside the function call: 
credit_card={
'card_number': '4111',
'expiration_date': '04/2014',
'card_code': '343',
}

import authorize

authorize.Configuration.configure(
authorize.Environment.TEST,
'api_login_id',
'api_transaction_key',
)

result = authorize.Transaction.sale({'amount': 40.00,credit_card})

result.transaction_response.trans_id

it returns following error:

result = authorize.Transaction.sale({40.00,credit_card})
TypeError: unhashable type: 'dict'

Do I need to make changes in authorize.Transaction.sale() source code?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: passing dictionay as argument

2016-06-13 Thread David Navarro
To be equivalent to the other one it should be:

result = authorize.Transaction.sale({'amount': 40.00, 'credit_card':
credit_card})

In this line:
result = authorize.Transaction.sale({40.00,credit_card})

You are not putting keys in the dictionary. If there are no keys Python
creates a 'set literal'. The error you are seeing is failing to create the
set (sets require all their elements to be hashable and dictionaries
aren't).

If you use the line at the beginning of the mail it should work.

On 13 June 2016 at 12:54, Arshpreet Singh  wrote:

> I have to pass dictionary as function argument for following code:
>
> 
> import authorize
>
> authorize.Configuration.configure(
> authorize.Environment.TEST,
> 'api_login_id',
> 'api_transaction_key',
> )
>
> result = authorize.Transaction.sale({
> 'amount': 40.00,
>
> 'credit_card': {
> 'card_number': '4111',
> 'expiration_date': '04/2014',
> 'card_code': '343',
> }
>
> })
>
> result.transaction_response.trans_id
>
> 
>
> I want to define 'credit-card' dictionary as argument in the function as
> follows but it returns syntax error:
>
> 
>
> # define dictionary outside the function call:
> credit_card={
> 'card_number': '4111',
> 'expiration_date': '04/2014',
> 'card_code': '343',
> }
>
> import authorize
>
> authorize.Configuration.configure(
> authorize.Environment.TEST,
> 'api_login_id',
> 'api_transaction_key',
> )
>
> result = authorize.Transaction.sale({'amount': 40.00,credit_card})
>
> result.transaction_response.trans_id
>
> it returns following error:
>
> result = authorize.Transaction.sale({40.00,credit_card})
> TypeError: unhashable type: 'dict'
>
> Do I need to make changes in authorize.Transaction.sale() source code?
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
David Navarro Estruch
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: passing dictionay as argument

2016-06-13 Thread Frank Millman
"Arshpreet Singh"  wrote in message 
news:0b6372ce-3f16-431b-9e72-42d5c935d...@googlegroups.com...



I have to pass dictionary as function argument for following code:


[...]


result = authorize.Transaction.sale({
'amount': 40.00,

'credit_card': {
'card_number': '4111',
'expiration_date': '04/2014',
'card_code': '343',
}



[...]

I want to define 'credit-card' dictionary as argument in the function as 
follows but it returns syntax error:


# define dictionary outside the function call:
credit_card={
'card_number': '4111',
'expiration_date': '04/2014',
'card_code': '343',
}



[...]


result = authorize.Transaction.sale({'amount': 40.00,credit_card})


Try this -

   result = authorize.Transaction.sale({'amount': 40.00, 
'credit_card':credit_card})


Frank Millman


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


Re: passing dictionay as argument

2016-06-13 Thread marco . nawijn
On Monday, June 13, 2016 at 12:54:45 PM UTC+2, Arshpreet Singh wrote:
> I have to pass dictionary as function argument for following code:
> 
> 
> import authorize
> 
> authorize.Configuration.configure(
> authorize.Environment.TEST,
> 'api_login_id',
> 'api_transaction_key',
> )
> 
> result = authorize.Transaction.sale({
> 'amount': 40.00,
> 
> 'credit_card': {
> 'card_number': '4111',
> 'expiration_date': '04/2014',
> 'card_code': '343',
> }
> 
> })
> 
> result.transaction_response.trans_id
> 
> 
> 
> I want to define 'credit-card' dictionary as argument in the function as 
> follows but it returns syntax error:
> 
> 
> 
> # define dictionary outside the function call: 
> credit_card={
> 'card_number': '4111',
> 'expiration_date': '04/2014',
> 'card_code': '343',
> }
> 
> import authorize
> 
> authorize.Configuration.configure(
> authorize.Environment.TEST,
> 'api_login_id',
> 'api_transaction_key',
> )
> 
> result = authorize.Transaction.sale({'amount': 40.00,credit_card})
> 
> result.transaction_response.trans_id
> 
> it returns following error:
> 
> result = authorize.Transaction.sale({40.00,credit_card})
> TypeError: unhashable type: 'dict'
> 
> Do I need to make changes in authorize.Transaction.sale() source code?

You explicitly need to specify the key for credit_card in the
call to sale(..). I have not run the code myself, but I believe it
will work like this:

result = authorize.Transaction.sale({'amount': 40.00,'credit_card': 
credit_card}) 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Ian Kelly
On Mon, Jun 13, 2016 at 1:13 AM, dieter  wrote:
> alanquei...@gmail.com writes:
>
>> I'm trying to override methods inherited from a superclass by methods 
>> defined in a mixin class.
>> Here's an sscce:
>> https://bpaste.net/show/6c7d8d590658 (never expires)
>>
>> I've had problems finding the proper way to do that, since at first the base 
>> class wasn't to the right and I've assumed the correct order was from left 
>> to right.
>
> The class' MRO ("Method Resolution Order") determines in which
> order attributes are looked up.
> Either, you must order your base classes in such a way that the MRO
> controlled lookup finds the methods you want to be used or
> you must explicitely put a definition for those methods in your
> derived class (it may have the form "overridden_method = 
> .overridden_method").
>
> The rules to determine the MRO are complex. The "inspect" module contains
> a function ("get_mro") to show the MRO of a given class. Use it
> to get your inheritance order right.

The details are complex, but there are two fairly simple principles
that can be relied upon:

1) Subclasses always appear before their superclasses in the MRO.
2) When a class inherits from multiple base classes, they will always
appear in the MRO in the order they appear in the class statement from
left-to-right.

Note that neither of these rules guarantee that the classes will
appear *sequentially* in the MRO.

So in the case of mixins, listing the mixin class first is absolutely correct:

class Derived(Mixin, Base): pass

This ensures that Mixin will always appear before Base in the MRO (and
thus override Base's methods) for Derived and for any subclass of
Derived.

It is possible to concoct elaborate inheritance hierarchies in which
it is not possible to come up with an MRO that will satisfy both 1)
and 2) above. In such cases, it is also useful to know what Python
will do. Fortunately, the answer to that is also simple: the type
constructor will throw an exception. So this isn't something that
really needs to be worried about.
-- 
https://mail.python.org/mailman/listinfo/python-list


Conversion: execfile --> exec

2016-06-13 Thread Long Yang
The python 2.x command is as following:
---
info = {}
execfile(join('chaco', '__init__.py'), info)
--

But execfile has been removed in python 3.x.
So my problem is how to convert the above to a 3.x based command?

thanks very much
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Altering sys.argv on startup in Python 2

2016-06-13 Thread Adam Bartoš
Thank you very much, the hook gets invoked at the right place.

Adam Bartoš
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: base64.b64encode(data)

2016-06-13 Thread Random832
On Mon, Jun 13, 2016, at 06:35, Steven D'Aprano wrote:
> But this is a Python forum, and Python 3 is a language that tries
> very, very hard to keep a clean separation between bytes and text,

Yes, but that doesn't mean that you're right about which side of that
divide base64 output belongs on.

> where text is understood to mean Unicode, not a subset of ASCII-
> encoded bytes.

Sure. But let's not pretend that U+0020 through U+007E *aren't* unicode
characters. Base 64's output is characters. Those characters could be
encoded as ASCII, as UTF-32, as EBCDIC, and they would still be the same
characters.

At
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/uuencode.html
you can see in the rationale section a specific mention of using base64
with EBCDIC, and that the characters are all invariant across all EBCDIC
encodings being part of the reason for base64 using the characters it
does (as opposed to the historical uuencode algorithm's 0x20 through
0x5F, or as opposed to using some other non-alphanumeric characters than
+ / =)

The fact that many historical standards do mix text with ASCII-encoded
bytes and treat them interchangeably, as you said, does that you have to
read carefully to see which one they mean. The problem with your
argument, though, is that in base64's case it clearly *is* text. For
example, from the original privacy-enhanced mail standards - the very
first application of base64:

RFC 989:

"1.   (Local_Form) The message text is created (e.g., via an editor)
  in the system's native character set, with lines delimited in
  accordance with local convention."

RFC 1421:

"A plaintext message
   is accepted in local form, using the host's native character set and
   line representation."

And specifically in its description of base64 ("printable encoding"):

"Proceeding from
   left to right, the bit string resulting from step 3 is encoded into
   characters which are universally representable at all sites, though
   not necessarily with the same bit patterns (e.g., although the
   character "E" is represented in an ASCII-based system as hexadecimal
   45 and as hexadecimal C5 in an EBCDIC-based system, the local
   significance of the two representations is equivalent)."
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Conversion: execfile --> exec

2016-06-13 Thread MRAB

On 2016-06-13 14:24, Long Yang wrote:

The python 2.x command is as following:
---
info = {}
execfile(join('chaco', '__init__.py'), info)
--

But execfile has been removed in python 3.x.
So my problem is how to convert the above to a 3.x based command?

thanks very much


Open the file and pass it to exec:

info = {}
with open(join('chaco', '__init__.py')) as file:
exec(file.read(), info)

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


Re: Conversion: execfile --> exec

2016-06-13 Thread Rustom Mody
On Monday, June 13, 2016 at 7:41:33 PM UTC+5:30, MRAB wrote:
> On 2016-06-13 14:24, Long Yang wrote:
> > The python 2.x command is as following:
> > ---
> > info = {}
> > execfile(join('chaco', '__init__.py'), info)
> > --
> >
> > But execfile has been removed in python 3.x.
> > So my problem is how to convert the above to a 3.x based command?
> >
> > thanks very much
> >
> Open the file and pass it to exec:
> 
> info = {}
> with open(join('chaco', '__init__.py')) as file:
>  exec(file.read(), info)


I wonder whether this should use importlib instead [yeah really wondering...
not a rhetorical question]

See slide 38-40 http://www.slideshare.net/pydanny/python-worst-practices
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: base64.b64encode(data)

2016-06-13 Thread Michael Torrie
On 06/12/2016 11:16 PM, Steven D'Aprano wrote:
> "Safe to transmit in text protocols" surely should mean "any Unicode code
> point", since all of Unicode is text. What's so special about the base64
> ones?
> 
> Well, that depends on your context. For somebody who cares about sending
> bits over a physical wire, their idea of "text" is not Unicode, but a
> subset of ASCII *bytes*.

Not necessarily.  The encoding of the text containing the results of the
base64 encoding does not matter provided the letters and numbers used in
base64 can be represented.  I could take the text and paste it in an
email and send it via UTF-8, or UTF-16.  Won't make a difference
provided the decoder can deal decode that specific unicode encoding.
The other end could even cut and paste the base64 letters and numbers
out of his email body and paste it into a decoder. How the letters and
numbers got to him is immaterial and irrelevant.

Sure in the context of email base64 data is usually sent using UTF-8
encoding these days.  But there's no requirement that base64 data always
has to be encoded in ASCII, UTF-8, or LATIN1.

> The end result is that after you've base64ed your "binary" data, to
> get "text" data, what are you going to do with is? Treat it as Unicode code
> points? Probably not. 

Sure. Why not?  Write it to a text file.  Put it in an email.  Place it
in a word doc.  Print it.  Whatever.

> Squirt it down a wire as bytes? Almost certainly.

Sometimes yes.  But not always.

> Looking at this from the high-level perspective of Python, that makes it
> conceptually bytes not text.

I don't see how this is always the case.  From a high-level python
perspective it's definitely text.  That's the whole point of base64!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: base64.b64encode(data)

2016-06-13 Thread Chris Angelico
On Tue, Jun 14, 2016 at 1:15 AM, Michael Torrie  wrote:
>> Looking at this from the high-level perspective of Python, that makes it
>> conceptually bytes not text.
>
> I don't see how this is always the case.  From a high-level python
> perspective it's definitely text.  That's the whole point of base64!

Maybe what Python needs is an "ascii" type that's a subclass of both
str and bytes, and requires that the contents be <0x80. It is text, so
it can be combined with text strings; but it is also bytes, so when
you combine it with bytes strings, it'll behave as most people expect.

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


Re: Conversion: execfile --> exec

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016, 10:36 AM Rustom Mody  wrote:

> On Monday, June 13, 2016 at 7:41:33 PM UTC+5:30, MRAB wrote:
> > On 2016-06-13 14:24, Long Yang wrote:
> > > The python 2.x command is as following:
> > > ---
> > > info = {}
> > > execfile(join('chaco', '__init__.py'), info)
> > > --
> > >
> > > But execfile has been removed in python 3.x.
> > > So my problem is how to convert the above to a 3.x based command?
> > >
> > > thanks very much
> > >
> > Open the file and pass it to exec:
> >
> > info = {}
> > with open(join('chaco', '__init__.py')) as file:
> >  exec(file.read(), info)
>
>
> I wonder whether this should use importlib instead [yeah really
> wondering...
> not a rhetorical question]
>
> See slide 38-40 http://www.slideshare.net/pydanny/python-worst-practices


The slides you're referencing are saying importlib is better than exec'ing
an import. The question of this thread was more general. An import makes a
module object, but exec'ing arbitrary source does not (unless it uses
import).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 12:01 AM  wrote:

> I haven't used Python for some time so I don't feel confident to judge
>

Yet, you are clearly judging the code you pasted as not OK.

Perhaps you guys could help me either convincing me that the bpaste code is
> OK
>

It would be helpful for you to explain why you think the code you pasted is
not OK. To me it makes sense. English reads left-to-right, so method
lookups go left-to-right (and children before parents) in the inheritance
list.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Conversion: execfile --> exec

2016-06-13 Thread Rustom Mody
On Monday, June 13, 2016 at 10:48:33 PM UTC+5:30, Michael Selik wrote:
> On Mon, Jun 13, 2016, 10:36 AM Rustom Mody  wrote:
> 
> > On Monday, June 13, 2016 at 7:41:33 PM UTC+5:30, MRAB wrote:
> > > On 2016-06-13 14:24, Long Yang wrote:
> > > > The python 2.x command is as following:
> > > > ---
> > > > info = {}
> > > > execfile(join('chaco', '__init__.py'), info)
> > > > --
> > > >
> > > > But execfile has been removed in python 3.x.
> > > > So my problem is how to convert the above to a 3.x based command?
> > > >
> > > > thanks very much
> > > >
> > > Open the file and pass it to exec:
> > >
> > > info = {}
> > > with open(join('chaco', '__init__.py')) as file:
> > >  exec(file.read(), info)
> >
> >
> > I wonder whether this should use importlib instead [yeah really
> > wondering...
> > not a rhetorical question]
> >
> > See slide 38-40 http://www.slideshare.net/pydanny/python-worst-practices
> 
> 
> The slides you're referencing are saying importlib is better than exec'ing
> an import. The question of this thread was more general. An import makes a
> module object, but exec'ing arbitrary source does not (unless it uses
> import).


True but the supplied code:
info = {}
execfile(join('chaco', '__init__.py'), info) 

looks (to me) like an intent to import the package chaco with no locals and 
globals -- Just guessing of course
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread alanqueiros
Thank you for your replies. I don't know if I'm quoting you correctly, I'm 
quite confused with Google Groups... not sure if it's a "forum", something like 
a mailing list, or both... or neither.

> The class' MRO ("Method Resolution Order") determines in which
> order attributes are looked up.
> Either, you must order your base classes in such a way that the MRO
> controlled lookup finds the methods you want to be used or
> you must explicitely put a definition for those methods in your
> derived class (it may have the form "overridden_method = 
> .overridden_method").
> 
> The rules to determine the MRO are complex. The "inspect" module contains
> a function ("get_mro") to show the MRO of a given class. Use it
> to get your inheritance order right.

OK, I'm going to read about the MRO rules. Thanks for the heads up on the 
inspect module.



> But the code is fine. Write unit tests to ensure that the correct method is 
> called.
> 
> Usually you use mixins to add methods. In that case the order of base 
> classes doesn't matter.

Yeah, I see that in most cases the order doesn't matter, but still I would 
think that since the correct order is from right to left, that should be the 
common practice. What if later on you want to expand a mixin and actually 
override a method? That could cause a situation that's a hell to debug, so 
people should just get used to keeping their (most) "base" classes to the right 
when doing multiple inheritance in my opinion.
 
> That looks like you are actively excluding most alternatives ;)
> 
> Here's one option that should also work (though I'm not sure if that is what 
> you mean with point 2 of your list):
> 
> def subclass(base):
> class Z(base):
> def methodX(self):
> print "overridden methodX"
> return Z
> 
> Z = subclass(A)
> Z2 = subclass(A2)
> 

Yes, that violates the second item :). That would increase the complexity of 
the code because I would need to know which A to use when instantiating the 
classes, and what I'm doing is exactly to simplify the usage of those classes. 
Of course some docs and perhaps a well tailored enum (or alike) to be passed as 
the parameter could help, but a factory could do just as well, however, that 
isn't going to fulfill my needs at all, and since I'm the one who's going to 
use the code most of the time, I don't care much about using something somewhat 
"unconventional".



> The details are complex, but there are two fairly simple principles
> that can be relied upon:
> 
> 1) Subclasses always appear before their superclasses in the MRO.
> 2) When a class inherits from multiple base classes, they will always
> appear in the MRO in the order they appear in the class statement from
> left-to-right.
> 
> Note that neither of these rules guarantee that the classes will
> appear *sequentially* in the MRO.
> 
> So in the case of mixins, listing the mixin class first is absolutely correct:
> 
> class Derived(Mixin, Base): pass
> 
> This ensures that Mixin will always appear before Base in the MRO (and
> thus override Base's methods) for Derived and for any subclass of
> Derived.
> 
> It is possible to concoct elaborate inheritance hierarchies in which
> it is not possible to come up with an MRO that will satisfy both 1)
> and 2) above. In such cases, it is also useful to know what Python
> will do. Fortunately, the answer to that is also simple: the type
> constructor will throw an exception. So this isn't something that
> really needs to be worried about.

That's some very nice information you got there. I also like how Ian Lewis 
explained that, it may not be very technical and perhaps that "logic" is 
accidental, but it surely helps you remember the correct order when doing 
multiple inheritance. (That part about forgetting the brackets and thinking of 
the code as a lined-up hierarchy, so MyClass => Mixin2 => Mixin1 => BaseClass).
In my opinion Python users should get used to that order. It doesn't matter if 
*atm* you're not overriding, if that's the correct way to do it, you should get 
used to it in my opinion because who know how you may need/want to expand your 
code in the future. Still, pretty much *no one* uses that order. A quick Google 
search returns (at least in my "bubble") many blog articles from "notable" 
Python users with that order wrong.

As long as I can rely on that it's OK for me. I couldn't find anything 
"official" on that subject though (mixins that override).



> Yet, you are clearly judging the code you pasted as not OK.

Actually, I didn't say (hard and fast) the code wasn't OK (if memory serves), I 
said I didn't like it -on a first superficial analysis-. Especially due the 
lack of recent experience with Python I was afraid I wasn't seeing some obvious 
caveat, thus I've basically asked you guys to tell me if the code is or isn't 
OK.

> It would be helpful for you to explain why you think the code you pasted is
> not OK. To me it makes sense. English reads 

Re: Conversion: execfile --> exec

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 1:51 PM Rustom Mody  wrote:

> looks (to me) like an intent to import the package chaco with no locals
> and globals -- Just guessing of course
>

And without creating a module object. I suppose that means it doesn't get
cached in sys.modules either. Not sure if that's a feature or a bug.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Gregory Ewing

alanquei...@gmail.com wrote:

I see that in most cases the order doesn't matter, but still I would
think that since the correct order is from right to left, that should be the
common practice.


This order is only "correct" if overriding is what you want.
That's not always going to be the case. The mixin might be
intended to supply default functionality that can be
overridden by the classes it's being mixed into. You
can't say that one order is more correct than the other
in general.

> Basically, I

think of the mixins like plugins of kinds, I'm "adding" functionality to that
"base" class I'm inheriting from. Having them to the left sounds like a
sandwich recipe that tells you to "slice the ham, put mayonnaise on it, and
put it on the bread".


To me it's more like adding seasoning to a dish. Normally
you put the main ingredient in first, then add the salt
and pepper. This is probably the way most people are
thinking when they write the mixins after the main base
class.

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


Looking for Python Engineering Manager or Python experts for world's leading Artificial Intelligence Company in San Francisco,CA

2016-06-13 Thread pankaj
Hi,

I am looking to hire for an excellent opportunity for an Python Engineering 
Manager or Python experts for world's leading Arti-0878ficial Intelligence 
Company in San Francisco,CA. 

Please do refer or contact me at cell 510-396-0878. Both Full time Perm and 
Contract opportunities are open. Appreciate any help. 

Thanks so much,

Pankaj 
Director Best Practices
Openmind Technologies Inc
Cell 510-396-0878.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 2:46 PM  wrote:

> Thank you for your replies. I don't know if I'm quoting you correctly, I'm
> quite confused with Google Groups... not sure if it's a "forum", something
> like a mailing list, or both... or neither.
>

Mailing list. A "forum" in the metaphorical sense, not the sense of phpBB.
You're doing fine with quoting, though it would help to add who said what
when quoting multiple people.

since the correct order is from right to left,


Did you mean left-to-right?
Are you thinking of Java where there's only one parent class allowed and
you specify any extra interfaces you're implementing afterwards? Because
that's not what your code is doing.

Still, pretty much *no one* uses that order [mixin1, mixin2, base]. A quick
> Google search returns (at least in my "bubble") many blog articles from
> "notable" Python users with that order wrong.
>

Do you mind providing links? I haven't seen anyone "notable" make this
mistake.


> > To me it makes sense. English reads left-to-right, so method
>
> lookups go left-to-right (and children before parents) in the inheritance
> > list.
>
> Basically I wasn't very confident the code was OK because my intuition
> said the right way to order the classes I was inheriting from was from left
> to right.


That is correct! Write them in the order you are prioritizing the
definitions. Overrides before bases, left to right.


> I don't see any sense in that analogy you made... sure English and most
> occidental languages read ltr, but I fail to see how it makes more sense to
> have the base class on the right and the mixins on the left. Basically, I
> think of the mixins like plugins of kinds, I'm "adding" functionality to
> that "base" class I'm inheriting from.


That's not a good metaphor for what's actually happening. For more detail,
check out Raymond's "super considered super" video (
https://www.youtube.com/watch?v=EiOglTERPEo).


> Don't take my word for it, Google multi inheritance or mixin in Python and
> let me know if you find someone who thinks it's "natural" to do it that way.


This might be a bit of selection bias. People who think it makes sense
might not have an incentive to write a blog post about it. People who don't
like it will thus be more vocal.

Ian Lewis seems to be ranked highly by Google (
https://www.ianlewis.org/en/mixins-and-python).
I disagree with his assertion that "most people" read an inheritance
hierarchy top-down with the bases at the left. I think of inheritance as a
tree. Even if it is a diamond at some point, a depth-first-search of a tree
isn't far off from the truth. The root (base) is at the bottom, in my mind,
and the leaves are at the top.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: base64.b64encode(data)

2016-06-13 Thread Gregory Ewing

Michael Torrie wrote:

On 06/12/2016 11:16 PM, Steven D'Aprano wrote:


Squirt it down a wire as bytes? Almost certainly.


Sometimes yes.  But not always.


And even when the ultimate destination is a wire, a Python
programmer is more likely to be accessing the wire through
some high-level interface that accepts the payload to be
sent as text in the form of a Python str object.

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


Re: base64.b64encode(data)

2016-06-13 Thread Gregory Ewing

Chris Angelico wrote:

Maybe what Python needs is an "ascii" type that's a subclass of both
str and bytes, and requires that the contents be <0x80. It is text, so
it can be combined with text strings; but it is also bytes, so when
you combine it with bytes strings, it'll behave as most people expect.


That would be asking for trouble, I think. It would be
letting back in a bit of the text/bytes confusion that
Python 3 worked hard to get rid of. What happens if the
bytes that you combine it with aren't in an ascii-compatible
encoding? Nothing would detect that error.

The only thing you might gain is a bit of efficiency by
removing some encoding/decoding operations. But since the
FSR, these are pretty cheap anyway when the characters are all
ascii.

They could maybe be made a bit cheaper still by arranging
some way for a bytes object and an ascii-only str object
to share underlying storage.

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


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread alanqueiros
On Monday, June 13, 2016 at 7:29:05 PM UTC-3, Gregory Ewing wrote:
> > I see that in most cases the order doesn't matter, but still I would
> > think that since the correct order is from right to left, that should be the
> > common practice.
> 
> This order is only "correct" if overriding is what you want.
> That's not always going to be the case. The mixin might be
> intended to supply default functionality that can be
> overridden by the classes it's being mixed into. You
> can't say that one order is more correct than the other
> in general.

Yes, but (I presume) ordering it rtl doesn't have any caveat, and the code gets 
'future-proof' in case you want to override a method in a class that's intended 
to be used as a mixin. I for instance am making an effort to get used to the 
rtl order as quickly as possible. But sure, in most cases it's probably never 
going to make a difference.
 
>  > Basically, I
> > think of the mixins like plugins of kinds, I'm "adding" functionality to 
> > that
> > "base" class I'm inheriting from. Having them to the left sounds like a
> > sandwich recipe that tells you to "slice the ham, put mayonnaise on it, and
> > put it on the bread".
> 
> To me it's more like adding seasoning to a dish. Normally
> you put the main ingredient in first, then add the salt
> and pepper. This is probably the way most people are
> thinking when they write the mixins after the main base
> class.

Exactly.



On Monday, June 13, 2016 at 7:51:14 PM UTC-3, Michael Selik wrote:
> > Thank you for your replies. I don't know if I'm quoting you correctly, I'm
> > quite confused with Google Groups... not sure if it's a "forum", something
> > like a mailing list, or both... or neither.
> >
> 
> Mailing list. A "forum" in the metaphorical sense, not the sense of phpBB.
> You're doing fine with quoting, though it would help to add who said what
> when quoting multiple people.
> 
> > since the correct order is from right to left,
> 
> 
> Did you mean left-to-right?
> Are you thinking of Java where there's only one parent class allowed and
> you specify any extra interfaces you're implementing afterwards? Because
> that's not what your code is doing.

Nope, I'm certainly not thinking of interfaces of abstract classes, I'm 
literally thinking about mixins.

> > Still, pretty much *no one* uses that order [mixin1, mixin2, base]. A quick
> > Google search returns (at least in my "bubble") many blog articles from
> > "notable" Python users with that order wrong.
> >
> 
> Do you mind providing links? I haven't seen anyone "notable" make this
> mistake.

Not at all. Of course the snippets work because they're not overriding, but 
they all use an 'ltr' order. I feel somewhat bad about posting these links 
because I don't want to imply the code is wrong or something, since apparently 
there's no convention on that. So I'm publishing this list with all due respect 
to the programmers, and this only proves that it's probably more intuitive for 
most people to put is as [base,mixin]:

class Request(BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, 
AuthorizationMixin):
http://stackoverflow.com/a/547714

class RealTestCase(BaseTestCase, MyMixin):
http://nedbatchelder.com/blog/201210/multiple_inheritance_is_hard.html

class TextBook(Book, IndexMixin):
https://ahal.ca/blog/2014/when-would-you-use-python-mixin/

> > > To me it makes sense. English reads left-to-right, so method
> >
> > lookups go left-to-right (and children before parents) in the inheritance
> > > list.
> >
> > Basically I wasn't very confident the code was OK because my intuition
> > said the right way to order the classes I was inheriting from was from left
> > to right.
> 
> That is correct! Write them in the order you are prioritizing the
> definitions. Overrides before bases, left to right.

I'm sorry but it doesn't seem that obvious to me... It feels like building a 
house starting from the roof to me. Of course that's entirely subjective.

> > I don't see any sense in that analogy you made... sure English and most
> > occidental languages read ltr, but I fail to see how it makes more sense to
> > have the base class on the right and the mixins on the left. Basically, I
> > think of the mixins like plugins of kinds, I'm "adding" functionality to
> > that "base" class I'm inheriting from.
> 
> 
> That's not a good metaphor for what's actually happening. For more detail,
> check out Raymond's "super considered super" video (
> https://www.youtube.com/watch?v=EiOglTERPEo).

I'm going to take a look. Thank you for the link.

> > Don't take my word for it, Google multi inheritance or mixin in Python and
> > let me know if you find someone who thinks it's "natural" to do it that way.
> 
> 
> This might be a bit of selection bias. People who think it makes sense
> might not have an incentive to write a blog post about it. People who don't
> like it will thus be more vocal.

Yes, or maybe it's just my Google results that are biased.

> Ian Lewi

Re: for / while else doesn't make sense

2016-06-13 Thread Michael Selik
On Sun, Jun 12, 2016 at 10:16 PM Steven D'Aprano 
wrote:

> On Mon, 13 Jun 2016 04:44 am, Michael Selik wrote:
>
> > On Sun, Jun 12, 2016 at 6:11 AM Steven D'Aprano <
> > steve+comp.lang.pyt...@pearwood.info> wrote:
> >
> >> - run the for block
> >> - THEN unconditionally run the "else" block
> >>
> >
> > Saying "unconditionally" is a bit misleading here. As you say, it's
> > conditioned on completing the loop without break/return/raise.
>
> It's also conditional on the OS not killing the Python process, conditional
> on the CPU not catching fire, conditional on the user not turning the power
> of, and conditional on the sun not exploding and disintegrating the entire
> earth.
>
> In the absence of any event which interferes with the normal execution of
> code by the Python VM, and in the absence of one of a very few
> explicit "JUMP" statements which explicitly jump out of the compound
> for...else statement, the else clause is unconditionally executed after the
> for clause.
>
> Happy now?
>

I think most folks assume that their program will not run as expected if
the sun explodes.

Saying that ``raise``, ``break``, and ``return`` are "one of a very few
explicit JUMP statements" implies that they are obscure. Listing them in
addition to the sun exploding suggests that you think they are similarly
unlikely and should be ignored as too bizarre to consider.

In contrast, I think raise, break, and return are quite common. Further, I
think you do too, despite what you are trying to imply. Maybe I read the
tone wrong. It's tough sometimes to hear someone's tone of voice in email.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods inherited from a superclass with methods from a mixin

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 7:46 PM  wrote:

> I ... am making an effort to get used to the rtl order as quickly as
> possible.
>

Funny, you keep saying right-to-left. I think the issue is you think the
parent class is more important. Fight the power! Youth revolt! In Python,
the children are in control. Now you can read it left-to-right, as is
natural.

I feel somewhat bad about posting these links
>

The StackOverflow answer had an upvoted comment that the BaseRequest should
be written after the Mixins. The two blog posts read like conversation
starters. I don't think the authors intended to write model code.

A famous textbook getting it wrong would be more interesting. But even
Knuth makes mistakes (https://en.wikipedia.org/wiki/Knuth_reward_check).
-- 
https://mail.python.org/mailman/listinfo/python-list


Please use the Python Job Board for recruiting (was: [recruitment message])

2016-06-13 Thread Ben Finney
pan...@openmindtechno.com writes:

> I am looking to hire for an excellent opportunity

Please do not use this forum for recruiting. Instead, use the Python Job
Board https://www.python.org/community/jobs/> maintained for that
purpose.

-- 
 \  “The fact that I have no remedy for all the sorrows of the |
  `\ world is no reason for my accepting yours. It simply supports |
_o__)  the strong probability that yours is a fake.” —Henry L. Mencken |
Ben Finney 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: base64.b64encode(data)

2016-06-13 Thread Random832
On Mon, Jun 13, 2016, at 19:12, Gregory Ewing wrote:
> They could maybe be made a bit cheaper still by arranging
> some way for a bytes object and an ascii-only str object
> to share underlying storage.

While we're at it, why not allow bytes to share storage with FSR latin-1
strings and the cached UTF-8 versions of strings?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: for / while else doesn't make sense

2016-06-13 Thread Steven D'Aprano
On Tue, 14 Jun 2016 09:45 am, Michael Selik wrote:

> On Sun, Jun 12, 2016 at 10:16 PM Steven D'Aprano 
> wrote:
> 
>> On Mon, 13 Jun 2016 04:44 am, Michael Selik wrote:
>>
>> > On Sun, Jun 12, 2016 at 6:11 AM Steven D'Aprano <
>> > steve+comp.lang.pyt...@pearwood.info> wrote:
>> >
>> >> - run the for block
>> >> - THEN unconditionally run the "else" block
>> >>
>> >
>> > Saying "unconditionally" is a bit misleading here. As you say, it's
>> > conditioned on completing the loop without break/return/raise.
>>
>> It's also conditional on the OS not killing the Python process,
>> conditional on the CPU not catching fire, conditional on the user not
>> turning the power of, and conditional on the sun not exploding and
>> disintegrating the entire earth.
>>
>> In the absence of any event which interferes with the normal execution of
>> code by the Python VM, and in the absence of one of a very few
>> explicit "JUMP" statements which explicitly jump out of the compound
>> for...else statement, the else clause is unconditionally executed after
>> the for clause.
>>
>> Happy now?
>>
> 
> I think most folks assume that their program will not run as expected if
> the sun explodes.

On this list, I daresay somebody will insist that if their computer is on
one of Jupiter's moons it will keep running fine and therefore I'm wrong.


> Saying that ``raise``, ``break``, and ``return`` are "one of a very few
> explicit JUMP statements" implies that they are obscure. 

What? No. How do you get that?

If I tell you that Python has only two loop constructs, for and while, would
that imply that they are rare and unusual? (Three if you count
comprehensions as distinct from the for statement.)

Python has only two conditional branches: if...elif..else, and the ternary
if operator. Does that make them obscure?

raise, break and return are all explicit JUMPs: they transfer execution to
some place other than the next executable line. There are others, including
continue, but they don't transfer execution past the for loop, so don't
matter in this context. None of this implies that they are obscure. I'm
sorry if you've never thought of a return or break as a JUMP before, but
that's what they are.


> Listing them in 
> addition to the sun exploding suggests that you think they are similarly
> unlikely and should be ignored as too bizarre to consider.

No. The sun exploding was me gently mocking you for your comment disputing
the "unconditional" part. Yes, you are technically right that technically
the "else" block will only run if no "break" is reached, and no "return" is
reached, no exception is raised, also that os._exit or os.abort aren't
called, the CPU doesn't catch fire, and the world isn't destroyed.

If we try to enumerate all the things which could prevent the "else" block
from running, we'll be here for decades. But, and this is the point that
everyone seems to have missed, * every single one of those things* is
completely independent of the for...else statement.

*Including* the presence or absence of a "break".

If you want to understand how Python statements work, you should understand
them in isolation (as much as possible), which then allows you to
extrapolate their behaviour in combination with other statements. Most
lines of Python code are understandable in isolation, or at least close to
isolation. You can get *very close* to a full understanding of Python by
just reading one line at a time (with perhaps a bit of short term memory to
remember if you are compiling a function, building a class, etc).

E.g. you don't need to understand for loops to understand if...else.

And vice versa: for...else has a well-defined meaning and operates in a
simple fashion in isolation of other language features. Its not compulsory
to put a "return" statement inside your for loop. Nor is it compulsory to
put a "raise" inside it. And "break" is not compulsory either.

If you think of for...else as being (in some sense) glued to break, then
what are you going to make of code with for...else and no break? That's
legal Python code, and somebody will write it, even if only by accident.

If you think of for...else as being glued to an if inside the for block,
then what are you going to make of code where the if already has an else?
Or code that unconditionally breaks inside the loop? Again, that's legal
code, even if useless. If you think that the for...else has to match an if
inside the loop, you'll have to invent special rules for when there is no
if, or ten of them, or they all are already matched with their own elses.

If you start thinking of it as code which is run conditionally "only if no
break was executed", that leads to people thinking of it in terms of some
sort of hidden flag that Python keeps to tell whether or not a break was
seen. A month or two ago, we had somebody, mislead by that mental model,
asking whether Python should expose that flag so he could write code
something like:

for x in seq:
   do_stuff()
else:
   do_som

Re: Indentation example?

2016-06-13 Thread ICT Ezy
On Monday, June 13, 2016 at 3:09:15 AM UTC+5:30, Marc Dietz wrote:
> On Sun, 12 Jun 2016 08:10:27 -0700 ICT Ezy wrote:
> 
> > Pl explain with an example the following phase "Indentation cannot be
> > split over multiple physical lines using backslashes; the whitespace up
> > to the first backslash determines the indentation" (in 2.1.8.
> > Indentation of Tutorial.)
> > I want to teach my student that point using some examples.
> > Pl help me any body?
> 
> Hi!
> 
> This is my very first post inside the usenet. I hope I did understand 
> this right, so here is my answer. :)
> 
> I assume, that you do understand the concept of indentation inside Python 
> code. You can concatenate lines with a backslash. These lines work as if 
> they were only one line. For example:
> 
> >>> print ("This is a very long"\
> ... " line, that got "\
> ... "diveded into three lines.")
> This is a very long line, that was diveded into three.
> >>>
> 
> Because the lines get concatenated, one might think, that you could 
> divide for example 16 spaces of indentation into one line of 8 spaces 
> with a backslash and one line with 8 spaces and the actual code.
> Your posted text tells you though, that you can't do this. Instead the 
> indentation would be considered to be only 8 spaces wide.
> 
> I hope this helped a little. :)
> 
> Cheers 
> Marc.

Thank you very much your explaination here
-- 
https://mail.python.org/mailman/listinfo/python-list


Python 3.6.0a2 is now available

2016-06-13 Thread Ned Deily
On behalf of the Python development community and the Python 3.6 release
team, I'm happy to announce the availability of Python 3.6.0a2.
3.6.0a2 is the first of four planned alpha releases of Python 3.6,
the next major release of Python.  During the alpha phase, Python 3.6
remains under heavy development: additional features will be added
and existing features may be modified or deleted.  Please keep in mind
that this is a preview release and its use is not recommended for
production environments.

You can find Python 3.6.0a2 here:

https://www.python.org/downloads/release/python-360a2/ 

The next release of Python 3.6 will be 3.6.0a3, currently scheduled for
2016-07-11.

Enjoy!

--Ned

--
  Ned Deily
  n...@python.org -- []

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


Re: for / while else doesn't make sense

2016-06-13 Thread Michael Selik
On Mon, Jun 13, 2016 at 10:46 PM Steven D'Aprano 
wrote:

> On Tue, 14 Jun 2016 09:45 am, Michael Selik wrote:
> > On Sun, Jun 12, 2016 at 10:16 PM Steven D'Aprano 
> > wrote:
> >> On Mon, 13 Jun 2016 04:44 am, Michael Selik wrote:
> >> > On Sun, Jun 12, 2016 at 6:11 AM Steven D'Aprano <
> >> > steve+comp.lang.pyt...@pearwood.info> wrote:
> >> >
> >> >> - run the for block
> >> >> - THEN unconditionally run the "else" block
> >> >>
> >> > Saying "unconditionally" is a bit misleading here. As you say, it's
> >> > conditioned on completing the loop without break/return/raise.
> >>
> >> It's also conditional on the OS not killing the Python process,
> >> conditional on the CPU not catching fire, conditional on the user not
> >> turning the power of, and conditional on the sun not exploding and
> >> disintegrating the entire earth.
> >>
> >> In the absence of any event which interferes with the normal execution
> of
> >> code by the Python VM, and in the absence of one of a very few
> >> explicit "JUMP" statements which explicitly jump out of the compound
> >> for...else statement, the else clause is unconditionally executed after
> >> the for clause.
>
> > Saying that ``raise``, ``break``, and ``return`` are "one of a very few
> > explicit JUMP statements" implies that they are obscure.
>
> What? No. How do you get that?
>

The context. That was right after a list of several (mostly) oddball
situations. In my experience, that pattern of speech is usually used to
imply that everything listed is also exceptionally strange.

There's a simple mental model, one which has the advantage of actually
> matching the implementation: for...else executes else unconditionally, ...
> If Python 3.6 introduces a GOTO command, then my mental model of
> for...else doesn't need to change.
>

That's a good explanation. The documentation says, "A break statement
executed in the first suite terminates the loop without executing the else
clause’s suite." Do you think that qualification of "without executing the
else clause" is unnecessary/redundant?

Regardless of the implementation, I think that explanation -- if break,
then skip the else-clause -- helps clarify the purpose.

https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

else: # only if no break occurs
> and then I would feel guilty for lying, because that comment is not, in
> fact, correct. Returning out of the function from inside the loop will also
> avoid running the else part, as will an exception.
>

I absolve you of guilt! :-) If you had written, "guaranteed to run if no
break," then lawyers will come after you. If you had written "if and only
if" some mathematicians might complain. As you wrote it, it's actually true.

An "if and only if" logical statement has two parts: "if no break, run
else-clause" and "if break, do not run else-clause". As you say, the first
part is false. But you only made the latter claim.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to search item in list of list

2016-06-13 Thread Larry Hudson via Python-list

On 06/12/2016 08:29 PM, meInvent bbird wrote:

once a nested list have a word "node" then true else false

def search(current_item):
 if isinstance(current_item, list):
 if len(current_item)==4:
 if [item for item in current_item if item[4] == "node"] != []:
 return True
 if True in [search(item) for item in current_item]:
 return True
 else:
 return False

search(mresult)

but it return false


mresult = [[(2, {'11': 1, '10': 1, '00': 0, '01': 1}, ['000', '001', '010', 
'011', '100',
'101', '110', '111'], 'xy', 'start')], [(2, {'11': 1, '10': 1, '00': 0, '01': 1}
, ['000', '001', '010', '011', '100', '101', '110', '111'], 'yz', 'start')], [(2
, {'11': 1, '10': 1, '00': 0, '01': 1}, ['000', '001', '010', '011', '100', '101
', '110', '111'], 'xz', 'start')], [(2, {'11': 1, '10': 0, '00': 0, '01': 0}, ['
000', '001', '010', '011', '100', '101', '110', '111'], 'xy', 'start')], [(2, {'
11': 1, '10': 0, '00': 0, '01': 0}, ['000', '001', '010', '011', '100', '101', '
110', '111'], 'yz', 'start')], [(2, {'11': 1, '10': 0, '00': 0, '01': 0}, ['000'
, '001', '010', '011', '100', '101', '110', '111'], 'xz', 'start')], [(2, {'11':
  1, '10': 0, '00': 1, '01': 1}, ['000', '001', '010', '011', '100', '101', 
'110'
, '111'], 'xy', 'start')], [(2, {'11': 1, '10': 0, '00': 1, '01': 1}, ['000', '0
01', '010', '011', '100', '101', '110', '111'], 'yz', 'start')], [(2, {'11': 1,
'10': 0, '00': 1, '01': 1}, ['000', '001', '010', '011', '100', '101', '110', '1
11'], 'xz', 'start')], [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00', '01', '
11', '11', '10', '11', '11', '11'], 'xy', 'node')], [(1, {'11': 1, '10': 1, '00'
: 0, '01': 1}, ['00', '01', '10', '11', '11', '11', '11', '11'], 'xy', 'node')],
  [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00', '00', '10', '10', '10', 
'10',
  '11', '11'], 'xy', 'node')], [(1, {'11': 1, '10': 1, '00': 0, '01': 1}, ['00',
'00', '10', '11', '10', '10', '10', '11'], 'xy', 'node')], [(1, {'11': 1, '10':
1, '00': 0, '01': 1}, ['00', '00', '10', '10', '10', '11', '10', '11'], 'xy', 'n
ode')]]



I (manually) reformatted your list and found you have a missing left square 
bracket in the middle.
But the way your list is formatted here I really can't tell you where it is -- you'll have to 
reformat

it and/or use an editor that highlights matching brackets to find it yourself.  
Most programming
editors have that bracket matching capability.

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