Re: Function to determine list max without itertools

2019-04-18 Thread Sayth Renshaw
Thank you for the advice everyone.

> 
> The first thing to try is find every place where you update myMax, and

This was actually where I was going wrong. I was setting max but then 
overwriting it with item. Then kept checking item only to return myMax.

I went looking for other solutions as I thought I must be well off the path in 
the shrubs but I was actually close.

This is how I ended up. There may be better solutions but this works.

def maximum(listarg): 
items = list(listarg) 
myMax = items[0] 
for item in items:
for i in items[items.index(item)+1:len(items)]:
if myMax < i:
myMax = i
else:
pass

return myMax
  

if __name__ == "__main__":
print(maximum([4,3,6,2,1,4]))


Cheers

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


Re: immutability is not strictly the same as having an unchangeable value, it is more subtle

2019-04-18 Thread Gregory Ewing

Arup Rakshit wrote:

What protocols I need to
learn, to define a custom immutable class ?


That depends on how strictly you want to enforce immutability.

The easiest thing is not to enforce it at all and simply refrain
from mutating it. This is very often done.

You can provide some protection against accidental mutation
by using properties, for example,

class Foo:

def __init__(self, x):
self._x = x

@property
def x(self):
return self._x

This will let you read the x attribute but not directly assign
to it. Of course, it doesn't prevent someone from accessing the
underlying _x attribute, but there's no way to do that for a
class defined in Python. The only way to make a completely
bulletproof immutable object would be to write an extension
module in C or Cython.

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


Re: Function to determine list max without itertools

2019-04-18 Thread Chris Angelico
On Thu, Apr 18, 2019 at 5:41 PM Sayth Renshaw  wrote:
>
> Thank you for the advice everyone.
>
> >
> > The first thing to try is find every place where you update myMax, and
>
> This was actually where I was going wrong. I was setting max but then 
> overwriting it with item. Then kept checking item only to return myMax.
>
> I went looking for other solutions as I thought I must be well off the path 
> in the shrubs but I was actually close.
>
> This is how I ended up. There may be better solutions but this works.
>
> def maximum(listarg):
> items = list(listarg)
> myMax = items[0]
> for item in items:
> for i in items[items.index(item)+1:len(items)]:
> if myMax < i:
> myMax = i
> else:
> pass
>
> return myMax
>
>
> if __name__ == "__main__":
> print(maximum([4,3,6,2,1,4]))
>

This is where I would strongly recommend printing lots of stuff out,
to explore what the algorithm is doing at each point. See if you can
figure out when myMax is being updated.

(Also: items.index(item) will potentially give the wrong result if you
have duplicates.)

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


Re: immutability is not strictly the same as having an unchangeable value, it is more subtle

2019-04-18 Thread Chris Angelico
On Thu, Apr 18, 2019 at 6:16 PM Gregory Ewing
 wrote:
>
> Arup Rakshit wrote:
> > What protocols I need to
> > learn, to define a custom immutable class ?
>
> That depends on how strictly you want to enforce immutability.
>
> The easiest thing is not to enforce it at all and simply refrain
> from mutating it. This is very often done.
>
> You can provide some protection against accidental mutation
> by using properties

Another reasonably easy way to make a custom immutable class is to
make use of namedtuple. You can subclass a namedtuple to add methods
to it, for instance.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Gregory Ewing

DL Neil wrote:
Thus the basic question: why do we (apparently) so seldom consider the 
possibility of an ImportError?


Because the cases in which we can do something useful about
it are relatively rare.

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


Re: Function to determine list max without itertools

2019-04-18 Thread MRAB

On 2019-04-18 08:39, Sayth Renshaw wrote:

Thank you for the advice everyone.



The first thing to try is find every place where you update myMax, and


This was actually where I was going wrong. I was setting max but then 
overwriting it with item. Then kept checking item only to return myMax.

I went looking for other solutions as I thought I must be well off the path in 
the shrubs but I was actually close.

This is how I ended up. There may be better solutions but this works.

def maximum(listarg):
 items = list(listarg)
 myMax = items[0]
 for item in items:
 for i in items[items.index(item)+1:len(items)]:
 if myMax < i:
 myMax = i
 else:
 pass
 
 return myMax
   

It's still overly complicated.

 
if __name__ == "__main__":

 print(maximum([4,3,6,2,1,4]))


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


Re: Importing module from another subdirectory

2019-04-18 Thread Rich Shepard

On Wed, 17 Apr 2019, Sayth Renshaw wrote:


Apologies I don't know the answer but went looking. This guide should
answer the question. Didn't know it was so difficult to be honest.

https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html#example-directory-structure

Then there was this rather long list of traps.
http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html


Sayth,

Thank you. My web search terms didn't find these.

Regards,

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


Re: Importing module from another subdirectory

2019-04-18 Thread Rich Shepard

On Thu, 18 Apr 2019, dieter wrote:


Python knows about 2 kinds of "regular" imports: absolute ones and
relative ones. "Absolute" imports are guided by "sys.path" -- in the
simple case, a sequence of folders containing modules and/or pacakges.
Relative imports are guided in a similar way by the current packages's
"__path__", which typically contains just one element - the folder from
which the current package was loaded.


Dieter,

Thanks. My previous applications used a single directory rather than
separating the model, views, and controller so now I know what to learn to
resolve this issue.

Regards,

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Grant Edwards
On 2019-04-18, DL Neil  wrote:
> On 18/04/19 8:44 AM, Grant Edwards wrote:
>> On 2019-04-17, DL Neil  wrote:
>> 
>>> Do you bother with exception handling for import statements?
>> 
>> Sometimes.  There are two cases when I do that:
>> 
>>   1. When the module has different names under Python2 and Python3 and
>>  the program tries first one, then the other.
>
> Excellent example - and a lot easier than interrogating os.environ (for 
> example), ie permission cf forgiveness.
>
>
>>   2. When the program can still do something useful (if perhaps
>>  feature-limited) without the imported module by substituting
>>  something else in its place.
>
> Any (publishable) examples?

I can describe one example, but the source doesn't belong to me so I
can't publish it.  I wrote an application that dissects a proprietary
Ethernet protocol and prints out what's going on as a human-readable
transcript.

In the "normal" case, it uses pylibpcap to either capture packets live
or read them from a saved capture file.  If the import of pylibpcap
fails, I replace it with a built-in class which can only read packets
from a one particular type/version of capture file.  If you try to do
a live capture with the built-in class (or read an unsupported capture
file format), it prints an error message saying that's only possible
with pylibpcap and exits.

I can recall one or two other similar cases where a built-in class
handles a limited set of the functionality provided by the missing
module, but they're too obscure to describe succinctly...

>> You've omitted the second thing assumed by the authors: without numpy,
>> scipy, pandas, et alia the program can do nothing useful.
>
> but... what of the third inherent assumption: that the user(s) will be 
> able to handle the situation (discussed in another msg 'here')?

Or they notify somebody who can.  The probability of being able to
programmatically download and properly install a missing module in
order to automagically recover from a failed import is, in practice,
zero.  You could try to format the error in a prettier way, I suppose,
but that's just going to confuse experienced users and admins, and it
isn't going to help the user who doesn't know what to do anyway.

-- 
Grant Edwards   grant.b.edwardsYow! Don't hit me!!  I'm in
  at   the Twilight Zone!!!
  gmail.com

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Akkana Peck
DL Neil writes:
> On 18/04/19 8:44 AM, Grant Edwards wrote:
> >   2. When the program can still do something useful (if perhaps
> >  feature-limited) without the imported module by substituting
> >  something else in its place.
> 
> Any (publishable) examples?

One of the targets my RSS fetching program supports is Plucker on
PalmOS, which used to be how I read RSS feeds back in the day
(nowadays I use simplified HTML on Android). Plucker on Palm had
problems with accented characters, so I added a little module called
ununicode to translate strings to plain ASCII (so á would become a).
For most target platforms, it was a nonissue.

try:
import ununicode
has_ununicode = True
except ImportError as e:
has_ununicode = False

def output_encode(s, encoding):
if encoding == 'ascii' and has_ununicode:
return ununicode.toascii(s, in_encoding=encoding)
else:
return s

The program still worked fine if the module wasn't there, it just
wrote accented characters because it couldn't simplify them.

And yes, it could have tested "if 'ununicode' in sys.modules" instead
of setting a variable; I didn't know about that at the time.

> but... what of the third inherent assumption: that the user(s) will be able
> to handle the situation (discussed in another msg 'here')?

One example: there are a gazillion whois modules, and when I run my
domaincheck program on a machine where I haven't yet installed
whois, it's helpful to have a reminder of which one I should
install. (Of course, if you have one of the other whois modules
installed, the program will fail somewhere else.)

try:
import whois
# python-whois from pypi, not whois from pypi or python-whois from debian
# https://bitbucket.org/richardpenman/pywhois
except ImportError:
print("Couldn't import whois. Try: pip3 install python-whois")
sys.exit(1)

The third case has already been mentioned: modules that change name
but don't change their APIs much.

# Tkinter changed capitalization from Python 2 to Python 3.
try:
import tkinter
except ModuleNotFoundError:
import Tkinter as tkinter

I thought I had examples for gtk and qt -- GUI libraries change
their import syntax a lot -- but I can't find them.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Chris Angelico
On Fri, Apr 19, 2019 at 1:36 AM Akkana Peck  wrote:
> One example: there are a gazillion whois modules, and when I run my
> domaincheck program on a machine where I haven't yet installed
> whois, it's helpful to have a reminder of which one I should
> install. (Of course, if you have one of the other whois modules
> installed, the program will fail somewhere else.)
>
> try:
> import whois
> # python-whois from pypi, not whois from pypi or python-whois from debian
> # https://bitbucket.org/richardpenman/pywhois
> except ImportError:
> print("Couldn't import whois. Try: pip3 install python-whois")
> sys.exit(1)

I write this as:

import whois # ImportError? pip install python-whois

Way easier, AND it means that normal exception handling is still
happening (which might be important if I import this into something
else), plus it's printing the message to stderr rather than stdout
(not usually significant, but when it is, I'd usually rather the
errors go to stderr).

About the only downside is that it assumes the .py file is available -
this won't work with a .pyc-only setup.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Manolo Martínez

On 2019-04-17, DL Neil  wrote:

>   2. When the program can still do something useful (if perhaps
>  feature-limited) without the imported module by substituting
>  something else in its place.

Isn't this a very common scenario, similar to what package management systems
call "optional dependencies"? 

I maintain a small podcast aggregator that tags podcasts using an external
tagging library as an optional dependency---people can choose not to install it
if they don't care about tags. That library is imported within a try/except
block.

Manolo


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Rhodri James

On 18/04/2019 17:10, Manolo Martínez wrote:


On 2019-04-17, DL Neil  wrote:


   2. When the program can still do something useful (if perhaps
  feature-limited) without the imported module by substituting
  something else in its place.


Isn't this a very common scenario, similar to what package management systems
call "optional dependencies"?


I wouldn't have said "very common."


I maintain a small podcast aggregator that tags podcasts using an external
tagging library as an optional dependency---people can choose not to install it
if they don't care about tags. That library is imported within a try/except
block.


Most imports I've seen have been for mandatory functionality; while my 
current code could run without its CRC library, everything it tried to 
talk to would reject its messages, for example!


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Akkana Peck
Chris Angelico writes:
> I write this as:
> 
> import whois # ImportError? pip install python-whois
[ ... ]
> it means that normal exception handling is still
> happening (which might be important if I import this into something
> else), plus it's printing the message to stderr rather than stdout
[ ... ]
> About the only downside is that it assumes the .py file is available -
> this won't work with a .pyc-only setup.

It also assumes the user is capable of (1) finding the .py file
(maybe not so easy if it's imported from another program) and
(2) knowing Python well enough to find and understand the line with
the comment. Which in my example is not a problem since I'm probably
the only user of my domaincheck script; but when writing programs
for regular users, when you know an error is both likely and unclear
to read, it might make sense to catch the exception and print
a clearer message.

Your counterarguments are quite valid, though. It's a trade-off.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Chris Angelico
On Fri, Apr 19, 2019 at 2:46 AM Akkana Peck  wrote:
>
> Chris Angelico writes:
> > I write this as:
> >
> > import whois # ImportError? pip install python-whois
> [ ... ]
> > it means that normal exception handling is still
> > happening (which might be important if I import this into something
> > else), plus it's printing the message to stderr rather than stdout
> [ ... ]
> > About the only downside is that it assumes the .py file is available -
> > this won't work with a .pyc-only setup.
>
> It also assumes the user is capable of (1) finding the .py file
> (maybe not so easy if it's imported from another program) and
> (2) knowing Python well enough to find and understand the line with
> the comment.

Actually, only the Python interpreter has to be able to do those
steps. That's why I put the comment *on the same line* as the import
statement (not immediately above it, for instance). It comes out like
this:

(env) rosuav@sikorsky:~/shed$ python3 BL2_find_items.py
Traceback (most recent call last):
  File "BL2_find_items.py", line 19, in 
import lzo # ImportError? pip install python-lzo
ModuleNotFoundError: No module named 'lzo'
(env) rosuav@sikorsky:~/shed$

> Which in my example is not a problem since I'm probably
> the only user of my domaincheck script; but when writing programs
> for regular users, when you know an error is both likely and unclear
> to read, it might make sense to catch the exception and print
> a clearer message.

Define "clearer", though. Given that many MANY users won't read *any*
error message, the clarity becomes largely moot, and only a handful of
people will (a) read what you print out, (b) be able to resolve the
problem, and (c) not be able to figure it out from four lines of
output.

> Your counterarguments are quite valid, though. It's a trade-off.

Indeed. But the biggest argument in favour of this style of thing is
that it requires almost zero effort and has almost zero code
readability cost. Imagine having half a dozen dependencies and tagging
each one with a comment like mine... and now imagine having to bracket
each one of them with a try/except and an appropriate message.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Akkana Peck
Chris Angelico writes:
> Actually, only the Python interpreter has to be able to do those
> steps. That's why I put the comment *on the same line* as the import
> statement (not immediately above it, for instance). It comes out like
> this:
> 
> (env) rosuav@sikorsky:~/shed$ python3 BL2_find_items.py
> Traceback (most recent call last):
>   File "BL2_find_items.py", line 19, in 
> import lzo # ImportError? pip install python-lzo
> ModuleNotFoundError: No module named 'lzo'
> (env) rosuav@sikorsky:~/shed$

Oh, I see: because it prints the full line that caused the exception.
Clever!

> > for regular users, when you know an error is both likely and unclear
> > to read, it might make sense to catch the exception and print
> > a clearer message.
> 
> Define "clearer", though. Given that many MANY users won't read *any*
> error message, the clarity becomes largely moot, and only a handful of
> people will (a) read what you print out, (b) be able to resolve the
> problem, and (c) not be able to figure it out from four lines of
> output.

When writing programs for general use (which this admittedly wasn't),
it seems sad to accept unclear errors on the assumption that some
users don't read error messages. Even most of the nontechnical
users I know will read a one-line error message, though they
certainly wouldn't try to read a 4-line stack trace. I usually try
to catch errors that I expect will be common, and print something
clearer than the default traceback.

> Indeed. But the biggest argument in favour of this style of thing is
> that it requires almost zero effort and has almost zero code
> readability cost. Imagine having half a dozen dependencies and tagging
> each one with a comment like mine... and now imagine having to bracket
> each one of them with a try/except and an appropriate message.

Certainly. I don't use try/except on imports in general. And I
like your short form, and there are definitely places where I'll use
that now where a try/except would have been overkill.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Chris Angelico
On Fri, Apr 19, 2019 at 3:27 AM Akkana Peck  wrote:
>
> Chris Angelico writes:
> > Actually, only the Python interpreter has to be able to do those
> > steps. That's why I put the comment *on the same line* as the import
> > statement (not immediately above it, for instance). It comes out like
> > this:
> >
> > (env) rosuav@sikorsky:~/shed$ python3 BL2_find_items.py
> > Traceback (most recent call last):
> >   File "BL2_find_items.py", line 19, in 
> > import lzo # ImportError? pip install python-lzo
> > ModuleNotFoundError: No module named 'lzo'
> > (env) rosuav@sikorsky:~/shed$
>
> Oh, I see: because it prints the full line that caused the exception.
> Clever!

Yes - provided the .py file is available. If you delete the .py file
and just run the .pyc, this doesn't work. (Another reason not to do
that, honestly.)

> > > for regular users, when you know an error is both likely and unclear
> > > to read, it might make sense to catch the exception and print
> > > a clearer message.
> >
> > Define "clearer", though. Given that many MANY users won't read *any*
> > error message, the clarity becomes largely moot, and only a handful of
> > people will (a) read what you print out, (b) be able to resolve the
> > problem, and (c) not be able to figure it out from four lines of
> > output.
>
> When writing programs for general use (which this admittedly wasn't),
> it seems sad to accept unclear errors on the assumption that some
> users don't read error messages. Even most of the nontechnical
> users I know will read a one-line error message, though they
> certainly wouldn't try to read a 4-line stack trace. I usually try
> to catch errors that I expect will be common, and print something
> clearer than the default traceback.

TBH, I don't think the default message is all that unclear. It does
lack any sort of "how to solve this" information, but that can be
provided by the comment. Something that frequently annoys me in terms
of debugging is something that "knows better" - it absorbs a nice,
useful, helpful message, and spits out one bland, generic message,
based on what the developer THINKS is the cause. Remember: You will
*never* think of everything that can go wrong.

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


[no subject]

2019-04-18 Thread trisha guillot


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


Re: Function to determine list max without itertools

2019-04-18 Thread Sayth Renshaw


> >
> It's still overly complicated.
> 

This is where I have ended up. Without itertools and max its what I got 
currently.

def maximum(listarg):
myMax = listarg[0]
for item in listarg:
for i in listarg[listarg.index(item)+1:len(listarg)]:
if myMax < i:
myMax = i

return myMax

How would you simplify it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Function to determine list max without itertools

2019-04-18 Thread Rob Gaddi

On 4/18/19 4:35 PM, Sayth Renshaw wrote:




It's still overly complicated.



This is where I have ended up. Without itertools and max its what I got 
currently.

def maximum(listarg):
 myMax = listarg[0]
 for item in listarg:
 for i in listarg[listarg.index(item)+1:len(listarg)]:
 if myMax < i:
 myMax = i

 return myMax

How would you simplify it?



In English rather than Python, how do you find the maximum element in a 
list?


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to determine list max without itertools

2019-04-18 Thread Grant Edwards
On 2019-04-18, Rob Gaddi  wrote:
> On 4/18/19 4:35 PM, Sayth Renshaw wrote:
>
>> This is where I have ended up. Without itertools and max its what I got 
>> currently.
>> 
>> def maximum(listarg):
>>  myMax = listarg[0]
>>  for item in listarg:
>>  for i in listarg[listarg.index(item)+1:len(listarg)]:
>>  if myMax < i:
>>  myMax = i
>> 
>>  return myMax
>> 
>> How would you simplify it?
>
> In English rather than Python, how do you find the maximum element
> in a list?

Hint: "greater than" is transitive.

--
Grant


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


Re: Function to determine list max without itertools

2019-04-18 Thread Sayth Renshaw


> 
> In English rather than Python, how do you find the maximum element in a 
> list?
> 
> -- 
> Rob Gaddi, Highland Technology 

Get first 1 item in the list and compare it to the rest. If it is larger than 
rest its the max. However if another list member is larger it replaces the 
first item and comparison continues.

Sayth


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


Re: Function to determine list max without itertools

2019-04-18 Thread DL Neil

On 19/04/19 5:22 PM, Sayth Renshaw wrote:




In English rather than Python, how do you find the maximum element in a
list?

--
Rob Gaddi, Highland Technology


Get first 1 item in the list and compare it to the rest. If it is larger than 
rest its the max. However if another list member is larger it replaces the 
first item and comparison continues.



A good first effort!

Is it sufficiently-detailed to say "compare it to the rest"? Is it being 
compared with ALL of the other elements of the list at once?



How about this outline:

Set the first item in the list as the current largest.
Compare ...
if this element is larger, set ...

How could we fill in the gaps (...) of that description?


Also, what types of data are you expecting as elements within the list?
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list