Re: RE: Problem resizing a window and button placement

2024-02-27 Thread Alan Gauld via Python-list
On 27/02/2024 07:13, Steve GS via Python-list wrote:

> Aside from using it to resized
> the window, is there no way to
> know the last value of the
> change for use in the program?

The last value would be the current width.
And you know how to get that as shown in
your configure function:

Ww = root.winfo_width()

> I could write the value to a
> label and read it back later

That's no different to writing it to
global Ww and accessing that as demonstrated
in my last code post (with button).

>>>  It's better just to ask tk
> for the values whenever you
> need them, as you do inside
> your handler.
> 
> How would that be done?

Ww = root.winfo_width()

Provided you can access the root widget
(which is (nearly?) always true) you
can get the width of the main window.

But can I ask if you have a particular use-case
in mind for this? We started out talking about
relocating some widgets when the window was
resized. We established that the best place
to do that was inside the configure event
handler, with no need to store the width.
(assuming you aren't using a dynamic layout
manager(grid/pack/form) which would be better
still!)

We've now moved on to the more general issue
of communicating values between event handlers
(although still using the width as our exemplar).
Is this just academic interest or do you have
a specific need for this? If we know the need
we might be able to suggest a specific (and
possibly better?)solution.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: RE: Problem resizing a window and button placement

2024-02-26 Thread Alan Gauld via Python-list
On 26/02/2024 11:02, Steve GS via Python-list wrote:
> Although your code produces the value of Ww outside the function, 
> I do not see how I can use the value of Ww unless I close the program.

You have to use a function that operates inside the mainloop.
Thats the nature of event driven programs, all activity happens
inside the mainloop except initialisation and cleanup.

So you need to create an event handler as I described below.

Here is the complete program including the button:

###
import tkinter as tk

Ww=None

def on_configure(*args):
  global Ww
  Ww = root.winfo_width()
  print("Ww Inside = <" + str(Ww) + ">")

def printW(): print("Button Ww = ", Ww)


root = tk.Tk()
bw = tk.Button(root, text="Print Width", command=printW)
bw.pack()
root.bind('', on_configure)
root.mainloop()

print("Ww Outside = <" + str(Ww) + ">")


Notice that the button callback picks up the latest value of Ww.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


RE: RE: Problem resizing a window and button placement

2024-02-26 Thread Steve GS via Python-list
Although your code produces the value of Ww outside the function, I do not see 
how I can use the value of Ww unless I close the program.

import tkinter as tk

Ww = None  # What does this do? Why not Integer?
WwZ = None

def on_configure(*args):
global Ww
global WwZ
Ww = root.winfo_width()
print("9  Ww Inside =<"+str(Ww)+">")  # works
WwZ = Ww * 2
print("11  WwZ Inside =<"+str(WwZ)+">")  # works
return(Ww)  #Can I use this?

root = tk.Tk()
root.bind('',on_configure)
print("15  Ww Inside1 = <"+str(Ww)+">")
#Ww2 = int(Ww) * 2  # fails
print("17  WwZ Inside2 = <"+str(WwZ)+">")

root.mainloop()

Ww2 = int(Ww) * 2  #Works but only after the program stops
print("21  Ww Outside2 = <"+str(WwZ)+">")
# Can I have concentric loops?


SGA

-----Original Message-
From: Alan Gauld  
Sent: Monday, February 26, 2024 4:04 AM
To: Steve GS ; python-list@python.org
Subject: Re: RE: Problem resizing a window and button placement

On 26/02/2024 07:56, Steve GS via Python-list wrote:

> Then there is that discovery
> element: Why is my original
> idea not working? I still
> cannot pass the value back
> from the function.  What is
> different about this function
> that others would have given
> me the value?

There is nothing different, see the code below.
print() is a function like any other.
In this case it is called after you close the window, ie after mainloop() exits.
But any other function called inside
mainloop - eg any other event handler can also access it.

For example, if you added a button:

def printW(): print("Button Ww = ", Ww)

bw = tk.Button(root, text="Print Width", command=printW)
bw.pack()

You would be able to print the value on demand.

>> import tkinter as tk
>>
>> Ww = None
>>
>> def on_configure(*args):
>> global Ww
>> Ww = root.winfo_width()
>> print("Ww Inside =<"+str(Ww)+">")
>>
>> root = tk.Tk()
>> root.bind('',on_configure)
>> root.mainloop()
>>
>> print("Ww Outside = <"+str(Ww)+">")

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: Problem resizing a window and button placement

2024-02-26 Thread Alan Gauld via Python-list
On 26/02/2024 07:56, Steve GS via Python-list wrote:

> Then there is that discovery
> element: Why is my original
> idea not working? I still
> cannot pass the value back
> from the function.  What is
> different about this function
> that others would have given
> me the value?

There is nothing different, see the code below.
print() is a function like any other.
In this case it is called after you close the
window, ie after mainloop() exits.
But any other function called inside
mainloop - eg any other event handler can
also access it.

For example, if you added a button:

def printW(): print("Button Ww = ", Ww)

bw = tk.Button(root, text="Print Width", command=printW)
bw.pack()

You would be able to print the value on demand.

>> import tkinter as tk
>>
>> Ww = None
>>
>> def on_configure(*args):
>> global Ww
>> Ww = root.winfo_width()
>> print("Ww Inside =<"+str(Ww)+">")
>>
>> root = tk.Tk()
>> root.bind('',on_configure)
>> root.mainloop()
>>
>> print("Ww Outside = <"+str(Ww)+">")

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


RE: RE: Problem resizing a window and button placement

2024-02-25 Thread Steve GS via Python-list
SOLUTION FOUND!

The fix was to write the code that uses the width value and to place it into 
the function itself.  
Kluge? Maybe but it works. 

Mischief Managed.


As for the most recent suggestion, it fails for me:

Traceback (most recent call last):
  File "F:/___zInsulin Code A 08-02-23/WinPic/IOWw.pyw", line 14, in 
print("Ww Outside = <" + str(Ww) > + ">")
TypeError: bad operand type for unary +: 'str'

With the need to close the window, it adds an extra step and intervention to 
the program to use. I am not sure how this help[s.

As a curio, it would be interesting to see how to use the value of a variable, 
created in the function used here, and make it available to the code outside 
the function.



SGA

-Original Message-
From: Alan Gauld  
Sent: Sunday, February 25, 2024 12:44 PM
To: Steve GS ; python-list@python.org
Subject: Re: RE: Problem resizing a window and button placement

On 25/02/2024 03:58, Steve GS via Python-list wrote:
import tkinter as tk

Ww = None

def on_configure(*args):
   global Ww
   Ww = root.winfo_width()
   print("Ww Inside = <" + str(Ww) + ">")

root = tk.Tk()
root.bind('', on_configure)
root.mainloop()

print("Ww Outside = <" + str(Ww) > + ">")

Produces:
Ww Inside = <200>
Ww Inside = <200>
Ww Inside = <205>
Ww Inside = <205>
Ww Inside = <206>
Ww Inside = <206>
Ww Outside = <206>

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: Problem resizing a window and button placement

2024-02-25 Thread Alan Gauld via Python-list
On 25/02/2024 03:58, Steve GS via Python-list wrote:
import tkinter as tk

Ww = None

def on_configure(*args):
   global Ww
   Ww = root.winfo_width()
   print("Ww Inside = <" + str(Ww) + ">")

root = tk.Tk()
root.bind('', on_configure)
root.mainloop()

print("Ww Outside = <" + str(Ww) > + ">")

Produces:
Ww Inside = <200>
Ww Inside = <200>
Ww Inside = <205>
Ww Inside = <205>
Ww Inside = <206>
Ww Inside = <206>
Ww Outside = <206>

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Aw: Re: Re: Re: Extract lines from file, add to new files

2024-01-30 Thread Karsten Hilbert via Python-list
> On Tue, 30 Jan 2024, Karsten Hilbert wrote:
>
> > It doesn't need to. It just sends the (pre-personalized-by-Python) mail 
> > files.
>
> Karsten,
>
> In which case, I might as well have Python format and send the messages. :-)

Certainly. But it seems you are wrestling with Python. Might as well reduce the 
attack surface.

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


Re: Aw: Re: Re: Extract lines from file, add to new files

2024-01-30 Thread Rich Shepard via Python-list

On Tue, 30 Jan 2024, Karsten Hilbert wrote:


It doesn't need to. It just sends the (pre-personalized-by-Python) mail files.


Karsten,

In which case, I might as well have Python format and send the messages. :-)

Regards,

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


Aw: Re: Re: Extract lines from file, add to new files

2024-01-30 Thread Karsten Hilbert via Python-list


> > Why not foxus on just the part you think you are better off using python,
> > namely personalization ?
> >
> > Create personalized files and send them with your trusted mailx solution ?
>
> Karsten,
>
> Too much time. And while mailx accepts the '-a' option for attachments but
> has none for individual salutations.

It doesn't need to. It just sends the (pre-personalized-by-Python) mail files.

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


Aw: Re: Re: mypy question

2023-12-30 Thread Karsten Hilbert via Python-list
> I'm fairly sure your database queries don't actually give you strings or
> dicts, right?  You probably get lists (or iterators) of tuples and
> somewhere you convert them to the arguments you are feeding to
> run_queries().

Ah, no, those queries are enshrined within the middleware as Python strings
with placeholdders. When in need of being run they are assembled into
a list of dicts-enriched-with-arguments-per-query (and fed to run_queries()).

As to what queries *give* me: I have set up psycopg2 to, indeed, hand
me a list of dicts (DictRow instances, that is). Those are then used
in display rather than being fed to run_queries().

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


Aw: Re: Re: mypy question

2023-12-30 Thread Karsten Hilbert via Python-list
> It occurs to me that you could simplify things if you converted those
> plain query strings to dicts:
>
> 'SELECT 1' --> {'SQL': 'SELECT 1'}

Ha, indeed. There's likely not that many "simple string SQL queries"
in that codebase so I shall take it as an opportunity to refactor them.

So, at least that much good has come from the mypy hint ;-)

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


Re: RE: Newline (NuBe Question)

2023-11-26 Thread Chris Angelico via Python-list
On Mon, 27 Nov 2023 at 06:15,  wrote:
> But I learn from criticism. If I ever write a program like that and do not
> feel like typing, will this do?
>
> dents = [ ...]
>
> Or will that not include students who happen to be edentulous?
>

If they're learning to drive, this variable name would make complete sense.

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


RE: RE: Newline (NuBe Question)

2023-11-26 Thread AVI GROSS via Python-list
Just FYI, I deliberately chose that abbreviation for a sort of irony as for
some people college is about almost anything except learning and some people
think they are studs and just  party and ...

And I am very tired of gender discussions. Lots of words now include two or
even more genders. Women are often now "actors", not actresses. I see no
reason women cannot be studs!

But I learn from criticism. If I ever write a program like that and do not
feel like typing, will this do?

dents = [ ...]

Or will that not include students who happen to be edentulous?


-Original Message-
From: Python-list  On
Behalf Of Chris Angelico via Python-list
Sent: Sunday, November 26, 2023 6:49 AM
To: python-list@python.org
Subject: Re: RE: Newline (NuBe Question)

On Sun, 26 Nov 2023 at 21:08, Michael F. Stemper via Python-list
 wrote:
>
> On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote:
> > Grizz[l]y,
> >
> > I think the point is not about a sorted list or sorting in general It is
> > about reasons why maintaining a data structure such as a list in a
program
> > can be useful beyond printing things once. There are many possible
examples
> > such as having a list of lists containing a record where the third item
is a
> > GPA for the student and writing a little list comprehension that selects
a
> > smaller list containing only students who are Magna Cum Laude or Summa
Cum
> > Laude.
> >
> > studs = [
> >["Peter", 82, 3.53],
> >["Paul", 77, 2.83],
> >["Mary", 103, 3.82]
> > ]
>
> I've seen Mary, and she didn't look like a "stud" to me.
>

That's what happens when you abbreviate "student" though :) Don't
worry, there's far FAR worse around the place, and juvenile brains
will always find things to snigger at, usually in mathematical
libraries with "cumulative" functions.

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

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


RE: RE: Newline (NuBe Question)

2023-11-26 Thread AVI GROSS via Python-list
via Python-list
Sent: Saturday, November 25, 2023 9:32 AM
To: python-list@python.org
Subject: Re: RE: Newline (NuBe Question)

On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote:
> Grizz[l]y,
> 
> I think the point is not about a sorted list or sorting in general It is
> about reasons why maintaining a data structure such as a list in a program
> can be useful beyond printing things once. There are many possible
examples
> such as having a list of lists containing a record where the third item is
a
> GPA for the student and writing a little list comprehension that selects a
> smaller list containing only students who are Magna Cum Laude or Summa Cum
> Laude.
> 
> studs = [
>["Peter", 82, 3.53],
>["Paul", 77, 2.83],
>["Mary", 103, 3.82]
> ]

I've seen Mary, and she didn't look like a "stud" to me.

> Of course, for serious work, some might suggest avoiding constructs like a
> list of lists and switch to using modules and data structures [...]

Those who would recommend that approach do not appear to include Mr.
Rossum, who said:
   
   Avoid overengineering data structures. Tuples are better than
   objects (try namedtuple too though). Prefer simple fields over
   getter/setter functions... Built-in datatypes are your friends.
   Use more numbers, strings, tuples, lists, sets, dicts. Also
   check out the collections library, eps. deque.[1]
   
I was nodding along with the people saying "list of lists" until I
reread this quote. A list of tuples seems most appropriate to me.

   
[1] <https://gist.github.com/hemanth/3715502>, as quoted by Bill
Lubanovic in _Introducing Python_

-- 
Michael F. Stemper
This sentence no verb.

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

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


Re: RE: Newline (NuBe Question)

2023-11-26 Thread Chris Angelico via Python-list
On Sun, 26 Nov 2023 at 21:08, Michael F. Stemper via Python-list
 wrote:
>
> On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote:
> > Grizz[l]y,
> >
> > I think the point is not about a sorted list or sorting in general It is
> > about reasons why maintaining a data structure such as a list in a program
> > can be useful beyond printing things once. There are many possible examples
> > such as having a list of lists containing a record where the third item is a
> > GPA for the student and writing a little list comprehension that selects a
> > smaller list containing only students who are Magna Cum Laude or Summa Cum
> > Laude.
> >
> > studs = [
> >["Peter", 82, 3.53],
> >["Paul", 77, 2.83],
> >["Mary", 103, 3.82]
> > ]
>
> I've seen Mary, and she didn't look like a "stud" to me.
>

That's what happens when you abbreviate "student" though :) Don't
worry, there's far FAR worse around the place, and juvenile brains
will always find things to snigger at, usually in mathematical
libraries with "cumulative" functions.

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


Re: RE: Newline (NuBe Question)

2023-11-26 Thread Michael F. Stemper via Python-list

On 24/11/2023 21.45, avi.e.gr...@gmail.com wrote:

Grizz[l]y,

I think the point is not about a sorted list or sorting in general It is
about reasons why maintaining a data structure such as a list in a program
can be useful beyond printing things once. There are many possible examples
such as having a list of lists containing a record where the third item is a
GPA for the student and writing a little list comprehension that selects a
smaller list containing only students who are Magna Cum Laude or Summa Cum
Laude.

studs = [
   ["Peter", 82, 3.53],
   ["Paul", 77, 2.83],
   ["Mary", 103, 3.82]
]


I've seen Mary, and she didn't look like a "stud" to me.


Of course, for serious work, some might suggest avoiding constructs like a
list of lists and switch to using modules and data structures [...]


Those who would recommend that approach do not appear to include Mr.
Rossum, who said:
  
  Avoid overengineering data structures. Tuples are better than

  objects (try namedtuple too though). Prefer simple fields over
  getter/setter functions... Built-in datatypes are your friends.
  Use more numbers, strings, tuples, lists, sets, dicts. Also
  check out the collections library, eps. deque.[1]
  
I was nodding along with the people saying "list of lists" until I

reread this quote. A list of tuples seems most appropriate to me.

  
[1] , as quoted by Bill

Lubanovic in _Introducing Python_

--
Michael F. Stemper
This sentence no verb.

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


Re: Re: Re: Re: Any possible type alias that can also set a default value for a function arg?

2023-10-19 Thread Chris Angelico via Python-list
On Thu, 19 Oct 2023 at 19:34, Karsten Hilbert  wrote:
>
> > > As per my recent foray into abusing existence-checking for Singleton 
> > > assurance
> > > along such lines as
> > >
> > > >>> try: self.initialized
> > > >>> except AttributeError: print('first instantiation'); self.initialized 
> > > >>> = True
> > >
> > > and then changing that to
> > >
> > > >>> try: self.initialized:bool
> >
> > But that's not equivalent code.
>
> I learned as much (RHS vs LHS).
>
> But it did not _intuitively_ resonate with the sentiment
> "type annotation does not change the running of code".

Unfortunately, that simply means that your intuition was wrong. It
doesn't change my prior statement.

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


Aw: Re: Re: Re: Any possible type alias that can also set a default value for a function arg?

2023-10-19 Thread Karsten Hilbert via Python-list
> > As per my recent foray into abusing existence-checking for Singleton 
> > assurance
> > along such lines as
> >
> > >>> try: self.initialized
> > >>> except AttributeError: print('first instantiation'); self.initialized = 
> > >>> True
> >
> > and then changing that to
> >
> > >>> try: self.initialized:bool
>
> But that's not equivalent code.

I learned as much (RHS vs LHS).

But it did not _intuitively_ resonate with the sentiment
"type annotation does not change the running of code".

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


Re: Re: Re: Any possible type alias that can also set a default value for a function arg?

2023-10-19 Thread Chris Angelico via Python-list
On Thu, 19 Oct 2023 at 18:25, Karsten Hilbert  wrote:
>
> > > > Fundamentally no, at least not without some shenanigans. Type hints do
> > > > not affect the regular running of the code,
> > >
> > > Except when they do ;-)
> > >
> > > ... depending on what counts as (valid) code ...
> > >
> > > In Python a distinction can be made between "runnable" and "valid" :-D
> > >
> >
> > Can you give a counter-example?
>
> As per my recent foray into abusing existence-checking for Singleton assurance
> along such lines as
>
> >>> try: self.initialized
> >>> except AttributeError: print('first instantiation'); self.initialized = 
> >>> True
>
> and then changing that to
>
> >>> try: self.initialized:bool

But that's not equivalent code. You might just as well say that the
ellipsis here suddenly changes the code:

self.initialized
self.initialized = ...

These are completely different, and they behave differently. Both are
valid, but they mean different things.

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


Aw: Re: Re: Any possible type alias that can also set a default value for a function arg?

2023-10-19 Thread Karsten Hilbert via Python-list
> > > Fundamentally no, at least not without some shenanigans. Type hints do
> > > not affect the regular running of the code,
> >
> > Except when they do ;-)
> >
> > ... depending on what counts as (valid) code ...
> >
> > In Python a distinction can be made between "runnable" and "valid" :-D
> >
>
> Can you give a counter-example?

As per my recent foray into abusing existence-checking for Singleton assurance
along such lines as

>>> try: self.initialized
>>> except AttributeError: print('first instantiation'); self.initialized = True

and then changing that to

>>> try: self.initialized:bool

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


Re: Re: Any possible type alias that can also set a default value for a function arg?

2023-10-19 Thread Chris Angelico via Python-list
On Thu, 19 Oct 2023 at 18:04, Karsten Hilbert  wrote:
>
> > > or something like that. Basically, any way to avoid writing `= None` over 
> > > and over again.
> >
> > Fundamentally no, at least not without some shenanigans. Type hints do
> > not affect the regular running of the code,
>
> Except when they do ;-)
>
> ... depending on what counts as (valid) code ...
>
> In Python a distinction can be made between "runnable" and "valid" :-D
>

Can you give a counter-example? I mean, yes, any code can be written
that inspects the annotations at runtime and makes whatever changes it
likes, but that's part of what I described as "shenanigans".

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


RE: RE: Weak Type Ability for Python

2023-04-13 Thread avi.e.gross
Yes, Dave, there are many data structures that can be used to maintain a
list of output types the class claims to support. Dictionaries have the
interesting property that you can presumably have a value that holds a
member function to access the way the key specifies.

Ideally, the order is not important for what I am looking for. Generally, I
would think that any class like the ones I have been discussing, would want
to broadcast a fairly short list of output types it would support.

Of course, if you look at my date example, the list could be quite big but
if you simply use something like strftime() for many of the formats, perhaps
you may not need to list all possible ones. Any valid format could be
accepted as an argument and passed to such a utility function. Your
dictionary might simply store some commonly used formats known to work.

But I repeat. This is not a serious request. I know how to build limited
functionality like this if I ever want it, but wonder if anyone has ever
created a proposal for some protocols and perhaps helpers like say an
embedded object that handles aspects of it once you have initialized your
dictionary and also handles requests to show part of what is stored for any
shoppers wondering if you are compatible with their needs.

-Original Message-
From: Python-list  On
Behalf Of 2qdxy4rzwzuui...@potatochowder.com
Sent: Thursday, April 13, 2023 10:27 PM
To: python-list@python.org
Subject: Re: RE: Weak Type Ability for Python

On 2023-04-13 at 22:14:25 -0400,
avi.e.gr...@gmail.com wrote:

> I am looking at a data structure that is an object of some class and
> stores the data in any way that it feels like. But it may be a bit of
> a chameleon that shows one face or another as needed. I can write code
> now that simply adds various access methods to the class used and also
> provides a way to query if it supports some interfaces.

Python dicts act mostly like hash tables.  All by themselves, hash
tables are unordered (and in return for giving up that order, you get
O(1) access to an item if you know its key).

But when you ask a Python dict for the keys, you always get them in the
same order, skipping those that have been deleted since the last time
you asked, and appending the new keys to the end of the list in the
order in which you added them.

There's your chameleon.
-- 
https://mail.python.org/mailman/listinfo/python-list

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


Re: RE: Weak Type Ability for Python

2023-04-13 Thread 2QdxY4RzWzUUiLuE
On 2023-04-13 at 22:14:25 -0400,
avi.e.gr...@gmail.com wrote:

> I am looking at a data structure that is an object of some class and
> stores the data in any way that it feels like. But it may be a bit of
> a chameleon that shows one face or another as needed. I can write code
> now that simply adds various access methods to the class used and also
> provides a way to query if it supports some interfaces.

Python dicts act mostly like hash tables.  All by themselves, hash
tables are unordered (and in return for giving up that order, you get
O(1) access to an item if you know its key).

But when you ask a Python dict for the keys, you always get them in the
same order, skipping those that have been deleted since the last time
you asked, and appending the new keys to the end of the list in the
order in which you added them.

There's your chameleon.
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: RE: Weak Type Ability for Python

2023-04-13 Thread avi.e.gross
..@gmail.com; python-list@python.org
Subject: Re: RE: Weak Type Ability for Python

On 14/04/2023 00:25, avi.e.gr...@gmail.com wrote:

> Is there any concept in Python of storing information in some way, such as
> text, and implementing various ideas or interfaces so that you can query if
> the contents are willing and able to be viewed in one of many other ways?

Are you talking about something like a C union type (or a Pascal
variant record)? I'm not aware of any such feature in Python but
have often thought it would be a nice to have for the rare cases
where its useful.

> Or it may be storing text in some format but the object is willing to
> transform the text into one of several other formats when needed. The text
> may also have attributes such as whether it is in English or Hungarian or is
> mixed-language.

Or are you meaning something like an extension to the
struct module that can interpret a bytestring in any way
defined by a format string?

> basis. But do some languages have some support within the language itself?

The closest to what you seem to mean is, I think, the C union
type, at least in my experience. But you have to define all
the ways you can interpret the type up front in the type
definition.

> My reason for asking, is based on the discussion. If I want to use plus with
> an integer and a string, it may be reasonable for the interpreter to ask one
> or the other operand if they are able to be seen another way.

You can achieve that in a slightly different way in Tcl which
allows you to redefine all the operators (commands in Tcl-speak)
in the language so redefining plus is easy. Doing it based on
type is more tricky but doable.

> Unfortunately, if they BOTH are flexible, how do you decide whether to add
> them as numbers or concatenate them as strings?

Yes, that's where it becomes a designer's arbitrary choice.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



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


Re: RE: Weak Type Ability for Python

2023-04-13 Thread Alan Gauld
On 14/04/2023 00:25, avi.e.gr...@gmail.com wrote:

> Is there any concept in Python of storing information in some way, such as
> text, and implementing various ideas or interfaces so that you can query if
> the contents are willing and able to be viewed in one of many other ways?

Are you talking about something like a C union type (or a Pascal
variant record)? I'm not aware of any such feature in Python but
have often thought it would be a nice to have for the rare cases
where its useful.

> Or it may be storing text in some format but the object is willing to
> transform the text into one of several other formats when needed. The text
> may also have attributes such as whether it is in English or Hungarian or is
> mixed-language.

Or are you meaning something like an extension to the
struct module that can interpret a bytestring in any way
defined by a format string?

> basis. But do some languages have some support within the language itself?

The closest to what you seem to mean is, I think, the C union
type, at least in my experience. But you have to define all
the ways you can interpret the type up front in the type
definition.

> My reason for asking, is based on the discussion. If I want to use plus with
> an integer and a string, it may be reasonable for the interpreter to ask one
> or the other operand if they are able to be seen another way.

You can achieve that in a slightly different way in Tcl which
allows you to redefine all the operators (commands in Tcl-speak)
in the language so redefining plus is easy. Doing it based on
type is more tricky but doable.

> Unfortunately, if they BOTH are flexible, how do you decide whether to add
> them as numbers or concatenate them as strings?

Yes, that's where it becomes a designer's arbitrary choice.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: RE: Fast full-text searching in Python (job for Whoosh?)

2023-03-08 Thread Dino

On 3/7/2023 2:02 PM, avi.e.gr...@gmail.com wrote:

Some of the discussions here leave me confused as the info we think we got
early does not last long intact and often morphs into something else and we
find much of the discussion is misdirected or wasted.



Apologies. I'm the OP and also the OS (original sinner). My "mistake" 
was to go for a "stream of consciousness" kind of question, rather than 
a well researched and thought out one.


You are correct, Avi. I have a simple web UI, I came across the Whoosh 
video and got infatuated with the idea that Whoosh could be used for 
create a autofill function, as my backend is already Python/Flask. As 
many have observed and as I have also quickly realized, Whoosh was 
overkill for my use case. In the meantime people started asking 
questions, I responded and, before you know it, we are all discussing 
the intricacies of JavaScript web development in a Python forum. Should 
I have stopped them? How?


One thing is for sure: I am really grateful that so many used so much of 
their time to help.


A big thank you to each of you, friends.

Dino


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


Re: RE: Fast full-text searching in Python (job for Whoosh?)

2023-03-06 Thread Dino
Thank you for taking the time to write such a detailed answer, Avi. And 
apologies for not providing more info from the get go.


What I am trying to achieve here is supporting autocomplete (no pun 
intended) in a web form field, hence the -i case insensitive example in 
my initial question.


Your points are all good, and my original question was a bit rushed. I 
guess that the problem was that I saw this video:


https://www.youtube.com/watch?v=gRvZbYtwTeo_channel=NextDayVideo

The idea that someone types into an input field and matches start 
dancing in the browser made me think that this was exactly what I 
needed, and hence I figured that asking here about Whoosh would be a 
good idea. I know realize that Whoosh would be overkill for my use-case, 
as a simple (case insensitive) query substring would get me 90% of what 
I want. Speed is in the order of a few milliseconds out of the box, 
which is chump change in the context of a web UI.


Thank you again for taking the time to look at my question

Dino

On 3/5/2023 10:56 PM, avi.e.gr...@gmail.com wrote:

Dino, Sending lots of data to an archived forum is not a great idea. I
snipped most of it out below as not to replicate it.

Your question does not look difficult unless your real question is about
speed. Realistically, much of the time spent generally is in reading in a
file and the actual search can be quite rapid with a wide range of methods.

The data looks boring enough and seems to not have much structure other than
one comma possibly separating two fields. Do you want the data as one wide
filed or perhaps in two parts, which a CSV file is normally used to
represent. Do you ever have questions like tell me all cars whose name
begins with the letter D and has a V6 engine? If so, you may want more than
a vanilla search.

What exactly do you want to search for? Is it a set of built-in searches or
something the user types in?

The data seems to be sorted by the first field and then by the second and I
did not check if some searches might be ambiguous. Can there be many entries
containing III? Yep. Can the same words like Cruiser or Hybrid appear?

So is this a one-time search or multiple searches once loaded as in a
service that stays resident and fields requests. The latter may be worth
speeding up.

I don't NEED to know any of this but want you to know that the answer may
depend on this and similar factors. We had a long discussion lately on
whether to search using regular expressions or string methods. If your data
is meant to be used once, you may not even need to read the file into
memory, but read something like a line at a time and test it. Or, if you end
up with more data like how many cylinders a car has, it may be time to read
it in not just to a list of lines or such data structures, but get
numpy/pandas involved and use their many search methods in something like a
data.frame.

Of course if you are worried about portability, keep using Get Regular
Expression Print.

Your example was:

  $ grep -i v60 all_cars_unique.csv
  Genesis,GV60
  Volvo,V60

You seem to have wanted case folding and that is NOT a normal search. And
your search is matching anything on any line. If you wanted only a complete
field, such as all text after a comma to the end of the line, you could use
grep specifications to say that.

But once inside python, you would need to make choices depending on what
kind of searches you want to allow but also things like do you want all
matching lines shown if you search for say "a" ...



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


RE: RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread avi.e.gross
Alan,

I got divorced from the C++ crowd decades ago when I left Bell Labs. You are 
making me glad I did!

I do accept your suggestion that you can be idiomatic if you follow the common 
methods of whatever language you use. That will take you quite far as long as 
you are not a total slave to it.

But I note some idioms catch on and some are imposed and some become almost 
moot. I am not sure which aspects of C++ have changed drastically and may go 
re-study the modern version as I was a very early adoptee within AT and saw 
changes even back then. 

But I consider something like the half dozen or so major print variants in 
python and wonder how much longer some of them will be seen as worth using, let 
alone idiomatic. Something like an fstring may dominate for many purposes.

I know in R, that I used to use some convoluted methods to assemble output that 
I often now ignore once a "glue" package gave me something similar to fstring 
abilities where all kinds of variables and calculations can now be embedded 
withing a string to be dynamically evaluated in your current environment. Some 
of the documents I write now similarly embed parts of programs and also have an 
inline ability to evaluate small amounts of code in one of many languages  that 
inserts directly into the text as it is being typeset.

So I see moving targets where what was formerly at or near the state of the 
art, becomes passé. So much of my early work rapidly became trivial or 
irrelevant or never caught on or became lost in an environment I no longer 
used. To keep going forward often involves leaving things behind.

Some new features in Python will be interesting to watch. I mentioned the match 
statement. I was using a similar construct in a JVM language called SCALA ages 
ago.  There it was a sort of core part of the language and often replaced 
constructs normally used by other languages such as many simple or nested IF 
statements. I am sure someone will point out where they borrowed parts from or 
who did it better, but what I am saying is that I want to see if it becomes an 
exotic addition to Python in a way that loosely melds, or if it becomes the 
PYTHONIC way ...



-Original Message-
From: Alan Gauld  
Sent: Saturday, March 4, 2023 1:38 PM
To: avi.e.gr...@gmail.com; python-list@python.org
Subject: Re: RE: Which more Pythonic - self.__class__ or type(self)?

On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote:
> 
> Of course each language has commonly used idioms 
> 

That's the point, the correct term is probably "idiomatic"
rather than "pythonic" but it is a defacto standard that
idiomatic Python has become known as Pythonic. I don't
think that's a problem. And at least we aren't in the C++
situation where almost everything that was idiomatic up
until 1999 is now deemed an anti-pattern and they have
standard library modules to try and guide you to use the
"correct" idioms!

But being Pythonic is still a much more loose term and
the community less stressed about it than their C++
cousins where it has almost reached a religious fervour!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



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


Re: RE: Which more Pythonic - self.__class__ or type(self)?

2023-03-04 Thread Alan Gauld
On 04/03/2023 17:38, avi.e.gr...@gmail.com wrote:
> 
> Of course each language has commonly used idioms 
> 

That's the point, the correct term is probably "idiomatic"
rather than "pythonic" but it is a defacto standard that
idiomatic Python has become known as Pythonic. I don't
think that's a problem. And at least we aren't in the C++
situation where almost everything that was idiomatic up
until 1999 is now deemed an anti-pattern and they have
standard library modules to try and guide you to use the
"correct" idioms!

But being Pythonic is still a much more loose term and
the community less stressed about it than their C++
cousins where it has almost reached a religious fervour!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


RE: Re: Python 3.10 Fizzbuzz

2023-02-28 Thread avi.e.gross
Karsten,

Would it be OK if we paused this discussion a day till February is History?

Sarcasm aside, I repeat, the word black has many unrelated meanings as
presumably this case includes. And for those who do not keep close track of
the local US nonsense, February has for some reason been dedicated to be a
National Black History Month.

Can software violate a code for human conduct? The recent AI news suggests
it does! LOL!

But you know, if you hire a program to tell you if your code passes a
designated series of tests and it just points out where they did not, and
suggest changes that may put you in alignment, that by itself is not
abusive. But if you did not ask for their opinion, yes, it can be annoying
as being unsolicited.

Humans can be touchy and lose context. I have people in my life who
magically ignore my carefully thought-out phrases like "If ..." by acting as
if I had said something rather than IF something. Worse, they hear
abstractions too concretely. I might be discussing COVID and saying "If
COVID was a lethal as it used to be ..." and they interject BUT IT ISN'T.
OK, listen again. I am abstract and trying to make a point. The fact that
you think it isn't is nice to note but hardly relevant to a WHAT IF
question.

So a program designed by programmers, a few of whom are not well known for
how they interact with humans but who nonetheless insist on designed user
interfaces by themselves, may well come across negatively. The reality is
humans vary tremendously and one may appreciate feedback as a way to improve
and get out of the red and the other will assume it is a put down that
leaves them black and blue, even when the words are the same.

-Original Message-
From: Python-list  On
Behalf Of Karsten Hilbert
Sent: Tuesday, February 28, 2023 2:44 PM
To: pythonl...@danceswithmice.info
Cc: python-list@python.org
Subject: Aw: Re: Python 3.10 Fizzbuzz

> > I've never tried Black or any other code formatter, but I'm sure we 
> > wouldn't get on.
>
> Does this suggest, that because Black doesn't respect other people's 
> opinions and feelings, that it wouldn't meet the PSF's Code of Conduct?

That much depends on The Measure Of A Man.

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

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


RE: RE: How to read file content and send email on Debian Bullseye

2023-02-05 Thread avi.e.gross
Bart,

Some really decent cron jobs can be written without using anything complex.

I get it  now that perhaps your motivation is more about finding an excuse
to learn python better. The reality is there is not much that python cannot
do if other programming languages and environments can do them so asking if
it can do it feels a tad naïve. Like many languages, python is very
extendable with all kinds of modules so often instead of doing something
totally on your own, you can find something that does much of the hard work
for you, too. 

Yes, python can nicely read in lines from a log and compare them to a fixed
string or pattern and either find or not find what you ask for.

But a shell script can be written in a few minutes that simply gets the
string for the current date in the format you want, interpolates it in a
regular expression, calls grep or a dozen other programs that handle a
command line argument, and if it returns a single line, you send one email
and if none you send another and if more than one, you may have done it
wrong. Some such programs, like AWK are designed mainly to do exactly
something like you ask and examine each input line against a series of
patterns. Sending an email though is not always something easy to do from
within a program like that but a shell script that checks how it ends may do
that part.

If you are on a specific machine and only need to solve the problem on that
machine or something similar, this seems straightforward. 

My impression is you want to match a line in the log file that may look like
it should  match "anything", then some keyword or so that specifies all
lines about this particular upload on every day, then matches another
"anything" up to something that exactly matches the date for today, and
maybe match another "anything" to the end of the line. It can be a fairly
straightforward regular expression if the data has a regular component in
the formatting. Grep, sed, awk, perl and others can do this and others. 

Could you do this faster in python? Maybe. Arguably if speed is a major
issue, write it in some compiled language like C++. 

But if your data is very regular such as the entry will have some key phrase
between the 12th and 19th characters and the date will be exactly in another
exact region, then you certainly can skip regular expressions and read each
line and examine the substrings for equality. You may also speed it a bit if
you exit any such loop as soon as you find what you are looking for. 

I note if your log file is big but not very busy, and you are pretty sure
the entry will be in the last few (maybe hundred) lines, some may use the
tail command and pipe the text it returns to whatever is processing the
data. There are many ways to do what you want.

But you improve your chances of getting an answer if you ask it more
clearly. There have been people (maybe just one) who have been posing
questions of a rather vague nature and then not responding as others debate
it in seemingly random directions. You are interacting nicely but some of us
have become hesitant to jump in until they see if the request is
well-intended. You do sound like you know quite a bit and your question
could have  been closer to saying that you know several ways to do it
(include examples or at least outlines) and wonder if some ways are better
or more pythonic or ...

So if people keep wondering what you want, it is because the people here are
not generally interested in doing homework or complete programs for people.
If you ask us how to generate a string with the current date, and cannot
just find it on your own, we might answer. If you want to know how to store
a date as an object including the current time, and also convert the text on
a line in the log file to make another such date object and then be able to
compare them and be able to include in your email how LONG AGO the upload
was done, that would be another more specific request. If you are not sure
how python does regular expressions, ...

Otherwise, what you are asking for may not be BASIC for some but seems
relatively straightforward to some of us and we sort of may be  wondering
if we are missing anything?

Good Luck,

^Avi

-Original Message-
From: Python-list  On
Behalf Of ^Bart
Sent: Sunday, February 5, 2023 8:58 AM
To: python-list@python.org
Subject: Re: RE: How to read file content and send email on Debian Bullseye

> For example, try to do whatever parts you know how to do and when some 
> part fails or is missing, ask.

You're right but first of all I wrote what I'd like to do and if Python
could be the best choice about it! :)

> I might have replied to you directly if your email email address did 
> not look like you want no SPAM, LOL!

Ahaha! I think you know what is spam and what is a reply\answer to a post
request so you can feel free to use also my email! :)

> The cron stuff is not really relevant and it seems your idea is 

Re: RE: How to read file content and send email on Debian Bullseye

2023-02-05 Thread ^Bart

For example, try to do whatever parts you know how to do and when some part
fails or is missing, ask.


You're right but first of all I wrote what I'd like to do and if Python 
could be the best choice about it! :)



I might have replied to you directly if your email email address did not
look like you want no SPAM, LOL!


Ahaha! I think you know what is spam and what is a reply\answer to a 
post request so you can feel free to use also my email! :)



The cron stuff is not really relevant and it seems your idea is to read a
part or all of a log file, parse the lines in some way and find a line that
either matches what you need or fail to find it. Either way you want to send
an email out with an appropriate content.


You got the point!


Which part of that do you not know how to do in python? Have you done some
reading or looking?


Like what I wrote above I didn't know if Python can does what I need and 
if to use Python is a good way I'll start to study how to do it! :)


In my past I used Python for Arduino programming or to do easy things, 
what I should do now is little more complex but I understood from years 
and years by the Python's powers you can do everything! LOL! :)


Regards.
^Bart
--
https://mail.python.org/mailman/listinfo/python-list


Re: RE: RE: bool and int

2023-01-28 Thread Dino



you have your reasons, and I was tempted to stop there, but... I have to 
pick this...


On 1/26/2023 10:09 PM, avi.e.gr...@gmail.com wrote:

  You can often borrow
ideas and code from an online search and hopefully cobble "a" solution
together that works well enough. Of course it may suddenly fall apart.


also carefully designed systems that are the work of experts may 
suddenly fall apart.


Thank you for all the time you have used to address the points I raised. 
It was interesting reading.


Dino

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


RE: RE: bool and int

2023-01-26 Thread avi.e.gross
[Dino has a deliberately invalid email address so sending him anything
privately is not an option.]

Dino,

I would agree with you that for some purposes, you do NOT need to dig deep
into a language to get fairly routine things done. You can often borrow
ideas and code from an online search and hopefully cobble "a" solution
together that works well enough. Of course it may suddenly fall apart. An
example is code written that assumes 4 specific files exist in the current
directory and unconditionally reads them and does stuff and eventually
overwrites some other file with new data. OOPS, what does the program do it
one or more files do not exist in the current directory under those exact
names? Does it check if they exist and exit gracefully, or start throwing
error messages as the code blindly proceeds on trying to change variables
that were never created and so on, and then end with perhaps an emptied file
and ruin lots of things?

Too many examples you get from the internet are a bit like that. They often
just tell you how to do something specific but leave out lots of details
that are a good idea for many kinds of code. And some adjustments you make
may break things and produce a result you trust but that is actually wrong. 

So if you find something you don't like about the language, guess what. You
have very little standing if you never learned much more than what it took
to copy some code.  You are likely to be told things by others ranging from
suggesting you need to do it another way or that the language is doing
exactly what was designed and suggestions you go back to school and get a
proper education and then the answer may be obvious.

It truly does NOT matter what YOU think should happen unless you point to
documentation that says something else should have happened.

I will skip a lengthier reply but am thinking how some languages use a
boxing/unboxing approach to wrap native "objects" like an integer. In many
cases, your program is allowed to treat this as either a wrapped object or
unboxed as needed and the compiler or interpreter keeps making changes
behind the scenes so you see it as needed. In a sense, Booleans are a
restricted form of integer and are viewed one of several ways. Python goes
many steps further and has a concept of truthy that maps practically
anything to True or False.

The bottom line is not that Python or any language is wrong or right or
great or horrible. It is that based on your own admission, you have not
taken steps to understand more than you have to and thus are in a weak
position to argue anything. Not because any of us are smarter in some sense,
but because some of us do study more intensively and come ready to
re-evaluate our ideas when we encounter others. What Python does in the
situation discussed is pretty much what an assortment of languages include
many C-based ones do. If it happens that your background is limited, fine.
Many of us here have been exposed to the ideas in 5 or a dozen or literally
hundreds of languages and variants and are well aware that some languages
treat Booleans differently. But note we are posting on this forum so we
generally don't find it that objectionable the way Python has chosen. 

We welcome well-intentioned discussions and the question is not at all
stupid. But our answers may not be being seen as reasonable and that can be
of some concern. The answer remains that the language was designed this way
and many are happy with the design. Interestingly, I wonder if anyone has
designed an alternate object type that can be used mostly in place of
Booleans but which imposes changes and restrictions so trying to add a
Boolean to an integer, or vice versa, results in an error. Python is
flexible enough to do that and perhaps there already is a module out there
...


-Original Message-
From: Python-list  On
Behalf Of Dino
Sent: Thursday, January 26, 2023 9:26 AM
To: python-list@python.org
Subject: Re: RE: bool and int


Wow. That was quite a message and an interesting read. Tempted to go deep
and say what I agree and what I disagree with, but there are two
issues: 1) time 2) I will soon be at a disadvantage discussing with people
(you or others) who know more than me (which doesn't make them right
necessarily, but certainly they'll have the upper-hand in a discussion).

Personally, in the first part of my career I got into the habit of learning
things fast, sometimes superficially I confess, and then get stuff done
hopefully within time and budget. Not the recommended approach if you need
to build software for a nuclear plant. An OK approach (within reason) if you
build websites or custom solutions for this or that organization and the
budget is what it is. After all, technology moves sooo fast, and what we
learn in detail today is bound to be old and possibly useless 5 years down
the road.

Also, I argue that there is value in having familiarity with lots of
different technologies (front-end and b

Re: RE: bool and int

2023-01-26 Thread Dino



Wow. That was quite a message and an interesting read. Tempted to go 
deep and say what I agree and what I disagree with, but there are two 
issues: 1) time 2) I will soon be at a disadvantage discussing with 
people (you or others) who know more than me (which doesn't make them 
right necessarily, but certainly they'll have the upper-hand in a 
discussion).


Personally, in the first part of my career I got into the habit of 
learning things fast, sometimes superficially I confess, and then get 
stuff done hopefully within time and budget. Not the recommended 
approach if you need to build software for a nuclear plant. An OK 
approach (within reason) if you build websites or custom solutions for 
this or that organization and the budget is what it is. After all, 
technology moves sooo fast, and what we learn in detail today is bound 
to be old and possibly useless 5 years down the road.


Also, I argue that there is value in having familiarity with lots of 
different technologies (front-end and back-end) and knowing (or at 
lease, having a sense) of how they can all be made play together with an 
appreciation of the different challenges and benefits that each domain 
offers.


Anyway, everything is equivalent to a Turing machine and IA will screw 
everyone, including programmers, eventually.


Thanks again and have a great day

Dino

On 1/25/2023 9:14 PM, avi.e.gr...@gmail.com wrote:

Dino,

There is no such things as a "principle of least surprise" or if you insist
there is, I can nominate many more such "rules" such as "the principle of
get out of my way and let me do what I want!"

Computer languages with too many rules are sometimes next to unusable in
practical situations.

I am neither defending or attacking choices Python or other languages have
made. I merely observe and agree to use languages carefully and as
documented.


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


RE: RE: NoneType List

2023-01-02 Thread avi.e.gross
Alan,

I stand corrected as my path never led me back to any form of PASCAL. And, 
frankly, my path rarely led me again to having to do what we describe as 
twiddling bits with the minor exception when doing something like setting the 
bits needed to specify what permissions should be associated with a file in the 
UNIX world.

What you say is largely true of programming languages in general. Many are 
created with some paradigm in mind that sounds like an idea until it meets 
reality and compromises and adjustments are made. 

When new languages follow that have the ability to gain from prior experience, 
they may indeed come up with a more nuanced paradigm. I have been studying 
JavaScript and Node.js lately, for no special reason, and see that as an 
example of sorts. The former was largely created to run inside a browser and 
NOT do anything harmful to the user's machine. Lots of parts normally included 
in other programming languages such as Python were not only deliberately left 
out but the code often monitors some things to make sure you do not try 
anything sneaky.

But the language took off and evolved and at some point seemed to people to be 
a good tool to use on their servers too, and especially since the two sides 
could exchange relatively live objects such as with JSON. The paradigm had to 
change as most such programs written in what is now Node.js or other names, 
actually had to do things to the server including reading and writing files. So 
they had to add quite a bit and struggled at times to keep other parts of the 
languages similar as they evolved semi-independently. In my opinion, it remains 
a futile work in progress.

Has Python managed the version 2 versus version 3 schism to the point where 
enough users have migrated their code and new users avoid version 2? Other 
languages have had to split when big enough changes were made. 

-Original Message-
From: Alan Gauld  
Sent: Monday, January 2, 2023 3:01 AM
To: avi.e.gr...@gmail.com; python-list@python.org
Subject: Re: RE: NoneType List

On 02/01/2023 02:14, avi.e.gr...@gmail.com wrote:
> I used PASCAL before C and I felt like I was wearing a straitjacket at 
> times in PASCAL when I was trying to write encryption/decryption 
> functions and had to find ways to fiddle with bits. Similar things 
> were easy in C, and are even easier in many more recent languages such as 
> Python.

That's true of pure Pascal. But Thomas was talking about Turbo Pascal which had 
extra functions and features for all those "real world" type things. (And you 
could insert some inline assembler if all else failed) It also relaxed the 
ludicrously strict typing slightly. Turbo Pascal made Pascal a joy and I still 
use Delphi for Windows programming today.

TP also introduced classes to Pascal (although Apple had already done so for 
the Mac and Borland basically ported the syntax to the PC).

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



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


Re: RE: NoneType List

2023-01-02 Thread Alan Gauld
On 02/01/2023 02:14, avi.e.gr...@gmail.com wrote:
> I used PASCAL before C and I felt like I was wearing a straitjacket at times
> in PASCAL when I was trying to write encryption/decryption functions and had
> to find ways to fiddle with bits. Similar things were easy in C, and are
> even easier in many more recent languages such as Python. 

That's true of pure Pascal. But Thomas was talking about Turbo Pascal
which had extra functions and features for all those "real world" type
things. (And you could insert some inline assembler if all else failed)
It also relaxed the ludicrously strict typing slightly. Turbo Pascal
made Pascal a joy and I still use Delphi for Windows programming today.

TP also introduced classes to Pascal (although Apple had already done
so for the Mac and Borland basically ported the syntax to the PC).

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: Re: Long running process - how to speed up?

2022-02-20 Thread Shaozhong SHI
On Sat, 19 Feb 2022 at 18:51, Alan Gauld  wrote:

> On 19/02/2022 11:28, Shaozhong SHI wrote:
>
> > I have a cvs file of 932956 row
>
> That's not a lot in modern computing terms.
>
> > and have to have time.sleep in a Python
> > script.
>
> Why? Is it a requirement by your customer? Your manager?
> time.sleep() is not usually helpful if you want to do
> things quickly.
>
> > It takes a long time to process.
>
> What is a "long time"? minutes? hours? days? weeks?
>
> It should take a million times as long as it takes to
> process one row. But you have given no clue what you
> are doing in each row.
> - reading a database?
> - reading from the network? or the internet?
> - writing to a database? or the internet?
> - performing highly complex math operations?
>
> Or perhaps the processing load is in analyzing the totality
> of the data after reading it all? A very different type
> of problem. But we just don't know.
>
> All of these factors will affect performance.
>
> > How can I speed up the processing?
>
> It all depends on the processing.
> You could try profiling your code to see where the time is spent.
>
> > Can I do multi-processing?
>
> Of course. But there is no guarantee that will speed things
> up if there is a bottleneck on a single resource somewhere.
> But it might be possible to divide and conquer and get better
> speed. It all depends on what you are doing. We can't tell.
>
> We cannot answer such a vague question with any specific
> solution.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
> --
> https://mail.python.org/mailman/listinfo/python-list


Do not know these answers yet.  Now, it appeared to hang/stop at a point
and does not move on.

Regards,

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


Re: Re: Long running process - how to speed up?

2022-02-19 Thread Chris Angelico
On Sat, 19 Feb 2022 at 22:59, Karsten Hilbert  wrote:
>
> > > I have a cvs file of 932956 row and have to have time.sleep in a Python
> > > script.  It takes a long time to process.
> > >
> > > How can I speed up the processing?  Can I do multi-processing?
> > >
> > Remove the time.sleep()?
>
> He's attesting to only having "time.sleep" in there...
>
> I doubt removing that will help much ;-)

I honestly don't understand the question, hence offering the
stupidly-obvious suggestion in the hope that it would result in a
better question. A million rows of CSV, on its own, isn't all that
much to process, so it must be the processing itself (of which we have
no information other than this reference to time.sleep) that takes all
the time.

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


RE: Re: The task is to invent names for things

2021-10-28 Thread Avi Gross via Python-list
Names can be taken too far as the same variable may have different
connotations in one place than another.

Say I am counting how many of something and incrementing variable HowMany as
I go along and initialized to zero. Then I want to test if I have any and
instead of:

if (HowMany > 0)

I decide to be cute and depend on the truthiness of HowMany like:

if (HowMany)

The latter is a tad hard to parse for some people and if it had been named
WeHaveAny then the code would sort of make sense:

if (WeHaveAny)

Somewhere else in the code some other names might make sense and make the
program easier to read.

So, the obvious solution is to ask the language, like Python, to allow
variables that are synonyms. In languages with pointers, this can often be
done fairly easily. In some languages with some optimizations, it can be
dangerous as some copies of this kind can later be changed to an actual copy
when the underlying data changes.

So, since at the moment you might not be able to do this:

HowMany = 0
alias HowMany WeHaveAny

Then if this feature matters to you, you could cautiously write code that
declares a second variable and copies either the current value of the first
or a Boolean true/false.

I am sure many of us (meaning me) have often named a variable and later
reconsidered once we saw the role it plays in various parts of the program
and had to go back and change everything. As other have noted, it is not a
trivial task and really good names often end up being really long names
which are also a pain especially when other really long names start with the
same characters. Compilers don't care but humans reading the code may give
up!

Worse, many times the code consists of longer combinations and trying to
keep within reasonable (printable) line lengths gets hard.

MyHumoungousDictionaryContainingElectionResults[SomeCountyInSomeStateOfTheUS
] =
MyHumoungousDictionaryContainingElectionResults[SomeCountyInSomeStateOfTheUS
] + TheOfficialCertifiedVoteCountOfThisRegion




-Original Message-
From: Python-list  On
Behalf Of Karsten Hilbert
Sent: Thursday, October 28, 2021 2:50 AM
Cc: python-list@python.org
Subject: Aw: Re: The task is to invent names for things

> > I don't know. A mediocre name conveys at least some information, and 
> > that seems to be better than none. On the other hand it might be 
> > just enough to lead the reader astray which wouldn't happen with a 
> > non-sensical name.

I was thinking that a nonsensical name might lead readers to go beyond the
name when trying to understand code, and would prompt me to improve upon the
name upon reading my own code (and having acquired, likely, a better
understanding of the concept that's to be named).

Karsten

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

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


Re: Re: sum() vs. loop

2021-10-12 Thread Chris Angelico
On Wed, Oct 13, 2021 at 12:36 PM Avi Gross via Python-list
 wrote:
>
> Alan,
>
> I am also wondering about that zip() function call to bind the two lists
> into a sort of iterator object. Presumably that calls the iterator N times.
> I did a test where I made two list called A and B and used zip to make an
> object holding the two and then removed A and B. I was able to print the
> list of tuples just fine with print(list(C)) so clearly it is not so much a
> pure iterator as one that holds yet another copy of both lists!

What do you mean by "removed" here? Simply removing the name that
refers to it doesn't destroy the list; an iterator will keep the list
alive.

> Now the old-fashioned C way, might simply use old fashioned but highly
> efficient pointer arithmetic to move through two lists or arrays or whatever
> of the same length adding as it goes so one pass period. Or it could use
> indexing as in sum += A[i] * B[i] ...

It's basically that, yup. Of course, it's not defined by C behaviour,
but the effect is the same.

> Is there a version of zip() or an alternative that might be faster? In
> particular, I was wondering the usual question of what happens if you might
> abort early if something is noticed, like say a negative number. If you
> pre-calculated and copied 100,000 items and abort after 5, ...

The purpose of zip is to represent the concept of iterating over two
things at once. Aborting early is fine, just as it is with other
iterations. It's incredibly convenient to be able to write something
like:

for tradegood, value in zip(data.tradegoods, data.tradevalues):
...

(Not exact code, but something very similar to what I've done while
parsing game savefiles.)

> I note an approach in some languages using a vectorized approach may be
> faster. Forget lists and as long as A and B are equal length vectors or
> arrays as in numpy, there are ways to ask to multiply two arrays in
> vectorized fashion so effectively you can say something akin to:
>
> sum(A*B)
>
> The above may be highly efficient especially if the underlying code is in
> C/C++.

Or Fortran :)

> If there is no objection in your code to using the numpy module and the
> corresponding objects you can make a similar test with something like this:
>
> And the function they seem to want is the dot product of two such arrays as
> in numpy.dot(A, B) provides the sum of the many products of corresponding
> entries in A and B.

If you're worried about the performance of summing pairwise products
of numbers, you should probably be using numpy already. It's
intellectually entertaining to explore the performance implications of
various types of iteration, but numpy is basically always going to win
any race that involves large numbers of floats :) It's like having a
hundred-yard-dash involving a bunch of schoolchildren, and one Olympic
runner - which of the schoolkids was fastest?

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


RE: Re: sum() vs. loop

2021-10-12 Thread Avi Gross via Python-list
Alan,

I am also wondering about that zip() function call to bind the two lists
into a sort of iterator object. Presumably that calls the iterator N times.
I did a test where I made two list called A and B and used zip to make an
object holding the two and then removed A and B. I was able to print the
list of tuples just fine with print(list(C)) so clearly it is not so much a
pure iterator as one that holds yet another copy of both lists!

Now the old-fashioned C way, might simply use old fashioned but highly
efficient pointer arithmetic to move through two lists or arrays or whatever
of the same length adding as it goes so one pass period. Or it could use
indexing as in sum += A[i] * B[i] ...

But yes, there are many good reasons to use clearer code with well-tested
parts even at the cost of some efficiency. 

Is there a version of zip() or an alternative that might be faster? In
particular, I was wondering the usual question of what happens if you might
abort early if something is noticed, like say a negative number. If you
pre-calculated and copied 100,000 items and abort after 5, ... 

I note an approach in some languages using a vectorized approach may be
faster. Forget lists and as long as A and B are equal length vectors or
arrays as in numpy, there are ways to ask to multiply two arrays in
vectorized fashion so effectively you can say something akin to:

sum(A*B)

The above may be highly efficient especially if the underlying code is in
C/C++.

If there is no objection in your code to using the numpy module and the
corresponding objects you can make a similar test with something like this:

And the function they seem to want is the dot product of two such arrays as
in numpy.dot(A, B) provides the sum of the many products of corresponding
entries in A and B.


-Original Message-
From: Python-list  On
Behalf Of Alan Gauld
Sent: Tuesday, October 12, 2021 6:56 PM
To: python-list@python.org
Subject: Fwd: Re: sum() vs. loop


On 10/10/2021 09:49, Steve Keller wrote:
> I have found the sum() function to be much slower than to loop over 
> the operands myself:
>
> def sum_products(seq1, seq2):
> return sum([a * b for a, b in zip(seq1, seq2)])
>
> def sum_products2(seq1, seq2):
> sum = 0
> for a, b in zip(seq1, seq2):
> sum += a * b
> return sum
>
> In a program I generate about 14 million pairs of sequences of ints 
> each of length 15 which need to be summed. The first version with 
> sum() needs
> 44 seconds while the second version runs in 37 seconds.
>
> Can someone explain this difference?

I'm no expert on Python innards but it looks to me like the first version
loops over the length of the list twice, once to generate the list of
products and the second time to add them together.

The pure Python version only loops once because it does the addition in
transit.

Presumably, especially for large numbers, a single python loop is faster
than 2 C loops?

But that's purely my speculation.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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

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


Aw: Re: Re: Re: How do you find what exceptions a class can throw?

2020-12-20 Thread Karsten Hilbert
> Trust me: it takes 100x getting anything done plus keep up with your prayers, 
> and it takes 100^100x learning anything solid, as in just forget about it.  
> Indeed, consider that we are rather going to the formal verification of 
> programs, software, and even hardware...

I sincerly wish you that your hope becomes reality within your lifetime.

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


Re: Re: Re: How do you find what exceptions a class can throw?

2020-12-20 Thread Julio Di Egidio
On Sunday, 20 December 2020 at 19:54:08 UTC+1, Karsten Hilbert wrote:
> > > So what you are looking for is the form of a potential 
> > > "timeout exception" (say, exception name) ? 
> > > 
> > > Provoke one and have a look. 
> > > 
> > > Then catch what you saw. 
> > 
> >  
> > 
> > Programmers don't guess...
> 
> I did not suggest guessing. 

Yes, you did.  :)

> I suggested gathering scientific evidence by 
> running a controlled experiment.

Programming is not a science: in fact, computer science is a mathematics, and 
engineering is engineering.

Rather (speaking generally), the "trial and error" together with "not reading 
the docs" is a typical beginner's mistake.

> Or should I say "Programmers don't trust..." ? 

Trust me: it takes 100x getting anything done plus keep up with your prayers, 
and it takes 100^100x learning anything solid, as in just forget about it.  
Indeed, consider that we are rather going to the formal verification of 
programs, software, and even hardware...

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


Aw: Re: Re: How do you find what exceptions a class can throw?

2020-12-20 Thread Karsten Hilbert
> > So what you are looking for is the form of a potential
> > "timeout exception" (say, exception name) ?
> >
> > Provoke one and have a look.
> >
> > Then catch what you saw.
>
> 
>
> Programmers don't guess...

I did not suggest guessing.

I suggested gathering scientific evidence by
running a controlled experiment.

Or should I say "Programmers don't trust..." ?

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


Re: Re: How do you find what exceptions a class can throw?

2020-12-20 Thread Julio Di Egidio
On Sunday, 20 December 2020 at 19:35:21 UTC+1, Karsten Hilbert wrote:

> > If it's a timeout exception I'm going to delay a little while and then 
> > try again. The timeout is probably because the server is busy.
> 
> So what you are looking for is the form of a potential 
> "timeout exception" (say, exception name) ? 
> 
> Provoke one and have a look. 
> 
> Then catch what you saw.



Programmers don't guess...

HTH,

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


Re: Re: CLI parsing—with `--help` text—`--foo bar`, how to give additional parameters to `bar`?

2020-10-15 Thread Samuel Marks
Yeah I've played with custom actions before
https://github.com/offscale/argparse-utils/tree/master/argparse_utils/actions

But this would only help in one phase, the important phase of
providing help text will need to be provided out-of-argparse and
thrown in

(like my trivial absl alternative, exposing a function which takes an
argparse instance and returns an argparse instance)

The only hack remaining is that I have to pass through `sys.argv` at
least once before giving it to argparse. I wonder if there's a way to
not need to explicitly go through it at all…
https://github.com/SamuelMarks/ml-params/blob/d1fb184/ml_params/__main__.py#L89

[I didn't know `getopt` was exposed otherwise I'd use that , but there has to be a solution just using
argparse?]

Samuel Marks
Charity  | consultancy
 | open-source  |
LinkedIn 


Samuel Marks
Charity | consultancy | open-source | LinkedIn


On Fri, Oct 16, 2020 at 3:47 PM Dieter Maurer  wrote:
>
> Samuel Marks wrote at 2020-10-16 10:09 +1100:
> >Yes it’s my module, and I’ve been using argparse
> >https://github.com/SamuelMarks/ml-params
> >
> >No library I’ve found provides a solution to CLI argument parsing for my
> >use-case.
>
> Do you know that with `argparse` you can specify how many arguments an option
> expects? Thus, it should be quite easily possible to
> have --opt   ...
> Do you know that you can define new `Action`s for `argparse`?
> This way, you could properly process `--opt ,, ...`.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: CLI parsing—with `--help` text—`--foo bar`, how to give additional parameters to `bar`?

2020-10-15 Thread Dieter Maurer
Samuel Marks wrote at 2020-10-16 10:09 +1100:
>Yes it’s my module, and I’ve been using argparse
>https://github.com/SamuelMarks/ml-params
>
>No library I’ve found provides a solution to CLI argument parsing for my
>use-case.

Do you know that with `argparse` you can specify how many arguments an option
expects? Thus, it should be quite easily possible to
have --opt   ...
Do you know that you can define new `Action`s for `argparse`?
This way, you could properly process `--opt ,, ...`.
-- 
https://mail.python.org/mailman/listinfo/python-list


Aw: Re: Re: Python 3 how to convert a list of bytes objects to a list of strings?

2020-08-29 Thread Karsten Hilbert
> Just appending a message as a raw file to a mailbox, doesn't properly
> add it as a new message. You need to add a From: line to the front, and
> then go through the message and alter any line that begins as "From:"
> (and possibly any line that begins with something like ">From:" or
> ">>From:" depending on which mailbox format is being used. There may be
> a few other small details that needs to happen to.

I see, thanks.

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


Aw: Re: Re: Another 2 to 3 mail encoding problem

2020-08-27 Thread Karsten Hilbert
> > > Because of this, the Python 3 str type is not suitable to store an email
> > > message, since it insists on the string being Unicode encoded,
> >
> > I should greatly appreciate to be enlightened as to what
> > a "string being Unicode encoded" is intended to say ?
> >
>
> A Python 3 "str" or a Python 2 "unicode" is an abstract sequence of
> Unicode codepoints.

OK, I figured that much. So it was the "encoded" that threw me off.

Being a sequence of Unicode codepoints makes it en-Uni-coded at
a technically abstract level while I assumed the "encoded" is meant
to somehow reference ''.encode() and friends.

Karsten

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


Re: Re: Another 2 to 3 mail encoding problem

2020-08-27 Thread Chris Angelico
On Thu, Aug 27, 2020 at 11:10 PM Karsten Hilbert
 wrote:
>
> > Because of this, the Python 3 str type is not suitable to store an email
> > message, since it insists on the string being Unicode encoded,
>
> I should greatly appreciate to be enlightened as to what
> a "string being Unicode encoded" is intended to say ?
>

A Python 3 "str" or a Python 2 "unicode" is an abstract sequence of
Unicode codepoints. As such, it's not suitable for transparently
round-tripping an email, as it would lose information about the way
that things were encoded. However, it is excellent for building and
processing emails - you deal with character encodings at the same
point where you deal with the RFC 822 header format. In the abstract,
your headers might be stored in a dict, but then you encode them to a
flat sequence of bytes by putting "Header: value", wrapping correctly
- and also encode the text into bytes at the same time.

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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread Ethan Furman

On 12/08/2019 06:32 AM, Python wrote:


Well... Maybe it's time to admit, Rob, that programming is not
your thing.


Rob, my apologies.  Whoever this person is, they are not "Python", and their 
behavior will not be tolerated.

"Python", if you don't want to help then remain silent.  If you don't want to 
be frustrated, stop reading the thread.
Rude behavior will not be tolerated.  Consider this your one warning.

--
~Ethan~
Python List Moderator
--
https://mail.python.org/mailman/listinfo/python-list


Re: Aw: Re: Re: Re: Re: stuck on time

2019-12-08 Thread RobH

On 08/12/2019 14:26, Karsten Hilbert wrote:

Like this?
  >>>print_time()
Traceback (most recent call last)
File "stdin>", line 1, in 
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
[Previous line  repeated 996 more times]
RecursionError: maximum recursion depth excedded.


Sort of, yes, but since you meanwhile redeclared the function:

def print_time():
print_time()

to be recursive and then you ran that recursive function
it recursed until it ran out of resources.

However,


Running the code in a shell , it is displaying the time and now also the  date .


That would prove that the code itself is not
the reason why it hangs where you think it
hangs.

I suggest sprinkling print statements about the initial code
and see what it prints to the console to find out where
(and whether) it actually hangs.

Karsten



Ok, when I do:
>>>def print_time():
   print_time()

It hangs.

the code I linked to apparently works for the author and also for some 
others, but not for me. Admittedly they are using the Minecraftia.ttf 
font which gives me the IOError which posted about above this one.
I am presently using the NotoSerif-Regular.ttf font, and I only think 
that that is why nothing else happens.


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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread Chris Angelico
On Mon, Dec 9, 2019 at 1:56 AM RobH  wrote:
> Thanks, but I am only using the code which someone else has written, and
> apparently it works ok for them and others but not for me.
>
> I only came here to find out why, and that is why I posted the link to
> the code, which I thought would be helpful to anyone who wishes to reply.
>
> I know I am not a python programmer, although have done some VB
> programming years ago.

"Not a Python programmer" is something that can easily be changed :)
Python's an easy language to pick up, and since you have some
programming experience already, even easier. If you have half an hour
- maybe a whole hour to be on the safe side - just work your way
through the tutorial and get that "ah ha" moment as you figure out
what's actually happening here. You'll unlock a ton of coolness! :)

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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread RobH

On 08/12/2019 14:39, Chris Angelico wrote:

On Mon, Dec 9, 2019 at 1:36 AM Python  wrote:


RobH wrote:

On 08/12/2019 13:06, Karsten Hilbert wrote:

In an interactive interpreter:

def print_time():
   current_time = time.strftime("%I:%M")


What happens if you then do

print_time()



print_time()
on it's own returns NameError: name 'print_time' is not defined


Notice the "then" above ?

More precisely: directly one after the other without leaving the
interpreter ...

Karsten


I'm not sure what you mean.

Like this?
  >>>print_time()
Traceback (most recent call last)
File "stdin>", line 1, in 
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
[Previous line  repeated 996 more times]
RecursionError: maximum recursion depth excedded.

Running the code in a shell , it is displaying the time and now also the
date .
Nothing else tho', as in no rectangle drawn


Well... Maybe it's time to admit, Rob, that programming is not
your thing.



That's rude and uncalled for, and since you're hiding behind
anonymity, you're painting your newsgroup server in a bad light (it's
proxad.net if anyone's curious).

Rob, I recommend working through a Python tutorial. There are some
subtleties to what you're doing that would best be discovered through
experimentation, and a good tutorial will help with that. Try this
one:

https://docs.python.org/3/tutorial/index.html

ChrisA



Thanks, but I am only using the code which someone else has written, and 
apparently it works ok for them and others but not for me.


I only came here to find out why, and that is why I posted the link to 
the code, which I thought would be helpful to anyone who wishes to reply.


I know I am not a python programmer, although have done some VB 
programming years ago.


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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread Chris Angelico
On Mon, Dec 9, 2019 at 1:36 AM Python  wrote:
>
> RobH wrote:
> > On 08/12/2019 13:06, Karsten Hilbert wrote:
> > In an interactive interpreter:
> >
> > def print_time():
> >   current_time = time.strftime("%I:%M")
> 
>  What happens if you then do
> 
>  print_time()
> 
> >>>
> >>> print_time()
> >>> on it's own returns NameError: name 'print_time' is not defined
> >>
> >> Notice the "then" above ?
> >>
> >> More precisely: directly one after the other without leaving the
> >> interpreter ...
> >>
> >> Karsten
> >>
> > I'm not sure what you mean.
> >
> > Like this?
> >  >>>print_time()
> > Traceback (most recent call last)
> > File "stdin>", line 1, in 
> > File "stdin>", line 2, in print_time
> > File "stdin>", line 2, in print_time
> > File "stdin>", line 2, in print_time
> > [Previous line  repeated 996 more times]
> > RecursionError: maximum recursion depth excedded.
> >
> > Running the code in a shell , it is displaying the time and now also the
> > date .
> > Nothing else tho', as in no rectangle drawn
>
> Well... Maybe it's time to admit, Rob, that programming is not
> your thing.
>

That's rude and uncalled for, and since you're hiding behind
anonymity, you're painting your newsgroup server in a bad light (it's
proxad.net if anyone's curious).

Rob, I recommend working through a Python tutorial. There are some
subtleties to what you're doing that would best be discovered through
experimentation, and a good tutorial will help with that. Try this
one:

https://docs.python.org/3/tutorial/index.html

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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread Python

RobH wrote:

On 08/12/2019 13:06, Karsten Hilbert wrote:

In an interactive interpreter:

def print_time():
  current_time = time.strftime("%I:%M")


What happens if you then do

print_time()



print_time()
on it's own returns NameError: name 'print_time' is not defined


Notice the "then" above ?

More precisely: directly one after the other without leaving the 
interpreter ...


Karsten


I'm not sure what you mean.

Like this?
 >>>print_time()
Traceback (most recent call last)
File "stdin>", line 1, in 
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
[Previous line  repeated 996 more times]
RecursionError: maximum recursion depth excedded.

Running the code in a shell , it is displaying the time and now also the 
date .

Nothing else tho', as in no rectangle drawn


Well... Maybe it's time to admit, Rob, that programming is not
your thing.


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


Aw: Re: Re: Re: Re: stuck on time

2019-12-08 Thread Karsten Hilbert
> Like this?
>  >>>print_time()
> Traceback (most recent call last)
> File "stdin>", line 1, in 
> File "stdin>", line 2, in print_time
> File "stdin>", line 2, in print_time
> File "stdin>", line 2, in print_time
> [Previous line  repeated 996 more times]
> RecursionError: maximum recursion depth excedded.

Sort of, yes, but since you meanwhile redeclared the function:

def print_time():
   print_time()

to be recursive and then you ran that recursive function
it recursed until it ran out of resources.

However,

> Running the code in a shell , it is displaying the time and now also the  
> date .

That would prove that the code itself is not
the reason why it hangs where you think it
hangs.

I suggest sprinkling print statements about the initial code
and see what it prints to the console to find out where
(and whether) it actually hangs.

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


Re: Aw: Re: Re: Re: stuck on time

2019-12-08 Thread RobH

On 08/12/2019 13:06, Karsten Hilbert wrote:

In an interactive interpreter:

def print_time():
  current_time = time.strftime("%I:%M")


What happens if you then do

print_time()



print_time()
on it's own returns NameError: name 'print_time' is not defined


Notice the "then" above ?

More precisely: directly one after the other without leaving the interpreter ...

Karsten


I'm not sure what you mean.

Like this?
>>>print_time()
Traceback (most recent call last)
File "stdin>", line 1, in 
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
File "stdin>", line 2, in print_time
[Previous line  repeated 996 more times]
RecursionError: maximum recursion depth excedded.

Running the code in a shell , it is displaying the time and now also the 
date .

Nothing else tho', as in no rectangle drawn
--
https://mail.python.org/mailman/listinfo/python-list


Aw: Re: Re: Re: stuck on time

2019-12-08 Thread Karsten Hilbert
> >> In an interactive interpreter:
> >>
> >> def print_time():
> >>  current_time = time.strftime("%I:%M")
> >
> > What happens if you then do
> >
> > print_time()
> >
>
> print_time()
> on it's own returns NameError: name 'print_time' is not defined

Notice the "then" above ?

More precisely: directly one after the other without leaving the interpreter ...

Karsten

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


Re: Aw: Re: Re: stuck on time

2019-12-08 Thread RobH

On 08/12/2019 10:39, Karsten Hilbert wrote:

In an interactive interpreter:

def print_time():
  current_time = time.strftime("%I:%M")

returns nothing.


That should be correct.

What happens if you then do

print_time()

inside the interpreter ?

Karsten


print_time()
on it's own returns NameError: name 'print_time' is not defined

def print_time();
print_time()

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


Aw: Re: Re: stuck on time

2019-12-08 Thread Karsten Hilbert
> In an interactive interpreter:
>
> def print_time():
> current_time = time.strftime("%I:%M")
>
> returns nothing.

That should be correct.

What happens if you then do

print_time()

inside the interpreter ?

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


Re: re not working

2019-09-16 Thread MRAB

On 2019-09-17 02:31, CrazyVideoGamez wrote:

For some reason these are different:

pattern = r'[0-9]{4,6}'

And

pattern2 = r'[0-9][0-9][0-9][0-9]([0-9]){0,2}'

And when I try to match them

import re
re.search(pattern, '1234')

and

import re
re.search(pattern2, '1234')

are different. Help?

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 
bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> pattern = r'[0-9]{4,6}'
>>> pattern2 = r'[0-9][0-9][0-9][0-9]([0-9]){0,2}'
>>> re.search(pattern, '1234')

>>> re.search(pattern2, '1234')


They look the same to me.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re: absolute path to a file

2019-08-16 Thread Chris Angelico
On Sat, Aug 17, 2019 at 2:27 AM Paul St George  wrote:
> BUT does not work with
> | print('test2:',os.path.realpath(n.image.filepath))|
>
> This returns only
> |/image01.tif|
>
>
> Notes:
> Chris, I only mention the extra leading slash on my Mac in case anyone
> wonders why it is there. Python puts it there to escape the following slash.

I still don't understand what you mean by that, because there's no
concept of "escaping" with these slashes. It looks like you're
actually working with absolute paths (starting with the leading slash)
when you want to work with relative paths (NOT starting with a leading
slash). The double slash isn't "escaping" anything, to my knowledge,
and Python would not add it.

>From the look of things, you really are getting a valid absolute path
- "/image01.tif" is already absolute. It just isn't the path you want.

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


Re: Re: absolute path to a file

2019-08-16 Thread Paul St George

Thank you Manfred and Cameron!
I think the problem may lie within syntax rather than vocabulary. The 
code works in one place but not where I use it in my script*. Cameron’s 
suggestion works when I try


| print('test1:', os.path.realpath(bpy.data.filepath))|

This returns:
|/Users/Lion/Desktop/test8/tifftest8.blend|


BUT does not work with
| print('test2:',os.path.realpath(n.image.filepath))|

This returns only
|/image01.tif|


Here is my full script:
# starts

|import bpy||
||import os||
||from pathlib import Path ||
||
||texture_list = []||
||
||with open(os.path.splitext(bpy.data.filepath)[0] + ".txt", "w") as 
outstream:||

||
||
|| for obj in bpy.context.scene.objects:||
||    for s in obj.material_slots:||
||    if s.material and s.material.use_nodes:||
||    for n in s.material.node_tree.nodes:||
||    if n.type == 'TEX_IMAGE':||
||    texture_list += [n.image]||
||print(obj.name,'uses',n.image.name,'saved at',n.image.filepath, 'which 
is at', os.path.realpath(n.image.filepath), file=outstream)||


|# ends

Notes:
Chris, I only mention the extra leading slash on my Mac in case anyone 
wonders why it is there. Python puts it there to escape the following slash.
Perhaps I should also mention (in case it is relevant) that I am calling 
my script ‘texturescript.py’ from the Python console of Blender. I use:


|filename = "/Users/Lion/Desktop/test8/texturescript.py"||
||exec(compile(open(filename).read(), filename, 'exec'))|


* My original |os.path.abspath| also works (and doesn’t work) in these 
circumstances. As does Manfred’s: |Path('./myfile').resolve()|.


On 16/08/2019 05:44, Manfred Lotz wrote:

On Fri, 16 Aug 2019 09:00:38 +1000
Cameron Simpson  wrote:


On 15Aug2019 22:52, Manfred Lotz  wrote:

I did this:

>from pathlib import Path

abs_myfile = Path('./myfile').resolve()
which worked fine for me.

There is also os.path.realpath(filename) for this purpose. In modern
Python that also accepts a Pathlike object.

Thanks for this.

I changed my code to use your suggestion which seems to
be better for the situation where I used resolve() before.


--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: String slices

2019-08-10 Thread Paul St George


On 10/08/2019 17:35, Dennis Lee Bieber wrote:

On Sat, 10 Aug 2019 11:45:43 +0200, "Peter J. Holzer"
declaimed the following:



There are of course many variants to all three methods.

And then one can get downright nasty...


X = 3.14
Y = 2.78
Z = 6.226E23
print("".join(["Plane rotation %s: %s\n" % (nm, vl)

... for (nm, vl) in [("X", X), ("Y", Y), ("Z", Z)]]))
Plane rotation X: 3.14
Plane rotation Y: 2.78
Plane rotation Z: 6.226e+23

(replace "print" with "outstream.write" for use with the file)


|outstream.write| could be very useful, thank you Peter and Cameron 
(neither being Rhodri James). If I wanted to learn more about formatting 
strings is there a better place to go than:


https://docs.python.org/release/3.6.5/library/string.html?highlight=string#format-string-syntax

https://pyformat.info

https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html

And Dennis, whatever you did there is very impressive and works 
perfectly but I don’t know enough to be able to use it. Please will you 
say more or direct me to some reference? I couldn’t find ‘nasty’ in the 
Python docs.

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


Re: Re: String slices

2019-08-09 Thread Paul St George


On 09/08/2019 16:29, Rhodri James wrote:

On 09/08/2019 15:13, Paul St George wrote:

In the code (below) I want a new line like this:

Plane rotation X: 0.0
Plane rotation Y: 0.0
Plane rotation Z: 0.0

But not like this:

Plane rotation X:
0.0
Plane rotation Y:
0.0
Plane rotation Z:
0.0

Is it possible?
(I am using Python 3.5 within Blender.)

#
import os

outstream = open(os.path.splitext(bpy.data.filepath)[0] + ".txt",'w')

print(

"Plane rotation X:",bpy.data.objects["Plane"].rotation_euler[0],

"Plane rotation Y:",bpy.data.objects["Plane"].rotation_euler[1],

"Plane rotation Z:",bpy.data.objects["Plane"].rotation_euler[2],

file=outstream, sep="\n"

)

outstream.close()


The 'sep="\n"' parameter to print() means "put a newline between each 
item."  So don't do that.  Put the newlines you do want in explicitly, 
or use separate calls to print():


(I'm abbreviating because I really can't be bothered to type that much 
:-)


  print("X:", thing[0],
    "\nY:", thing[1],
    "\nZ:", thing[2],
    file=outstream)

or

  print("X:", thing[0], file=outstream)
  print("Y:", thing[1], file=outstream)
  print("Z:", thing[2], file=outstream)

I would probably use the latter, but it's just a matter of personal 
preference.


(Actually I would probably use outstream.write() and do my own 
formatting, but let's not get side-tracked ;-)





So, I am going with your second suggestion (see below) but I would love 
to hear your outstream.write() side-track!



import os

with open(os.path.splitext(bpy.data.filepath)[0] + ".txt", "w") as outstream:

   plane = bpy.data.objects["Plane"]

   print("Plane rotation X:",plane.rotation_euler[0], file=outstream)

   print("Plane rotation Y:",plane.rotation_euler[1], file=outstream)

   print("Plane rotation Z:",plane.rotation_euler[2], file=outstream)

   print("Focal length:", bpy.context.object.data.lens, file=outstream)

   and so on...




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


Re: Re: Python in Blender. Writing information to a file.

2019-08-09 Thread Paul St George


On 09/08/2019 15:59, Rhodri James wrote:

On 09/08/2019 14:54, Paul St George wrote:


On 09/08/2019 04:09, Cameron Simpson wrote:

On 08Aug2019 22:42, Paul St George  wrote:

On 08/08/2019 10:18, Peter Otten wrote:

The print() function has a keyword-only file argument. So:
with open(..., "w") as outstream:
    print("Focal length:", bpy.context.object.data.lens, 
file=outstream)

[...]



That worked perfectly.

outstream = open(path to my file,'w')
print(
whatever I want to print
file=outstream
)
outstream.close()


I just wanted to point out Peter's use of the open context manager:

   with open(..., "w") as outstream:
 print stuff ...

You'll notice that it does not overtly close the file. The file 
object returned from open() is a context manager, the "with" 
statement arranges to close the file when your programme exits the 
with suite.


Importantly, the close will happen even if the code inside raises an 
exception, which in your "open..print..close" sequence would not 
reach the close call.


So we recommend the "with" form of open() above.

There are circumstances where it isn't useful, but they are very rare.

Cheers,
Cameron Simpson 


I almost understand.

Are you saying I should change the first line of code to something like:

|outstream = with open(path to my file,'w') # this is invalid syntax|

and then delete the

outstream.close()


No, you should do what Peter wrote:

with open("/path/to/file", "w") as outstream:
  print(my_stuff, file=outstream)


Got it! I hadn't taken Peter's advice as code. I thought (well anyway now I 
have it). So thanks to Peter, Cameron and
Rhodri.

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


Re: Re: Python in Blender. Writing information to a file.

2019-08-08 Thread Paul St George


On 08/08/2019 10:18, Peter Otten wrote:

Paul St George wrote:


I am using Python 3.5 within Blender. I want to collect values of the
current settings and then write all the results to a file.

I can see the settings and the values in the Python console by doing
this for each of the settings
|
|

|print(“Focal length:”,bpy.context.object.data.lens)|

---Focal length: 35.0


or I can do many at a time like this:

|print("Plane rotation
X:",bpy.data.objects["Plane"].rotation_euler[0],"\nPlane rotation
Y:",bpy.data.objects["Plane"].rotation_euler[1],"\nPlane rotation
Z:",bpy.data.objects["Plane"].rotation_euler[2])|

---Plane rotation X: 0.0
---Plane rotation Y: 0.0
---Plane rotation Z: 0.0


My question:
How do I write all the results to a file? I have tried file.write but
can only write one argument at a time. Is there a better way to open a
file, write the collected information to it and then close the file?


The print() function has a keyword-only file argument. So:

with open(..., "w") as outstream:
 print("Focal length:", bpy.context.object.data.lens, file=outstream)


|print("Plane rotation
X:",bpy.data.objects["Plane"].rotation_euler[0],"\nPlane rotation
Y:",bpy.data.objects["Plane"].rotation_euler[1],"\nPlane rotation
Z:",bpy.data.objects["Plane"].rotation_euler[2])|

This looks messy to me. I' probably use intermediate variables

x, y, z = bpy.data.objects["Plane"].rotation_euler
print(
 "Plane rotation X:", x,
 "Plane rotation Y:", y,
 "Plane rotation Z:", z,
 file=outstream, sep="\n"
)

or even a loop.



That worked perfectly.

outstream = open(path to my file,'w')
print(
whatever I want to print
file=outstream
)
outstream.close()



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


Re: Re: Issue in using "subprocess.Popen" for parsing the command output

2018-11-25 Thread Chris Angelico
On Mon, Nov 26, 2018 at 5:40 AM srinivasan  wrote:
>
> Dear Karsten,
>
> With the help of Mrab Inputs, I tried Even with  "return
> stdout.strip().decode("utf-8")", it still seems to be an issue, I am using
> python 3.6, is this causing a issue?

No, it isn't. Two things are causing most of your issues.

1) You are trying to *get your homework done*, rather than actually
gain competence. Slow down. Read some documentation. Don't fire off
another request to the mailing list the moment you've tried one thing;
instead, do some research.

2) You don't currently understand what decode() actually means. I
don't fault you for that; a lot of people don't understand it, and it
was thrown at you in a suggestion without any explanation. But
encode() and decode() are not magical incantations to be inserted
randomly until your code works. Read these:

https://nedbatchelder.com/text/unipain.html
https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

I'll leave you with those.

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


Re: Re: Issue in using "subprocess.Popen" for parsing the command output

2018-11-25 Thread srinivasan
Dear Karsten,

With the help of Mrab Inputs, I tried Even with  "return
stdout.strip().decode("utf-8")", it still seems to be an issue, I am using
python 3.6, is this causing a issue?

/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/venv/bin/python
/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py
printing stdout!!
printing retcode!! 0
Traceback (most recent call last):
  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
line 37, in 
main("Apartment 18", "40672958689850014685")
  File
"/home/srinivasan/Downloads/wifidisconnectissuenov23_homework/qa/test_library/test4.py",
line 34, in main
return stdout.strip().decode("utf-8")
AttributeError: 'str' object has no attribute 'decode'

Process finished with exit code 1

Many Thanks in advance

On Sun, Nov 25, 2018 at 11:57 PM Karsten Hilbert 
wrote:

> > Even only with "*proc.decode("utf-8")"* in the above code still it seems
> to
> > throw the error
>
> No it does not. It throws the same TYPE of error due to the same
> SORT of mistake you made.
>
> You need to read carefully and try to think about what you read.
>
> Karsten
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: Generators, generator expressions, and loops

2018-11-16 Thread Peter via Python-list

Lovely, succinct answers.


On 17/11/2018 2:44 AM, Ian Kelly wrote:

On Fri, Nov 16, 2018 at 7:57 AM Steve Keller  wrote:

I have looked at generators, generator expressions, and iterators and
I try to get more familiar with these.

1. How would I loop over all (with no upper bound) integers or all
powers of two, for example?

In C it would be

for (int i = 0; ; i++) { ... }  or  for (int i = 1; ; i *= 2) { ... }

In Python, I could define a generator

 def powers():
 i = 1
 while True:
 yield(i)
 i *= 2

 for i in powers():
 ...

More elegant are generator expressions but I cannot think of a way
without giving an upper limit:

 for i in (2 ** i for i in range(100)):
 ...

which looks ugly.  Also, the double for-loop (and also the two loops
in the above exmaple, for + while in the generator) look unnatural,
somehow, i.e. loop over all elements which are created by a loop.

Is there a more beautyful way?

Some options:

from itertools import count

def powers():
 for i in count():
 yield 2 ** i


for i in (2 ** i for i in count()):
 ...


for i in map(lambda x: 2 ** x, count()):
 ...


from functools import partial
from operator import pow

for i in map(partial(pow, 2), count()):
 ...


Take your pick.




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


Re: Re: PEP 394

2018-10-20 Thread Chris Angelico
On Sun, Oct 21, 2018 at 12:41 PM Peter via Python-list
 wrote:
>
> I'd imagine the PEP would stay as active, but changed so that:
>
> python2 -> always refers to python v2
> python3 -> always refers to python v3
> python -> which currently refers to python v2 will change to point to
> python v3

That would have a lot of very annoying considerations for shebangs. As
such, it's highly unlikely that this will become the recommendation
until LONG after 2020.

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


Re: Re: PEP 394

2018-10-20 Thread Peter via Python-list

I'd imagine the PEP would stay as active, but changed so that:

python2 -> always refers to python v2
python3 -> always refers to python v3
python -> which currently refers to python v2 will change to point to 
python v3


I don't know when the core team would be considering this. The PEP was 
last updated in April this year, so it's clearly still active. I would 
imagine this change would happen when python v2 ends updates at end of 
2019, although I personally would like to see it happen earlier.


Peter L



On 20/10/2018 6:47 PM, Anders Wegge Keller wrote:

På Sat, 20 Oct 2018 12:57:45 +1100
Ben Finney  skrev:

Anders Wegge Keller  writes:


Short and simple: Do you expect PEP 394 to change status

The status of PEP 394 today is “Active”. What change of status would you
expect in this Informational PEP?

  One possible change would be that it would become archived, ceased to be,
bereft of life, resting in peace or maybe even retired.

  I don't have any particular status change I want to see; I merely ask
what other experienced python developers expect to happen.




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


Re: Re: Python indentation (3 spaces)

2018-10-07 Thread Peter via Python-list
It's also useful to be aware of the standard tabnanny module for 
"Detection of ambiguous indentation".


Very useful for highlighting problems with tabs and spaces.

Peter


On 8/10/2018 2:32 AM, Terry Reedy wrote:

On 10/5/2018 11:30 PM, Ryan Johnson wrote:

The point that OP is trying to make is that a fixed standard that is
distinguishable from the even-spacing Tab-length convention in code and
text editors will establish a level of trust between the end 
developer and
upstream developers or co-developers who may not have the same 
development

environment.


And my counter point is that a) we will not change the standard and b) 
we deliver an editor that by default enforces the standard, and c) to 
be fair, many other editors will do the same.



For example, the first Python library I ever tried to use was


What library?  From where?

poorly maintained and had spaces on one line with tabs on the next, 
and the
author mixed naming conventions and syntax from Python 2 and 3 in his 
code.

That type of experience doesn’t exactly instill trust in the coding
language’s standards, when a noob tries to use a library they found and
ends up having to debug weird errors with weirder error messages on the
first project they do.


I don't follow the logic.  If someone violates a law, does that make 
the law bad?  And if people follow a law, does that make it good?


People obviously should not distribute buggy messes, at least not 
without warning.  Were you using the library with an unsupported 
version?  Or inform the author or distributor?


Flexibility is great until the learning curve comes into play. That 
said,
there is an easy fix for tab misuse: in Visual Studio Code, you can 
replace

all Tabs with Spaces by highlighting the entire code block, hitting Tab
once and Shift-Tab after.


IDLE does that also.




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


Re: Re : So apparently I've been banned from this list

2018-10-02 Thread Ethan Furman

On 10/02/2018 03:40 PM, armand.fouca...@telecom-bretagne.eu wrote:


Hello there, I'm quite new here.


Welcome!


I'm sorry to interfere, but this thread is only creating noise on this list.


You are correct.  This thread is now closed.


Is there a place where such topics can be debated, other than the common ML?
On StackOverflow, we would take this to Meta; do we have our Meta?


Sadly, there is not, and we do not.

--
~Ethan~
Python List Moderator
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re[2]: [OT] master/slave debate in Python

2018-09-26 Thread Ian Kelly
On Wed, Sep 26, 2018 at 3:10 PM Brian Grawburg  wrote:
>
> This is right next to the objection of the use male and female to describe 
> the two parts of a connector. I lament that snowflakes and such are trying 
> desperately to enforce their quest for radical egalitarianism and see hidden 
> agendas behind just about everything---except their own, of course.

The only person who has said *anything* about "hidden agendas" here is
you. Projecting much?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: CURSES WINDOWS

2018-09-05 Thread Peter via Python-list

I get this:


C:\Users\Me> py
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 
bit (Inte

l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Program Files (x86)\Python36-32\lib\curses\__init__.py", 
line 13, in


    from _curses import *
ModuleNotFoundError: No module named '_curses'
>>>


I get the same on py 2.7



On 5/09/2018 4:59 PM, Anssi Saari wrote:

shinobi@f153.n1.z21.fsxnet (shinobi) writes:


Hello All,

can anyone please let me know what's the path to port linux python curses
program to Windows?

Is there really anything that needs to be done? At least a simple hello
world python curses program runs on Windows and Linux with no changes.





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


Re: Re: name 'aLOCK' is not defined When I add aLOCK = threading.RLock() behind if __name__ == "__main__"

2018-08-10 Thread Karsten Hilbert
On Fri, Aug 10, 2018 at 12:24:25AM +0800, xuanwu348 wrote:

> Yes, move the code from positionA(can run normally) to positionB(exception 
> with name undefined)
> I find this content 
> "https://docs.python.org/3.3/tutorial/classes.html#python-scopes-and-namespaces;
> But I still don't undewrstand the differenct of  scopes-and-namespaces 
> between positionA and positionB,
>
> I think the variable "aLock" at these positionA or  positionB are all global.

When something goes wrong in an unexpected way: test
your assumptions ;-)

Best,
Karsten
-- 
GPG  40BE 5B0E C98E 1713 AFA6  5BC0 3BEA AC80 7D4F C89B
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-12 Thread Paul St George




Dennis Lee Bieber wrote:
Both may be dependent upon the actual hardware graphics board and 
the

drivers for said board.

On 11/06/2018 01:47, Gregory Ewing wrote:
My guess is that if your surface is not fullscreen or is not
a hardware surface, then you're always drawing into an ofscreen
buffer that gets copied to the screen when display.flip() is
called. In other words, it's effectively double-buffered
whether you request it or not.

The only time it's an issue is when you're drawing directly
to the screen memory, i.e. both FULLSCREEN and HWSURFACE
where your hardware and drivers support that.

My suggestion is to just always specify DOUBLEBUF and not
worry about what's going on behind the scenes. That will
almost always give the result you want, i.e. a flicker-free
display.

The only time it would be an issue is if you wanted your
surface to *not* be double-buffered for some reason, but
that would be a rare situation.

Thank you! Your intervention could not have been more timely. I was just 
about to throw away the screen and try again with another. I want to use 
display.flip() and thought that was dependent on being able to set 
DOUBLEBUF. The surface is fullscreen.


I had considered meddling with the config.txt to try to enable* 
HWSURFACE but from what you say, this is unnecessary. Have I understood 
you right?


Paul

* Perhaps by uncommenting #dtparam=spi=on
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-10 Thread Paul St George

Paul St George wrote:


So...

  print pygame.display.get_surface()
gives


and
  print screen.get_flags()
gives
-2147483648
To recap: this thread started with a question. How do I know whether
DOUBLEBUF has been set with:

screen = pygame.display.set_mode((720,480), pygame.DOUBLEBUF |
pygame.FULLSCREEN)

On 10/06/2018 16:38, Peter Otten wrote:

flags = screen.get_flags()
if flags & pygame.DOUBLEBUF:
 print("DOUBLEBUF has been set")
if flags & pygame.FULLSCREEN:
 print("FULLSCREEN has been set")

See the pattern?
I do. I do. And also, I now know for certain that DOUBLEBUF is not being 
set.

The insights about flags will take more time to digest. Thank you for both!
--
https://mail.python.org/mailman/listinfo/python-list


Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-10 Thread Peter Otten
Paul St George wrote:

> So...
> 
>  print pygame.display.get_surface()
> gives
> 
> 
> and
>  print screen.get_flags()
> gives
> -2147483648

> To recap: this thread started with a question. How do I know whether
> DOUBLEBUF has been set with:
> 
> screen = pygame.display.set_mode((720,480), pygame.DOUBLEBUF |
> pygame.FULLSCREEN)

flags = screen.get_flags()
if flags & pygame.DOUBLEBUF:
print("DOUBLEBUF has been set")
if flags & pygame.FULLSCREEN:
print("FULLSCREEN has been set")

See the pattern?

The easiest way to argue about flags is in binary notation. Every flag 
corresponds to an integer with a single bit set, e. g.

HOT = 0b001
BLUE = 0b010
RIGHTEOUS = 0b100

You can combine the flags with bitwise or

hot_and_righteous = HOT | RIGHTEOUS # 0b101

and query them  with bitwise and:

>>> if hot_and_righteous & HOT: print("hot")
... 
hot
>>> if hot_and_righteous & BLUE: print("blue")
... 
>>> if hot_and_righteous & RIGHTEOUS: print("righteous")
... 
righteous

With your actual pygame flags it's very much the same. However, because 
integers in Python are signed numbers like

-2147483648

may be puzzling, even when you display them in binary

>>> bin(-2147483648)
'-0b1000'

You might think that only one flag is set because there is only one 1, but 
the - sign corresponds to an "infinite" number of leading 1s.

If you know that the flags are stored (for example) in a 32bit integer you 
can mask off these leading 1s and see the actual data more clearly:

>>> bin(-2147483648 & 0b)
'0b1000'

OK, so in this case it probably* was a single flag, but that's not always 
the case:

>>> bin(-7)
'-0b111'
>>> bin(-7 & 0b)
'0b1001'

(*) What if the flags were stored in a 64bit integer?

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


Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-10 Thread Paul St George
To recap: this thread started with a question. How do I know whether 
DOUBLEBUF has been set with:


    screen = pygame.display.set_mode((720,480), pygame.DOUBLEBUF | 
pygame.FULLSCREEN)



On 09/06/2018 22:04, Mark Lawrence wrote:

On 09/06/18 20:31, Paul St George wrote:


 print pygame.display.get_surface()
gives


and
 print screen.get_flags()
gives
-2147483648

The lists of flags at 
 
and 



has nothing remotely like -2147483648. I would expect something more 
like 0x4000


Am I using the wrong code to determine whether I have successfully 
set DOUBLEBUF with


 screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN | 
pygame.DOUBLEBUF)


AND

What does -2147483648 tell me? Does this number need converting?




From the interactive interpreter:-

>>> hex(-2147483648)
'-0x8000'
>>> hex(pygame.FULLSCREEN)
'-0x8000'
>>> hex(pygame.DOUBLEBUF)
'0x4000'


Thanks go to Mark Lawrence and Richard Damon.

Using
print hex(screen.get_flags())

I can see that the order of the two flags does not make a difference.

screen = pygame.display.set_mode((720,480), pygame.DOUBLEBUF | 
pygame.FULLSCREEN)
screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN | 
pygame.DOUBLEBUF)

both report the same

print hex(screen.get_flags())

'-0x8000'


BUT
omitting DOUBLEBUF from the code

screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN)

also makes no difference to the report

print hex(screen.get_flags())

'-0x8000'


AND

with with only DOUBLEBUF in the code

screen = pygame.display.set_mode((720,480), pygame.DOUBLEBUF)

does not give the expected and desired '-0x4000'

instead, the report is

print hex(screen.get_flags())

‘0x0’



0x0 (SWSURFACE) is consistent with

print pygame.display.get_surface()
‘’


It seems that DOUBLEBUF is *not* being set. I am guessing this is because the 
arguments passed by pygame.display.set_mode() are only requests.  The actual 
display will depend on the system, and what is available/possible.

More guessing leads me to wonder whether DOUBLEBUF is only available when 
HWSURFACE is being used so I tried three flags with:

flags = pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE
screen = pygame.display.set_mode((0, 0), flags)

But no change (screen is still SW and DOUBLEBUF is not set):


print pygame.display.get_surface()


print hex(screen.get_flags())
-0x8000


QUESTIONS
Can anyone find an error in any of this? I hope so.

Is DOUBLEBUF dependent on HWSURFACE?

If so, how does one force the change to a Hardware surface? ‘set_mode’ is not 
doing it.


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


Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-09 Thread Paul St George



On 08/06/18 09:00, Paul St George wrote:
Excellent. Now I know what to do in this instance and I understand 
the principle.


I hesitantly tried this:

 screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN | 
pygame.DOUBLEBUF)


Hesitantly because I expected the *bitwise or operator* (|) to work 
like a toggle, so FULLSCREEN or DOUBLEBUF.



On 08/06/2018 12:52, Rhodri James wrote:

The bitwise OR operator peforms a bitwise OR, i.e. *both* flags get set.

No errors were reported, but how would I check that DOUBLEBUF had 
been set? Is there a general rule, such as replace 'set_something' 
with 'get_something'?


There's documentation.  The link Chris gave you for 
pygame.display.set_mode() tells you that you get a Surface out of it. 
Reaching for the docs for that, this leaps out:


https://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_flags



So...

    print pygame.display.get_surface()
gives


and
    print screen.get_flags()
gives
-2147483648

The lists of flags at 
 
and 


has nothing remotely like -2147483648. I would expect something more 
like 0x4000


Am I using the wrong code to determine whether I have successfully set 
DOUBLEBUF with


    screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN | 
pygame.DOUBLEBUF)


AND

What does -2147483648 tell me? Does this number need converting?






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


Re: Re: FULLSCREEN and DOUBLEBUF

2018-06-08 Thread Paul St George
Excellent. Now I know what to do in this instance and I understand the 
principle.


I hesitantly tried this:

    screen = pygame.display.set_mode((720,480), pygame.FULLSCREEN | 
pygame.DOUBLEBUF)


Hesitantly because I expected the *bitwise or operator* (|) to work like 
a toggle, so FULLSCREEN or DOUBLEBUF.


No errors were reported, but how would I check that DOUBLEBUF had been 
set? Is there a general rule, such as replace 'set_something' with 
'get_something'?


Paul St George


On 07/06/2018 19:56, Chris Angelico wrote:

On Fri, Jun 8, 2018 at 3:12 AM, Paul St George  wrote:

This is both a narrow question about some code and a more general question
about syntax in Python

Using the Pygame modules, I want to set both FULLSCREEN and DOUBLEBUF

I can use
screen =
pygame.display.set_mode((screen_width,screen_height),pygame.FULLSCREEN)
to set a FULLSCREEN display

Or, I can use
screen =
pygame.display.set_mode((screen_width,screen_height),pygame.DOUBLEBUF)
to set DOUBLEBUF

But how do I set both FULLSCREEN and DOUBLEBUF?

And, how can I test or check that DOUBLEBUF is set?

This is definitely a pygame question. So let's grab the docos for that
set_mode function.

https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode

You're passing two parameters in each of your examples. The first is a
tuple of (w,h) for the dimensions; the second is a constant for the
mode you want. The name of the second argument is "flags", according
to the documentation. That usually means that you can provide
multiple. The exact mechanism for combining flags is given in the last
paragraph of the docs. I'll let you take the credit for figuring out
the details yourself :)

ChrisA



--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-31 Thread Paul St George
That's what I wanted! But, I didn't know the question because I didn't 
know the answer.



On 30/05/2018 23:09, Karsten Hilbert wrote:

On Wed, May 30, 2018 at 11:01:17PM +0200, Peter J. Holzer wrote:


On 2018-05-30 22:08:45 +0200, Paul St George wrote:

Ha! No, my question was clumsy.

If I know the name of the viewer that I want to use (say for example:
‘ImageMagick’), where do I find the argument that should be used in a line
of code such as this:

ImageShow.register(MyViewer("gwenview"), -1)

$> man -k ImageMagick
$> man whatever_you_found_with_the_above

Karsten


--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-30 Thread Karsten Hilbert
On Wed, May 30, 2018 at 11:01:17PM +0200, Peter J. Holzer wrote:

> On 2018-05-30 22:08:45 +0200, Paul St George wrote:
> > Ha! No, my question was clumsy.
> > 
> > If I know the name of the viewer that I want to use (say for example:
> > ‘ImageMagick’), where do I find the argument that should be used in a line
> > of code such as this:
> > 
> > ImageShow.register(MyViewer("gwenview"), -1)

$> man -k ImageMagick
$> man whatever_you_found_with_the_above

Karsten
-- 
GPG key ID E4071346 @ eu.pool.sks-keyservers.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-30 Thread Peter J. Holzer
On 2018-05-30 22:08:45 +0200, Paul St George wrote:
> Ha! No, my question was clumsy.
> 
> If I know the name of the viewer that I want to use (say for example:
> ‘ImageMagick’), where do I find the argument that should be used in a line
> of code such as this:
> 
> ImageShow.register(MyViewer("gwenview"), -1)
> 
> I want to replace ‘gwenview’ with the name of my favourite viewer (for
> example: ‘ImageMagick’).

If your favourite viewer is 'ImageMagick’, then the name is
'ImageMagick'. However, I doubt this is the case, since ImageMagick
isn't a viewer, it is a collection of programs for manipulating images.
The viewer included in the ImageMagick package is simply called
'display' (and it is already the default viewer in PIL, so you don't
have to do anything to use it).

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-30 Thread Paul St George

Ha! No, my question was clumsy.

If I know the name of the viewer that I want to use (say for example: 
‘ImageMagick’), where do I find the argument that should be used in a 
line of code such as this:


ImageShow.register(MyViewer("gwenview"), -1)

I want to replace ‘gwenview’ with the name of my favourite viewer (for 
example: ‘ImageMagick’).




On 30/05/2018 02:31, Steven D'Aprano wrote:

On Tue, 29 May 2018 20:02:22 +0200, Paul St George wrote:


Is there, somewhere, a list of viewers and their names (for the purposes
of this script)?

Do you mean a list of programs capable of viewing graphics? Do you think
there is some sort of central authority that registers the names of all
such programs? *wink*


You can start here:

https://en.wikipedia.org/wiki/Category:Graphics_software

but that's probably the closest you're going to get.





--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-30 Thread Paul St George
True, but I wanted to have some control over the image window, 
fullscreen, colour depth, etc. I am also exploring pygame. I will try 
your suggestion as it is so much simpler.


Being a novice, I had been frightened off using shell=True. See 
.


Is this equivalent?
p = subprocess.Popen('display',  + imagepath)

so

p = subprocess.Popen('display',  'test.png')





On 30/05/2018 03:04, Ian Kelly wrote:

On Sat, May 26, 2018 at 9:17 AM, Paul St George  wrote:

Thank you.
You are very right. The show() method is intended for debugging purposes and
is useful for that, but what method should I be using and is PIL the best
imaging library for my purposes? I do not want to manipulate images, I only
want to show images (full screen) on an external display. I want to use
Python to control the timing of the images.

You probably shouldn't be using PIL at all then. Why open the file in
Python just to export it and re-open it in an image viewer? It would
be simpler just to point whichever image viewer you prefer at the
original file directly. Your entire script could just be something
like this:

import subprocess

# Some timing logic

subprocess.call("display " + imagepath, shell=True)



--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Ian Kelly
On Sat, May 26, 2018 at 9:17 AM, Paul St George  wrote:
> Thank you.
> You are very right. The show() method is intended for debugging purposes and
> is useful for that, but what method should I be using and is PIL the best
> imaging library for my purposes? I do not want to manipulate images, I only
> want to show images (full screen) on an external display. I want to use
> Python to control the timing of the images.

You probably shouldn't be using PIL at all then. Why open the file in
Python just to export it and re-open it in an image viewer? It would
be simpler just to point whichever image viewer you prefer at the
original file directly. Your entire script could just be something
like this:

import subprocess

# Some timing logic

subprocess.call("display " + imagepath, shell=True)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Re: Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Paul St George
Is there, somewhere, a list of viewers and their names (for the purposes 
of this script)?


I am assuming that if I want to ImageMagick (for example), there would 
be some shorter name - such as 'magick' - and it would be lower case .



On 29/05/2018 08:58, Peter Otten wrote:

Paul St George wrote:


This is very helpful indeed, thank you. Awe-inspiring.

It occurred to me that I could edit the PIL/ImageShow.py, replacing ‘xv’
(in five places) with the utility of my choice and using ‘executable’ as
the command.

Or, is this just not done?

No, this tends to become a maintenance problem. Instead write a little
module of your own


from PIL import ImageShow

class MyViewer(ImageShow.UnixViewer):
 def __init__(self, command):
 self.command = command
 def get_command_ex(self, file, **options):
 return (self.command,) * 2

ImageShow.register(MyViewer("gwenview"), -1)


(replace "gwenview" with your favourite viewer) and import it before using
Image.show().




--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Paul St George

I tried this anyway. The error was:

    non-keyword arg after keyword arg



On 27/05/2018 21:51, Dennis Lee Bieber wrote:

On Sun, 27 May 2018 19:59:41 +0200, Paul St George 
declaimed the following:


So, on Unix I would use

Image.show(title=None, nameofdisplayutilty), or Image.show(title=None,
scriptname) #where script with name scriptname invokes the program

I will try this now! And thank you.


That is based upon my interpretation of the documentation... If the
other participant is right, however, then the "command" parameter may not
even be getting used at the lower levels, and only the list of registered
viewers is examined. In that case one would have to register a function to
invoke the viewer.




--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Paul St George

Thank you. For the advice, and for the new word 'monkeypatch'.


On 27/05/2018 23:58, Cameron Simpson wrote:

On 27May2018 20:15, Paul St George  wrote:

This is very helpful indeed, thank you. Awe-inspiring.

It occurred to me that I could edit the PIL/ImageShow.py, replacing 
‘xv’ (in five places) with the utility of my choice and using 
‘executable’ as the command.


Or, is this just not done?


It becomes a maintenance problem.

Alternatively you could:

Just write your own show function which accepts an Image and displays 
it with your program of choice. You might need to write some 
equivalent code which saves the Image to a file first, and removes it 
afterwards.


You could copy the show() code into a function of your own (i.e. in 
your own codebase) modify that to suit, then monkeypatch the class:


 Image.show = your_personal_show_function

when your programme starts. That way the code changes are not in the 
PIL code.


Cheers,
Cameron Simpson 



--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Paul St George

Should the PIL code be corrected?


On 28/05/2018 06:34, Christian Gollwitzer wrote:

Am 27.05.18 um 23:58 schrieb Cameron Simpson:

On 27May2018 20:15, Paul St George  wrote:

This is very helpful indeed, thank you. Awe-inspiring.

It occurred to me that I could edit the PIL/ImageShow.py, replacing 
‘xv’ (in five places) with the utility of my choice and using 
‘executable’ as the command.


Or, is this just not done?


It becomes a maintenance problem.

Alternatively you could:

Just write your own show function which accepts an Image and displays 
it with your program of choice. You might need to write some 
equivalent code which saves the Image to a file first, and removes it 
afterwards.


You could copy the show() code into a function of your own (i.e. in 
your own codebase) modify that to suit, then monkeypatch the class:


  Image.show = your_personal_show_function

when your programme starts. That way the code changes are not in the 
PIL code.


I think this is a bug/misfeature in the PIL code. On all 3 major 
platforms there is a way to invoke the standard program for a given 
file or URL. On Windows, it is "cmd.exe /c start ...", on OSX it is 
"open " and on Linux it is "xdg-open ...". That way the file is 
opened by whatever the user has set in his desktop environment.


Technically, xdg-open needs not to be present on Linux, though it is 
usually installed.


Christian



--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-29 Thread Peter Otten
Paul St George wrote:

> This is very helpful indeed, thank you. Awe-inspiring.
> 
> It occurred to me that I could edit the PIL/ImageShow.py, replacing ‘xv’
> (in five places) with the utility of my choice and using ‘executable’ as
> the command.
> 
> Or, is this just not done?

No, this tends to become a maintenance problem. Instead write a little 
module of your own


from PIL import ImageShow

class MyViewer(ImageShow.UnixViewer):
def __init__(self, command):
self.command = command
def get_command_ex(self, file, **options):
return (self.command,) * 2

ImageShow.register(MyViewer("gwenview"), -1)


(replace "gwenview" with your favourite viewer) and import it before using 
Image.show().

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


Re: Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-27 Thread Paul St George

This is very helpful indeed, thank you. Awe-inspiring.

It occurred to me that I could edit the PIL/ImageShow.py, replacing ‘xv’ 
(in five places) with the utility of my choice and using ‘executable’ as 
the command.


Or, is this just not done?

On 26/05/2018 19:11, Peter Otten wrote:

Paul St George wrote:


Thank you.
You are very right. The show() method is intended for debugging purposes
and is useful for that, but what method should I be using and is PIL the
best imaging library for my purposes? I do not want to manipulate
images, I only want to show images (full screen) on an external display.
I want to use Python to control the timing of the images.

And, out of curiosity, as I will probably use a different method - how
do I find out what commands can be used as parameters for show()? I read
the docs at
,
but I am none the wiser.

If you look into the source code

https://github.com/python-pillow/Pillow/blob/master/src/PIL/Image.py#L1967

after a few indirections

show --> _show --> _showxv --> ImageShow.show

you will end up in the file

https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageShow.py

which is short enough to read completely ;)

At first glance it looks like the command argument is silently discarded, so
here's plan B:

It turns out that you can register() Viewer instances, and the pre-
registered viewers for unixoids -- and thus probably the Pi are
DisplayViewer and XVViewer.

Using these as a template I came up with the following simple viewer that
shows an image with firefox:

#!/usr/bin/env python3
import os
import sys

from PIL import Image, ImageShow


class Firefox(ImageShow.UnixViewer):

 # store the image in a format understood by the browser
 format = "jpeg"

 def get_command_ex(self, file, **options):
 return ("firefox",) * 2

 def show_file(self, file, **options):
 quote = ImageShow.quote

 command, executable = self.get_command_ex(file, **options)

 # firefox returns immediately, so let's sleep a few seconds
 # to give it time to actually open the image file
 command = "(%s %s; sleep 10; rm -f %s)&" % (
 command, quote("file://" + file), quote(file)
 )
 os.system(command)
 return 1


# the -1 means our viewer will be inserted before the others
# and thus become the default
ImageShow.register(Firefox(), -1)


if __name__ == "__main__":
 try:
 file = sys.argv[1]
 except IndexError:
 print("Please provide an image file", file=sys.stderr)
 else:
 image = Image.open(file)
 image.show()


Here's another, even simpler one:

class Gwenview(ImageShow.UnixViewer):
 def get_command_ex(self, file, **options):
 return ("gwenview",) * 2





--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-27 Thread Paul St George

So, on Unix I would use

Image.show(title=None, nameofdisplayutilty), or Image.show(title=None, 
scriptname) #where script with name scriptname invokes the program


I will try this now! And thank you.


On 26/05/2018 19:30, Dennis Lee Bieber wrote:

On Sat, 26 May 2018 17:17:42 +0200, Paul St George 
declaimed the following:


And, out of curiosity, as I will probably use a different method - how
do I find out what commands can be used as parameters for show()? I read
the docs at
,
but I am none the wiser.


AS the examples ("On OS-of-choice...") illustrate... command is any
external executable program that can handle the temporary file, I presume
using the name of the temporary and not via redirection of stdin... If you
have a hex-editor, you could even supply that as "command". If you need to
provide more than the program name, you may have to instead create a
shell-script, set it executable, and pass the script name -- have the
script then invoke the program with the options and forwarding the
temporary file name to it.




--
Paul St George
http://www.paulstgeorge.com
http://www.devices-of-wonder.com

+44(0)7595 37 1302

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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-26 Thread Peter Otten
Paul St George wrote:

> Thank you.
> You are very right. The show() method is intended for debugging purposes
> and is useful for that, but what method should I be using and is PIL the
> best imaging library for my purposes? I do not want to manipulate
> images, I only want to show images (full screen) on an external display.
> I want to use Python to control the timing of the images.
> 
> And, out of curiosity, as I will probably use a different method - how
> do I find out what commands can be used as parameters for show()? I read
> the docs at
>  #PIL.Image.Image.show>,
> but I am none the wiser.

If you look into the source code

https://github.com/python-pillow/Pillow/blob/master/src/PIL/Image.py#L1967

after a few indirections

show --> _show --> _showxv --> ImageShow.show

you will end up in the file

https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageShow.py

which is short enough to read completely ;)

At first glance it looks like the command argument is silently discarded, so 
here's plan B:

It turns out that you can register() Viewer instances, and the pre-
registered viewers for unixoids -- and thus probably the Pi are 
DisplayViewer and XVViewer.

Using these as a template I came up with the following simple viewer that 
shows an image with firefox:

#!/usr/bin/env python3
import os
import sys

from PIL import Image, ImageShow


class Firefox(ImageShow.UnixViewer):

# store the image in a format understood by the browser
format = "jpeg"

def get_command_ex(self, file, **options):
return ("firefox",) * 2

def show_file(self, file, **options):
quote = ImageShow.quote

command, executable = self.get_command_ex(file, **options)

# firefox returns immediately, so let's sleep a few seconds
# to give it time to actually open the image file
command = "(%s %s; sleep 10; rm -f %s)&" % (
command, quote("file://" + file), quote(file)
)
os.system(command)
return 1


# the -1 means our viewer will be inserted before the others
# and thus become the default
ImageShow.register(Firefox(), -1)


if __name__ == "__main__":
try:
file = sys.argv[1]
except IndexError:
print("Please provide an image file", file=sys.stderr)
else:
image = Image.open(file)
image.show()


Here's another, even simpler one:

class Gwenview(ImageShow.UnixViewer):
def get_command_ex(self, file, **options):
return ("gwenview",) * 2


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


Re: Re: The PIL show() method looks for the default viewer. How do I change this to a different viewer (of my choice)?

2018-05-26 Thread Paul St George

Thank you.
You are very right. The show() method is intended for debugging purposes 
and is useful for that, but what method should I be using and is PIL the 
best imaging library for my purposes? I do not want to manipulate 
images, I only want to show images (full screen) on an external display. 
I want to use Python to control the timing of the images.


And, out of curiosity, as I will probably use a different method - how 
do I find out what commands can be used as parameters for show()? I read 
the docs at 
, 
but I am none the wiser.



On 26/05/2018 01:02, boB Stepp wrote:

On Fri, May 25, 2018 at 6:04 AM, Paul St George  wrote:

I am using the Python Imaging Library (PIL), Python 2 and Raspberry Pi 3 B+

My code is simply:

 from PIL import Image

 im = Image.open(‘somepic.jpg’)
 im.show() # display image


But the show() method looks for the default viewer (probably xv). How do I
change this (in the code, or in some settings) to a different viewer (of my
choice)?

In the PIL docs for show() at
https://pillow.readthedocs.io/en/5.1.x/reference/Image.html#PIL.Image.Image.show
it says:


Image.show(title=None, command=None)

Displays this image. This method is mainly intended for debugging purposes.

On Unix platforms, this method saves the image to a temporary PPM
file, and calls either the xv utility or the display utility,
depending on which one can be found.

On macOS, this method saves the image to a temporary BMP file, and
opens it with the native Preview application.

On Windows, it saves the image to a temporary BMP file, and uses the
standard BMP display utility to show it (usually Paint).

Parameters:

title – Optional title to use for the image window, where possible.
command – command used to show the image


I have not had occasion to use PIL, but perhaps this command parameter
can be used to do what you want?  If not then perhaps you can write
your own function to load your image into your favorite image viewer.




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


  1   2   3   4   5   6   7   8   9   10   >