Re: Proposal: Syntax for attribute initialisation in __init__ methods

2022-04-16 Thread dn
On 17/04/2022 09.20, Sam Ezeh wrote:
>> Perhaps I'm missing the point, but what functionality or advantage(s)
>> does this give, over data-classes?
> 
> One advantage is maintaining control over the __init__ function without
> having to write extra code to do so. In the linked discussion from
> python-ideas, it was mentioned that keyword-only and positional-only
> arguments can't be used with dataclasses [1].
> 
>> Maybe Dataclasses are not being used as much as one might hope, but they
>> are relatively new, and many Python-Masters simply carry-on constructing
>> classes the way they have for years...
> 
> I think one concern I have is that even if this is useful, it might
> still fall to the same fate.


Don't be discouraged by that - and that thread was not the first of such
discussions! The way Python is being applied is continually changing...

I'm not sure about the criticism of dataclasses though. Starting with
'explicit over implicit', once a parameter-list is more than two or
three long, shouldn't we be using 'labels' in order to avoid (potential)
confusion, ie keyword-parameters?

This removes the order/sequence of arguments from the list of potential
problems/gotchas one can fall into!

In which case, I'm wondering just how often the criticism applies 'in
real life'?

So, now the question becomes: what are the cases/examples which
require/desire improvement over the 'traditional' __init__ of
attributes, and facilities offered through dataclasses?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Receive a signal when waking or suspending?

2022-04-23 Thread dn
On 24/04/2022 07.36, Skip Montanaro wrote:
> It's not clear there is a straightforward way to catch a signal or get
> an event notification when my computer (Dell running XUbuntu 20.04) is
> about to sleep or when it's just awakened. The app uses tkinter. Is
> there some more-or-less easy way to do this? Mac support would be nice
> (I have my eye on a new MacBook one of these days). I suppose bonus
> points for something which works on Windows, but that's not a platform
> I actually care about.


https://duckduckgo.com/?t=ffab&q=python+up+time pointed-out the
"uptime — Cross-platform uptime library"
- TLDR; I'm not sure if "uptime" and "boot" relate only to a
'cold-start' or if they include bringing the machine out of 'stand-by'
or 'hibernation'


https://duckduckgo.com/?t=ffab&q=python+battery+status pointed-out
several ideas which require MS-Windows, but apparently the psutil
library could be bent to your will:
https://www.geeksforgeeks.org/python-script-to-shows-laptop-battery-percentage/


Please let us know how you get on...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tail

2022-04-23 Thread dn
On 24/04/2022 09.15, Chris Angelico wrote:
> On Sun, 24 Apr 2022 at 07:13, Marco Sulla  
> wrote:
>>
>> On Sat, 23 Apr 2022 at 23:00, Chris Angelico  wrote:
>>>>> This is quite inefficient in general.
>>>>
>>>> Why inefficient? I think that readlines() will be much slower, not
>>>> only more time consuming.
>>>
>>> It depends on which is more costly: reading the whole file (cost
>>> depends on size of file) or reading chunks and splitting into lines
>>> (cost depends on how well you guess at chunk size). If the lines are
>>> all *precisely* the same number of bytes each, you can pick a chunk
>>> size and step backwards with near-perfect efficiency (it's still
>>> likely to be less efficient than reading a file forwards, on most file
>>> systems, but it'll be close); but if you have to guess, adjust, and
>>> keep going, then you lose efficiency there.
>>
>> Emh, why chunks? My function simply reads byte per byte and compares it to 
>> b"\n". When it find it, it stops and do a readline():
...

> Ah. Well, then, THAT is why it's inefficient: you're seeking back one
> single byte at a time, then reading forwards. That is NOT going to
> play nicely with file systems or buffers.
> 
> Compare reading line by line over the file with readlines() and you'll
> see how abysmal this is.
> 
> If you really only need one line (which isn't what your original post
> suggested), I would recommend starting with a chunk that is likely to
> include a full line, and expanding the chunk until you have that
> newline. Much more efficient than one byte at a time.


Disagreeing with @Chris in the sense that I use tail very frequently,
and usually in the context of server logs - but I'm talking about the
Linux implementation, not Python code!

Agree with @Chris' assessment of the (in)efficiency. It is more likely
than not, that you will have a good idea of the length of each line.
Even if the line-length is highly-variable (thinking of some of my
applications of the Python logging module!), one can still 'take a stab
at it' (a "thumb suck" as an engineer-colleague used to say - apparently
not an electrical engineer!) by remembering that lines exceeding
80-characters become less readable and thus have likely?hopefully been
split into two.

Thus,

N*(80+p)

where N is the number of lines desired and p is a reasonable
'safety'/over-estimation percentage, would give a good chunk size.
Binar-ily grab that much of the end of the file, split on line-ending,
and take the last N elements from that list. (with 'recovery code' just
in case the 'chunk' wasn't large-enough).

Adding to the efficiency (of the algorithm, but not the dev-time),
consider that shorter files are likely to be more easily--handled by
reading serially from the beginning. To side-step @Chris' criticism, use
a generator to produce the individual lines (lazy evaluation and low
storage requirement) and feed them into a circular-queue which is
limited to N-entries. QED, as fast as the machine's I/O, and undemanding
of storage-space!

Running a few timing trials should reveal the 'sweet spot', at which one
algorithm takes-over from the other!

NB quite a few of IBM's (extensively researched) algorithms which formed
utility program[me]s on mainframes, made similar such algorithmic
choices, in the pursuit of efficiencies.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-23 Thread dn
On 23/04/2022 08.35, Michael F. Stemper wrote:
> On 22/04/2022 14.59, Chris Angelico wrote:
>> On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper
>>  wrote:
>>>
>>> I'm writing a function that is nearly self-documenting by its name,
>>> but still want to give it a docstring. Which of these would be
>>> best from a stylistic point of view:
>>>
>>>
>>>     Tells caller whether or not a permutation is even.
>>>
>>>     Determines if a permutation is even. (Alternative is that it's odd.)
>>>
>>>     Returns True if permutation is even, False if it is odd.
> 
> 
>>
>> I'd go with the third one, but "Return" rather than "Returns". Or
>> possibly "Test whether a permutation is even".
> 
> "So let it be written. So let it be done."
> 
>> That's just one opinion though, others may disagree :)
> 
> Two for two. Thanks.


I've always taken the PEP somewhat for granted (with belated thanks and
respect to the authors and others who exerted effort (or would that be,
efforts?) to publish the finished work.

One of the things that I've taken-as-read, is WHY we use docstrings.
That rationale is wider than Python. Like many others, I just brought
that sort thinking with me.

Have you noticed that the PEP doesn't discuss this? It has taken this
thread to make me realise such.


The elephant in the style room is PEP-008. It's quite old in
'Python-years'! As time went by, PEP-257 became relevant - and I don't
recall which was 'chicken' and which 'egg', between the PEP and the
docutils/help/etc tools which depend upon a level of docstring
uniformity. No matter, together they represent a step of progress, after
PEP-008.

Since then we have added typing. Where once there was an extensive
documentation system to clarify the use of parameters and the definition
of return-values, now much of that can be done on the def-line (or
equivalent).

Another 'development' (I'd prefer 'natural progression') is that as
computers have become more powerful and storage cheaper, we have been
able to first justify, and now habitually, use longer identifier-names.
This step of progress should enable more descriptive and readable code.


So, we can consider that there are (now) three aspects which overlap,
considerably:

1 the name of the function
- descriptive and readable (see OP's assurance on this point)
2 typing
- description and distinction of parameters and return-values
3 docstring
- even more information about the function, how the author intends it be
used, embedded assumptions, etc

Thus, aren't there situations where a short, sharp, DRY, and SRP,
function; once well-named and accurately typed, could stand on its own
merits without a docstring. (yes, others will suck in their breath and
start preparing a bon-fire, at the utterance of such 'heresy'...)

We all hate 'boiler-plate', ie feeling forced to type stuff 'just
because', and particularly when it seems like duplication/repetition
(see recent thread(s) 'here' about __init__() and dataclasses). In fact,
one reason why we have functions is to reduce/remove (code) duplication!
So, why would we indulge in documental 'duplication' just-because we
should?must have a docstring?


While I'm tilting at windmills, wasn't option-2 the best?
(ooh, those flames are starting to warm my feet...)

Why? First, see other discussion about "imperatives".

My habit is to take the Statement of Requirements and copy it into a
brand-new __main__. As development proceeds, various details will be
extracted and copied into function and class docstrings. The language of
a specification should be imperative, ie you will *do* 'this'.

A second reason, is that the docstring should document the function,
which is subtly-different from describing the return-value (and that has
become a task for typing anyway).
(OK, the flames are getting-good, and it's time to break-out the
marsh-mallows and crumpets...)

So, 'nr2' describes what the function DOES!


PS would you mind passing-over the fire-extinguisher?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-24 Thread dn
On 25/04/2022 01.24, Michael F. Stemper wrote:
> On 23/04/2022 12.43, Avi Gross wrote:
>> Given what you added, Michael, your function is part of a
>> larger collection of functions and being compatible with the others
>> is a valid consideration. Whatever you decide, would ideally be done
>> consistently with all or most of them.
>> And, of course, it others in the collection also can handle multiple
>> ways to specify a permutation, it may be simpler to have each call
>> something like as.permutation() that handlesmultiple forms and
>> converts to the one easiest for you to use.
>> I am not sure that is needed as I suspect the simplest storage is
>> something like a list:  [0,3,2,4,5,6,7,1,9,8] but could also be shown
>> with each cycle as a sub-list or something like anumpy vector or a
>> customized class.
> 
> Since you ask, I'm using dictionaries as the internal representation.
> If you think about it, a python dictionary *is* a function from one
> finite set to another, mathematically. And a (finite) permutation is
> a bijection from a (finite) set to itself.
> 
> For convenience, the module provides two methods of defining a permutation
> other than just entering a dictionary:
> 
>  >>> import PermGroups as pg
>  >>> a = {'1':'2', '2':'1', '3':'3'}
>  >>> b = pg.ParsePerm( '(12)(3)' )
>  >>> c = pg.ParseDomImg( '123', '213' )
>  >>> a==b
>  True
>  >>> b==c
>  True
>  >>>
> 
> All of the other functions work on these dictionaries.
> 
> I had thought about defining a permutation object, but the conceptual
> match between "dict" and "permutation" was too good to discard.
> 
>> Clearly if you control the package and how it is used, errors from bad
>> data may not be a concern.
> 
> An invalidly-constructed permutation will cause an exception, so
> the function won't return.
> 
>  >>> d = {'1':'2', '2':'2', '3':'3'}
>  >>> pg.ValidateDict(d)
>  False
>  >>>
> 
> If I was to do it over, I would have named this function something
> like IsValidPermutation(), hiding the internal representation as
> well as making the function's Boolean nature explicit.


Yes, we live and learn!
(but 'technical debt'...)

Naming something based upon its implementation, eg ValidateDict(),
rather than its purpose, is a definite no-no - and while I'm
nit-picking, is that a function? (and thus validate_dict())

The idea of representing perms as dicts is good-thinking!

Please review UserDict
(https://docs.python.org/3/library/collections.html#collections.UserDict).
Sub-classing UserDict gives the advantages of a dict, without some of
the methods you don't want/need, and the ability to gather custom
permutation-methods into the class.

For a discussion about sub-classing dict or using UserDict, may I
recommend Trey Hunner's analysis, aka "there's no such thing as a free
lunch"
(https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/)

Since then, we've been given (and I haven't had a reason to try it, yet)
"PEP 589 – TypedDict: Type Hints for Dictionaries with a Fixed Set of
Keys" which may offer an alternate approach. This comes with the
advantage of 'compile-time' static analysis/checking
(https://peps.python.org/pep-0589/). When I get around to experimenting
with this, I'll be referring to "TypedDict vs dataclasses in Python"
(https://dev.to/meeshkan/typeddict-vs-dataclasses-in-python-epic-typing-battle-onb)

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tail

2022-04-24 Thread dn
On 25/04/2022 04.21, pjfarl...@earthlink.net wrote:
>> -Original Message-
>> From: dn 
>> Sent: Saturday, April 23, 2022 6:05 PM
>> To: python-list@python.org
>> Subject: Re: tail
>>
>  
>> NB quite a few of IBM's (extensively researched) algorithms which formed 
>> utility
>> program[me]s on mainframes, made similar such algorithmic choices, in the
>> pursuit of efficiencies.
> 
> WRT the mentioned IBM utility program[me]s, the non-Posix part of the IBM 
> mainframe file system has always provided record-managed storage since the 
> late 1960's (as opposed to the byte-managed storage of *ix systems) so 
> searching for line endings was (and is) irrelevant and unnecessary in that 
> environment.  That operating system also provides basic "kernel-level" 
> read-backwards API's for the record-managed file system, so there was never 
> any need to build reverse-read into your code for that environment.
> 
> The byte-managed file storage used by the Posix kernel running under the 
> actually-in-charge IBM mainframe operating system is, of course, subject to 
> the same constraints and (in)efficiencies discussed in this thread.


Thanks for the clarification (and @wlfraed's addition).

Apologies if misunderstood. The above comment was about utilities which
would choose between algorithms, based on some rapid, initial,
assessment of the task. It was not about 'tail' utility/ies specifically
- and I don't recall using a 'tail' on mainframes, but...

Thus, the observation that the OP may find that a serial,
read-the-entire-file approach is faster is some situations (relatively
short files). Conversely, with longer files, some sort of 'last chunk'
approach would be superior.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tail

2022-04-25 Thread dn
On 26/04/2022 10.54, Cameron Simpson wrote:
> On 25Apr2022 08:08, DL Neil  wrote:
>> Thus, the observation that the OP may find that a serial,
>> read-the-entire-file approach is faster is some situations (relatively
>> short files). Conversely, with longer files, some sort of 'last chunk'
>> approach would be superior.
> 
> If you make the chunk big enough, they're the same algorithm!
> 
> It sound silly, but if you make your chunk size as big as your threshold 
> for "this file is too big to read serially in its entirety, you may as 
> well just write the "last chunk" flavour.


I like it!

Yes, in the context of memory-limited mainframes being in-the-past, and
our thinking has, or needs to, moved-on; memory is so much 'cheaper' and
thus available for use!

That said, it depends on file-size and what else is going-on in the
machine/total-application. (and that's 'probably not much' as far as
resource-mix is concerned!) However, I can't speak for the OP, the
reason behind the post, and/or his circumstances...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Style for docstring

2022-04-25 Thread dn
On 26/04/2022 11.47, Rob Cliffe via Python-list wrote:
> Well, de gustibus non est disputandum.  For me, the switch from the
> imperative mode to the descriptive mode produces a mild cognitive
> dissonance.

Disagree!

When coding, to whom?what are you talking?

When writing documentation - same question?

This is the reason why (typically) coders are pretty bad at, or disagree
with a need for, 'documentation' - and particularly documentation that
doesn't fit inside a code-module!

(no insult, pure observation)

See earlier when I described taking a set of Requirements and
progressively applying specific clauses or requirements to a function.
One's thinking is in requirement-satisfaction-mode or 'design-mode'.
Later, when implementing the function, one can work in 'coding-mode'.

Separating tasks/roles removes the dissonance. No split-personality
required!

However, I know what you mean, and earlier today was writing to someone
about why I may not bother with a docstring if I'm in coding-mode and
wanting to 'keep going'. However, I see such as 'technical debt',
justified only in the hope that when I do get back to it (presumably
when the code is working, and I'm basking in the joys of (my own)
success, I'll be in more of a 'documentation' frame of mind...

(and pigs might fly!)



> On 25/04/2022 23:34, Cameron Simpson wrote:
>> On 23Apr2022 03:26, Avi Gross  wrote:
>>> We know some people using "professional" language make things shorteror
>>> talk from a point of view different than others and often in
>>> otherwise incomprehensible jargon.
>>> If a programmer is taking about the algorithm that a function
>>> implements, then, yes, they may write "scan" and "return".
>>> But if they realize the darn documentation is for PEOPLE asking
>>> how to use the darn thing, and want to write in more informal
>>> and understandable English, I think it makes more sense to say
>>> what the function does as in "scans" and importantly what it
>>> "returns" to the user as a result.
>> I'm in the imperative camp. But if I think the function requires some
>> elaboration, _then_ I provide description:
>>
>>  def f(x):
>>  ''' Return the frobnangle of `x`.
>>
>>  This iterates over the internals of `x` in blah order
>>  gathering the earliest items which are frobby and composes a
>>  nangle of the items.
>>  '''
>>
>> I very much like the concise imperative opening sentence, sometimes 2
>> sentences. Then the elaboration if the function isn't trivially obvious.
>>
>> Cheers,
>> Cameron Simpson 
> 

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Question re Executing a Script

2022-04-30 Thread dn
On 01/05/2022 10.37, Brent Hunter wrote:
> Hello,
> 
> I just purchased a new Windows 11 computer and installed Python 3.10.4 (64 
> bit).  I can't figure out from your documentation, how do I:
> 
> 
>   1.  Run a python script that is located in the same directory ( 
> C:\Users\Brent\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 
> 3.10 )
> 
> 
>   1.  How do I automatically run a python app at Windows startup?
> 
> Thank you!
> 
> Brent Hunter


Please start with https://docs.python.org/3/using/windows.html

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: Python Question re Executing a Script (dn)

2022-05-02 Thread dn
Perhaps an MS-Win user can help the OP, please?
-- 
Regards,
=dn--- Begin Message ---
Hello dn,

Thanks for your reply.  My apologies, I should have provided more background 
information.

I was recently running a Windows 10 machine and I believe it was running Python 
3.8.  All I did was create a batch file titled Start-AIG.bat which simply 
contained the following: "pythonw AIG.py".  It started a python program titled 
"AIG.py" and the Python dialog box was displayed on my screen, running all day 
and night.  I set up Windows to run this batch file upon startup and it worked 
fine.  I remember having to do a bunch of research before I learned that I 
needed to put "pythonw AIG.py" in the batch file as opposed to "python AIG.py".

However, my old windows 10 desktop crashed and I have a new Windows 11 machine. 
 I installed the latest stable version of Python, which is 3.10.  Now, when I 
try to execute the same batch file, it doesn't launch the app.  It could be 
because I'm using Windows 11 or could be because I now have a newer version of 
Python.

With this additional information, do you have any ideas what I should do to get 
the Python script running in the same way I had it running before?

Thank you!

Brent

-Original Message-
From: Python-list  On 
Behalf Of dn
Sent: Saturday, April 30, 2022 5:48 PM
To: python-list@python.org
Subject: Re: Python Question re Executing a Script

On 01/05/2022 10.37, Brent Hunter wrote:
> Hello,
> 
> I just purchased a new Windows 11 computer and installed Python 3.10.4 (64 
> bit).  I can't figure out from your documentation, how do I:
> 
> 
>   1.  Run a python script that is located in the same directory ( 
> C:\Users\Brent\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 
> 3.10 )
> 
> 
>   1.  How do I automatically run a python app at Windows startup?
> 
> Thank you!
> 
> Brent Hunter


Please start with https://docs.python.org/3/using/windows.html

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list
--- End Message ---
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python/New/Learn

2022-05-06 Thread dn
ected, but consolidated.
So, "repetition" at that level is more likely to lead to "retention".

Now applying a little psychological 'warning'. We (humans) tend to
approach devices in a particular mode, eg most people regard their car,
bike (etc) as a means of getting from 'A' to 'B'. Yes, there are others
who have a different perspective, and want to go racing, for example.
The same idea of 'this is what the machine does' or 'this is what I use
if for', applies to computers and smart-phones - and again, those of us
who regard them as a machine to 'master' or which which to build 'apps'
and develop software are akin to the 'racers'! Thus, if someone mainly
uses their device to watch movies, tweet, put their face in a 'book',
send 'telegrams', or record humorous events/Dad-dancing; is the 'mode'
in which they habitually use their device and thus the 'state of their
brain', congruent to or encouraging of "learning"?

The technology one poster 'here' requested, that video and text might
appear together and synchronised is (surprisingly?) available today and
has been for five~ten years. It is a base-feature of HTML5's video
facility. IIRC something similar is also reproduced and available
through the YouTube 'engine' (I don't use that). It is not common
because it is MORE WORK! In this part of the game, most people seek a
technology which will take the video's audio-track and transliterate
(speech-to-text). I've had to take up a practice that I never previously
used, and write every single word of a presentation (like a formal
speech). This forms the text component of a future video, but I (or the
presenter) then have to read the words whilst making our voices sound
more conversational - again, a skill most have not acquired, even having
been required to read-aloud for the class in junior/grade school!

This form of 'multi-media' forms one aspect of my research into
Cognitive Psychology (how one learns) and tool-building to ease
presentation-production and/or to promote learning.

Finally, I was amused by @BigTenor's comment about "pictographic
language". Some years ago, a theory was proposed that different people
learn in different ways, eg some prefer to hear whereas others to read.
Sadly, whilst this idea has immediate appeal because a casual
introspection will have many readily saying "I'm a ... learner"), the
theory has been debunked - both by primary-research and by
secondary-researchers critiquing the 'evidence' which didn't actually
make a proper attempt to prove the theory in-reality. However, it can be
a useful 'guide' - as long as that is as far as it is ever applied. A
lot of 'damage' is done by people telling themselves (or being told by
their 'betters') that they can only learn in one particular style (to
the exclusion of all others). Don't you believe it!

As above, some things are best explained one way, and others another, eg
an annotated map cf a list of directions. @Stefan's French spelling and
phonetic pronunciation guide in-combination illustrates this nicely.
(see also 'try...except', above) The interesting observation is that
whilst I may grasp some new concept from a text explanation in the
morning, I may need a diagrammatic approach to convey something similar,
this afternoon, ie we don't always learn using the same approach, every
time! Which leads to the idea of having multiple means of conveying
information, eg the MOOC's text and video content, because we hope that
if one doesn't 'do it for you', the other will!

Apologies for the lack of 'Python', but thanks for the discussion (and
am hoping you won't mind me passing it around amongst my colleagues -
perhaps there's not much that is 'new' (for us) but the fact that it is
being discussed by folk who are primarily practitioners is most helpful!)
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: .0 in name

2022-05-13 Thread dn
This is not what @Avi menat by "silly variable names" but:

3D_position

2nd_floor_area

3M_PostIt_size

3rd_degree_polynomial

360_degree_view

12_hours_later

and ???
2_fast_2_furious

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: EAFP

2022-05-13 Thread dn
On 14/05/2022 04.37, bryangan41 wrote:
> Is the following LBYL:foo = 123if foo < 200:    do()

Yes (once formatted for Python).


If so, how to change to EAFP?

Not sure if can. Let's alter the code to:

foo = 0

#and

def do():
return 5 / foo

Then, you will expect a ZeroDivisionError exception to be raised -
whereas with other values, there will (likely) be no problem.

Now, we have a clear identification for when 'forgiveness' will need to
be requested! The 'EAFP' solution encloses the function-call:

foo = 123
try:
do()
except ZeroDivisionError:
undo()


In the OP's code-snippet, the "200" criteria means there is no such
clean-cut and automatic 'failure' attached to, or implied by, foo's
value. However, we could define a custom-exception and 'raise the alarm'
when 'forgiveness' is required:

class ValueTooLargeError( ValueError):
"""Catch values larger than the valid range."""

def do():
if foo < 200:
...
else:
raise ValueTooLargeError

This is a pythonic-construct (and thus a recommendable coding-pattern),
in that the calling-routine can decide how to respond to the exception -
which many vary according to the specifics of do()'s re-use.


However, is it "EAFP"? We had to introduce the exact if-condition which
makes it "LBYL"!

Perhaps time for me to bow-out, and leave such to the philosophers...


Sent from Samsung tablet.

There are pills for that...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing calling sequence

2022-05-14 Thread dn
On 12/05/2022 01.33, Michael F. Stemper wrote:
> I have a function that I use to retrieve daily data from a
> home-brew database. Its calling sequence is;
> 
> def TempsOneDay( year, month, date ):
> 
> After using it (and its friends) for a few years, I've come to
> realize that there are times where it would be advantageous to
> invoke it with a datetime.date as its single argument.
> 
> As far as I can tell, there are three ways for me to proceed:
> 1. Write a similar function that takes a single datetime.date
>    as its argument.
> 2. Rewrite the existing function so that it takes a single
>    argument, which can be either a tuple of (year,month,date)
>    or a datetime.date argument.
> 3. Rewrite the existing function so that its first argument
>    can be either an int (for year) or a datetime.date. The
>    existing month and date arguments would be optional, with
>    default=None. But, if the first argument is an int, and
>    either of month or date is None, an error would be raised.
> 
> The first would be the simplest. However, it is obviously WET
> rather than DRY.
> 
> The second isn't too bad, but a change like this would require that
> I find all places that the function is currently used and insert a
> pair of parentheses. Touching this much code is risky, as well
> as being a bunch of work. (Admittedly, I'd only do it once.)
> 
> The third is really klunky, but wouldn't need to touch anything
> besides this function.
> 
> What are others' thoughts? Which of the approaches above looks
> least undesirable (and why)? Can anybody see a fourth approach?


Reading the above, it seems that the options are limited to using
positional-arguments only. Because I keep tripping-over my long, grey,
beard; I'm reminded that relying upon my/human memory is, um, unreliable
(at least in my case). Accordingly, by the time a function's definition
reaches three parameters, I'll be converting it to use keyword-arguments
as a matter of policy. YMMV!

Remember: if keyword arguments are not used (ie existing/legacy code),
Python will still use positional logic.

Once the function's signature has been changed, we could then add
another keyword-parameter to cover the datetime option.


That said, a function which starts with a list of ifs-buts-and-maybes*
which are only there to ascertain which set of arguments have been
provided by the calling-routine; obscures the purpose/responsibility of
the function and decreases its readability (perhaps not by much, but
varying by situation).

Accordingly, if the function is actually a method, recommend following
@Stefan's approach, ie multiple-constructors. Although, this too can
result in lower readability.

Assuming it is a function, and that there are not many alternate
APIs/approaches (here we're discussing only two), I'd probably create a
wrapper-function which has the sole task of re-stating the datetime
whilst calling the existing three-parameter function. The readability
consideration here, is to make a good choice of (new) function-name!


* Python version >= 10? Consider using match-case construct keyed on
parameter-type
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing calling sequence

2022-05-14 Thread dn
On 15/05/2022 11.34, 2qdxy4rzwzuui...@potatochowder.com wrote:
> On 2022-05-15 at 10:22:15 +1200,
> dn  wrote:
> 
>> That said, a function which starts with a list of ifs-buts-and-maybes*
>> which are only there to ascertain which set of arguments have been
>> provided by the calling-routine; obscures the purpose/responsibility
>> of the function and decreases its readability (perhaps not by much,
>> but varying by situation).
> 
> Agreed.
> 
>> Accordingly, if the function is actually a method, recommend following
>> @Stefan's approach, ie multiple-constructors. Although, this too can
>> result in lower readability.
> 
> (Having proposed that approach myself (and having used it over the
> decades for functions, methods, procedures, constructors, ...), I also
> agree.)
> 
> Assuming good names,¹ how can this lead to lower readability?  I guess
> if there's too many of them, or programmers have to start wondering
> which one to use?  Or is this in the same generally obfuscating category
> as the ifs-buts-and-maybes at the start of a function?
> 
> ¹ and properly invalidated caches

Allow me to extend the term "readability" to include "comprehension".
Then add the statistical expectation that a class has only __init__().
Thus, assuming this is the first time (or, ... for a while) that the
class is being employed, one has to read much further to realise that
there are choices of constructor.


Borrowing from the earlier example:

>   This would be quite pythonic. For example, "datetime.date"
>   has .fromtimestamp(timestamp), .fromordinal(ordinal),
>   .fromisoformat(date_string), ...

Please remember that this is only relevant if the function is actually a
module - which sense does not appear from the OP (IMHO).

The alternatives' names are well differentiated and (apparently#)
appropriately named*.


* PEP-008 hobgoblins will quote:
"Function names should be lowercase, with words separated by underscores
as necessary to improve readability.
Variable names follow the same convention as function names."
- but this is a common observation/criticism of code that has been in
the PSL for a long time.

# could also criticise as not following the Software Craftsmanship/Clean
Code ideal of 'programming to the interface rather than the
implementation' - which we see in PEP-008 as "usage rather than
implementation"
(but please don't ask me how to differentiate between them, given that
the only reason for the different interfaces is the
function's/parameters' implementation!)

NB usual caveats apply to PEP-008 quotations!


So, I agree with you - it comes down to those pernicious
'ifs-buts-and-maybes'. If the interface/parameter-processing starts to
obfuscate the function's actual purpose, maybe it can be 'farmed-out' to
a helper-function. However, that would start to look very much like the
same effort (and comprehension-challenge) as having a wrapper-function!


Continuing the 'have to read further' criticism (above), it could
equally-well be applied to my preference for keyword-arguments, in that
I've suggested defining four parameters but the user will only call the
function with either three or one argument(s). Could this be described
as potentially-confusing?


Given that the OP wouldn't want to have to redefine the existing
interface, the next comment may not be applicable - but in the interests
of completeness: anyone contemplating such architecture might like to
consider "Single-dispatch generic functions"
(https://peps.python.org/pep-0443/). At least the decorators signal that
there are alternative-choices...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bug in python 3.10.4

2022-05-25 Thread dn
On 26/05/2022 13.46, Shuaib Akhtar wrote:
>When double clicking a .py file when have python install. It run file but
>at a spot of the program it stop running. But using the built-in ide for
>python this problem does not happen also any other ide it work fine

Please provide (minimal) example code so that we can reproduce the
problem and, if necessary, help find a solution...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: bug in python 3.10.4

2022-05-26 Thread dn
Please reply to the list. Others may be able to assist (particularly if
they use MS-Windows!).


> Removing the  quit does not help with the problem.
> 
> input 10 x 10

What was the result, or the exception report.

Once again: did MS-Windows finish the job and close the window before
you could see the result?



On 26/05/2022 15.44, dn wrote:
>>When double clicking a .py file when have python install. It run file but
>>at a spot of the program it stop running. But using the built-in ide for
>>python this problem does not happen also any other ide it work fine
> 
> 
> The code looks good (although most IT-people think of * as the
> multiplication operator).
> 
> At present, the only way to stop the program is to enter two numbers and
> an invalid operator. This leads to the quit(). I'm not a user of
> MS-Windows, but won't that close the window without giving any
> opportunity to read the screen? Can you try commenting-out the quit()
> and replacing it with a print( "terminating" ) type of message? Does
> this help with the "stop running"?
> 
> To enable us to run the program[me] to produce the same results, what
> combination of input produces the error, what output results, and do you
> see any exception messages? Please copy-paste into your email-reply.
> 
> (the more you help us, the better we can help you!)
> 
> 
> 
> On 26/05/2022 15.12, Shuaib Akhtar wrote:
>>  
>>
>>  
>>
>> number_1 = input("put a number\n")
>>
>> print('division is /')
>>
>>  
>>
>> operations = input("put a operations\n")
>>
>> number_2 = input("put a number\n")
>>
>>  
>>
>> number_2 = float(number_2)
>>
>> number_1 = float(number_1)
>>
>>  
>>
>> if operations == "+":
>>
>>     print(number_1+number_2)
>>
>> elifoperations.lower() == "x":
>>
>>     print(number_1 * number_2)
>>
>> elifoperations == "/":
>>
>>     print(number_1/number_2)
>>
>> elifoperations == "-":
>>
>>     print(number_1 - number_2)
>>
>> else:
>>
>>     print("put a operation next time")
>>
>>     quit()
>>
>>  
>>
>>  
>>
> 
> 


-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: terminate called after throwing an instance of 'boost::python::error_already_set

2022-05-27 Thread dn
On 28/05/2022 08.14, Larry Martell wrote:
> I have a script that has literally been running for 10 years.
> Suddenly, for some runs it crashes with the error:
> 
> terminate called after throwing an instance of 
> 'boost::python::error_already_set
> 
> No stack trace. Anyone have any thoughts on what could cause this
> and/or how I can track it down?

1 a change to Python interpreter being used

2 a change to the boost library being used

3 a change to lower levels in 'the s/w stack' or h/w

4 a change to the data being passed-across
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: terminate called after throwing an instance of 'boost::python::error_already_set

2022-05-27 Thread dn
On 28/05/2022 11.11, Larry Martell wrote:
> 
> 
> On Fri, May 27, 2022 at 5:51 PM dn  <mailto:pythonl...@danceswithmice.info>> wrote:
> 
> On 28/05/2022 08.14, Larry Martell wrote:
> > I have a script that has literally been running for 10 years.
> > Suddenly, for some runs it crashes with the error:
> >
> > terminate called after throwing an instance of
> 'boost::python::error_already_set
> >
> > No stack trace. Anyone have any thoughts on what could cause this
> > and/or how I can track it down?
> 
> 1 a change to Python interpreter being used
> 
> 2 a change to the boost library being used
> 
> 3 a change to lower levels in 'the s/w stack' or h/w
> 
> 4 a change to the data being passed-across
> 
> 
> Definitely not 1. 4 is always the case - every run is with different
> data. 2 and 3 I don’t know. What is boost and how does Python use it?
> None of my code is importing it. How can get a stack trace when it
> crashes with just that message?  


A possibly/hopefully helpful explanation appears at:
https://misspent.wordpress.com/2009/10/11/boost-python-and-handling-python-exceptions/

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help, please, with 3.10.4 install

2022-05-29 Thread dn
On 29/05/2022 14.11, Jack Gilbert wrote:
> I downloaded 3.10.4 on a 64 bit , 8.1
> I can see IDLE shell 3.10.1, I see Python 3.10.4 (tags/v3.10.4:9d38120, Mar
> 23 2022, 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32
> 
> also, the same line: Python 3.10.4 (tags/v3.10.4:9d38120, Mar 23 2022,
> 23:13:41) [MSC v.1929 64 bit (AMD64)] on win32 in CMD prompt
> 
> for the life of me I can't figure out how to launch python??
> 
> I did click add to path in the install
> 
> thanks


Please advise if https://docs.python.org/3/using/windows.html does not
answer the question...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problems with Python

2022-05-31 Thread dn
On 01/06/2022 00.00, Howard Samuels via Python-list wrote:
> Good day
> I am new to programming.  I have signed up for a virtual online course and 
> installed Python using Anaconda as well as jupyter notebook. I encountered 
> problems & then went to YouTube tried going directly to the python website 
> and used Pycharm. When I used pycharm and try to run the first basic program 
> I am getting a message that it is unable to load the Virtual environment.  
> Also a message that ??the SDK seem to be false??? or some like wording.  I 
> went to google which gave me stock overflow.  I am confused there as some of 
> the responses I see there suppose that I am into programming and understand a 
> lot of these terms. Some things I see, I understand but none of those have 
> made a difference.  One such is to type "pip install virtenv" The system 
> states that the requirement is already satisfied.  
> In the process of trying to uninstall & reinstall and saw the invitation to 
> write seeking for help.  I therefore cannot immediately reproduce the error 
> message.Can you help?


So many 'moving parts' and unnecessarily-advanced features are described
here. No wonder your head is spinning!

Which course? How does *it* recommend setting-up the Python environment?

Failing that, start PyCharm, open a new project, open a new Python file,
type:

a = 2 + 2
print( a )

and use the PyCharm command to "run".

Build from there, one step at a time!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: min, max with position

2022-06-04 Thread dn
On 05/06/2022 06.56, Dennis Lee Bieber wrote:
> On Sat, 4 Jun 2022 13:36:26 -0500, "Michael F. Stemper"
>  declaimed the following:
> 
>>
>> Are there similar functions that return not only the minimum
>> or maximum value, but also its position?
>>
>   If it isn't in the library reference manual, NO...
> 
>   But it also isn't that difficult to write...
> 
>>>> def whatAt(function, data):
> ...   what = function(data)
> ...   at = data.index(what)
> ...   return (at, what)
> ... 
>>>> l = [  1.618033,   3.1415923536,   2.718282]
>>>> whatAt(min, l)
> (0, 1.618033)
>>>> whatAt(max, l)
> (1, 3.1415923536)
>>>>
> 
> (properly, I should either reverse the order of the return value, or change
> the name to atWhat() )

...and remembering the special case:
if the what value appears more than once in the list, the where?at will
report the first/'left-most' index only.

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: min, max with position

2022-06-04 Thread dn
On 05/06/2022 09.50, Chris Angelico wrote:
> No, but it shouldn't be too hard to make it if you want it. The
> obvious option of calling max/min on the enumerated list won't work on
> its own, since the index comes before the value, but with a key
> function it would work fine:
> 
>>>> min(enumerate(l), key=lambda x: x[1])
> (0, 1.618033)
>>>> max(enumerate(l), key=lambda x: x[1])
> (1, 3.141593)

An elegant solution!

But, but, but which of the above characters is an 'el' and which a 'one'???
(please have pity on us old f...s and the visually-challenged!)

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread dn
On 08/06/2022 07.35, Dave wrote:
> Hi,
> 
> I’m new to Python and have a simple problem that I can’t seem to find the 
> answer.

> I want to test the first two characters of a string to check if the are 
> numeric (00 to 99) and if so remove the fist three chars from the string. 
> 
> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want 
> “Trinket”. I can’t for the life of work out how to do it in Python?

This sounds like an assignment or quiz-question. We could provide an/the
answer - but then you wouldn't learn how to solve it for yourself...


There is a gentle introduction to "slicing" (taking the first two
characters) at
https://docs.python.org/3/tutorial/introduction.html?highlight=slicing

Characters can be turned into int[egers], as discussed at
https://docs.python.org/3/library/stdtypes.html#typesnumeric

Of course precautions must be taken in case the string is not an
integer, eg https://docs.python.org/3/tutorial/errors.html?highlight=except

Another approach might be to use isnumeric(),
https://docs.python.org/3/library/stdtypes.html?highlight=isnum


NB the first URL-pointer is a page in the Python Tutorial. Reading that
in its entirety may be a good investment of time!

Are you aware of the Python Tutor list?

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread dn
>>>> It depends on the language I’m using, in Objective C, I’d use isNumeric, 
>>>> just wanted to know what the equivalent is in Python.
>>>>
>>>> If you know the answer why don’t you just tell me and if you don’t, don’t 
>>>> post!
>>>
>>> People ask home work questions here and we try to teach a student with 
>>> hints not finished answers.
>>> Your post was confused with a home work question.
>>
>> In the future, to make it look less like a homework question, show
>> your current code, which would provide context. Last I checked,
>> homework questions don't usually involve ID3 tags in MP3 files :)

Ah, so that's where I've seen it before!
(thanks for scratching my head @Chris - but watch-out for splinters!)

Yes, the problem has been used as a training exercise, eg same song but
in different albums/play-lists, different capitalisation, and such-like;
ie 'data cleaning' and harmonisation - good for use at the intersection
of Python and SQL (or NoSQL).


Knowing the background, and thus the particular need, would have saved a
lot of time - giving the answer as code (per one of the contributions)
would have taken considerably less effort than looking-up and citing the
docs.

Perhaps then, the 'learning-opportunity' is that when such questions pop
into one's mind, 'the docs' is *the* recommended first-call?


> The original question in this thread didn't say anything about MP3
> files.  Jumping to that conclusion from strings like '05 Trinket' was
> left as an exercise for the interested reader.  :-)

This reader's interest was to figure-out why "trinket" didn't refer to
some small decoration or 'bling', nor to a Python training tool
(https://trinket.io/), but to a music group/video series.
(even more-surprising: that this grey-beard recognised one of their tracks).


On the other side of the relationship, writers are expected to follow
the PSF Code of Conduct (https://www.python.org/psf/conduct/), eg
respect, acknowledgement, grace...

Such also encourages (positive) responses when asking future questions...


Now that you (@Dave) have revealed yourself as more than a raw-beginner,
and to have skills transferable to the Python world, it'll be great to
see you 'here', contributing to others' posts...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test characters of a string

2022-06-07 Thread dn
On 08/06/2022 10.18, De ongekruisigde wrote:
> On 2022-06-08, Christian Gollwitzer  wrote:
>> Am 07.06.22 um 21:56 schrieb Dave:
>>> It depends on the language I’m using, in Objective C, I’d use isNumeric, 
>>> just wanted to know what the equivalent is in Python.
>>>
>>
>> Your problem is also a typical case for regular expressions. You can 
>> create an expression for "starts with any number of digits plus optional 
>> whitespace" and then replace this with nothing:
> 
> Regular expressions are overkill for this and much slower than the
> simple isdigit based solution.

...

> Regular expressions are indeeed extremely powerful and useful but I tend
> to avoid them when there's a (faster) normal solution.

Yes, simple solutions are (likely) easier to read.

RegEx-s are more powerful (and well worth learning for this reason), but
are only 'readable' to those who use them frequently.

Has either of you performed a timeit comparison?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need help in blockchain coding.

2022-06-11 Thread dn
On 12/06/2022 02.51, Ayesha Tassaduq wrote:
> I am a beginner in python I want to transfer generated hash to a local 
> database. I try it with socket programming but I fail. can anyone please help 
> me ow I can do this?

Where is the database?
Where is the socket?
What are the (full) error messages?


> class Block:
> def __init__( self, previous_block_hash, transaction_list ):
> self.previous_block_hash = previous_block_hash
> self.transaction_list = transaction_list
> 
> self.block_data = f"{' - '.join(transaction_list)} - 
> {previous_block_hash}"
> self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()
> 
> 
> class Blockchain:
> def __init__( self ):
> self.chain = [ ]
> self.generate_genesis_block()
> 
> def generate_genesis_block( self ):
> self.chain.append(Block("0", [ 'Genesis Block' ]))
> 
> def create_block_from_transaction( self, transaction_list ):
> previous_block_hash = self.last_block.block_hash
> self.chain.append(Block(previous_block_hash, transaction_list))
> 
> def display_chain( self ):
> for i in range(len(self.chain)):
> print(f"Hash {i + 1}: {self.chain [ i ].block_hash}\n")
> 
> @property
> def last_block( self ):
> return self.chain [ -1 ]
> 
> 
> **t1 = Time_sensitive_df
> t2 = "abcdefghijklmnopqrstuvwxyz"
> t3 = normal_df
> myblockchain = Blockchain()
> myblockchain.create_block_from_transaction(t1)
> myblockchain.create_block_from_transaction(t2)
> myblockchain.create_block_from_transaction(t3)
> myblockchain.display_chain()**

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: fill out bulletins

2022-06-13 Thread dn
On 14/06/2022 11.34, MRAB wrote:
> On 2022-06-13 23:41, jak wrote:
> [snip]
>>
>> If you are interested in seeing what I called "post office bulletin"
>> (English is not my language and I don't know the name, sorry), you can
>> find a sample pdf (fillable) but it works badly here:
>>
>> https://www.guardiacostiera.gov.it/venezia/Documents/Bollettino%20MOD.%20TD123.pdf
>>
> 
> Probably best to just call it a "form".

pygame might offer a simple way to add text to a 'form' at appropriate
x,y co-ordinates.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Call for speakers/guides (virtual Python User Group meetings)

2022-06-16 Thread dn
TLDR; our PUG seeks (speakers or guides). Message contains a range of
Python-related topics requested by attendees.


To follow-up requests from meeting-attendees, herewith a call for
speakers/guides. Would you show us what you've learned, please?

- state transitions/finite state machines
  (pref not all 'math' eg IoT or the usual example of a vending machine)

- working with the web (several, separate, topics):
  - web-scraping
  - building and displaying a web-page, eg flask
  - async versions of the above, eg fastapi
  - accessing APIs, building APIs
  - PyIodide
  - authentication and identity/membership

- working with databases
  - SQL and RDBMS
  - NoSQL, eg MongoDB
  - graph databases
  - coding with inversion of control for flexible choice of I/O

- Python programming
  - Python idioms
  - basic coding techniques and tactics
  - developing from problem to solution
  - practical follow-up to our series on Software Craftsmanship/SOLID
eg implementing SRP, when to split into functions, classes, modules

We'll be interested to include any other ideas. What excites you?
Perhaps something that has come through the PEP process and was added to
Python 3.n recently?

Other suggested topics at https://cloud.nzoss.nz/s/6WbkbBzydcqsNaE


The Auckland Python Users' Group holds two meetings a month on Wednesday
evenings (NZST). A "Coding Evening" which suits a 'live demo' or 'code
along with me' type of hands-on approach. Also a "Presentation Evening"
which often consists of talk-and-slides. We operate virtually (using
BigBlueButton) - so location is irrelevant, but time-zone differences
may be! Attendees range from 'Apprentices' to 'Python Masters', all keen
to advance in Python. Atmosphere is helpful, humorous, and constructive,
ie thoroughly Kiwi! (more information is available to interested-parties)

What's in it for you? Apart from a solid addition to your CV, and a
burnished record in the Python-community? Any and all help will be given
in putting a talk/tutorial together, and/or making the best use of the
BBB web-conferencing tool.

Please follow-up with Pete and myself - offline from this list.

-- 
Regards =dn,
Facilitator and General Factotum to:
Pete Mayes, Benevolent Dictator/Leader for life, of:
NZPUG - Auckland Branch
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pycharm issue

2022-06-17 Thread dn
On 18/06/2022 10.52, GIORGOS PORIOTIS wrote:
>  > Hello i have an issue with my pycharm latest edition, it doesnt take the
> files in the pycharm window , when i click on
>  > them , also intead of the pycharm picture on my py files i have the idle
> picture ...

This list is for Python (cf PyCharm)! However, many of us use PyCharm...

What are you typing or clicking-on to start Python/Idle/PyCharm?
Which operating system?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pycharm issue

2022-06-17 Thread dn
On 18/06/2022 11.21, Giorgos Poriotis wrote:
> I use windows 10 , I click on a shortcut of the pycharm , the icon that
> runs the programm

Please reply to the list - there are many people here who know more than
I, and can help you with MS-Windows issues.

Please review https://docs.python.org/3/using/windows.html

If it is a matter of choosing which/how to open .py files, that is an
MS-Win question. There may be a decision to be made: does clicking on a
.py file mean that you wish to edit it (in PyCharm), or do you wish to
run the code in the Python interpreter.


> *From: *dn <mailto:pythonl...@danceswithmice.info>
> *Sent: *Saturday, June 18, 2022 02:05
> *To: *python-list@python.org <mailto:python-list@python.org>
> *Subject: *Re: pycharm issue
> 
>  
> 
> On 18/06/2022 10.52, GIORGOS PORIOTIS wrote:
> 
>>  > Hello i have an issue with my pycharm latest edition, it doesnt
> take the
> 
>> files in the pycharm window , when i click on
> 
>>  > them , also intead of the pycharm picture on my py files i have the
> idle
> 
>> picture ...
> 
>  
> 
> This list is for Python (cf PyCharm)! However, many of us use PyCharm...
> 
>  
> 
> What are you typing or clicking-on to start Python/Idle/PyCharm?
> 
> Which operating system?


-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "CPython"

2022-06-20 Thread dn
On 21/06/2022 09.47, Roel Schroeven wrote:
...

> So we have an untrustworthy site that's the only one to claim that
> CPython is short for Core Python, and we have an official site that says
> CPython is so named because it's written in C. Hm, which one to believe?


...and so you can C that the only important part is the Python!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "CPython"

2022-06-20 Thread dn
On 21/06/2022 10.02, Chris Angelico wrote:
> On Tue, 21 Jun 2022 at 08:01, dn  wrote:
>>
>> On 21/06/2022 09.47, Roel Schroeven wrote:
>> ...
>>
>>> So we have an untrustworthy site that's the only one to claim that
>>> CPython is short for Core Python, and we have an official site that says
>>> CPython is so named because it's written in C. Hm, which one to believe?
>>
>>
>> ...and so you can C that the only important part is the Python!
> 
> I should have cn that coming.


Which is a terribly OT invitation to make the (these days non-PC) Monty
Python joke: "No-one expects the Spanish Inquisition"
(https://www.youtube.com/watch?v=Cj8n4MfhjUc)
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why this code giving recursion error????

2022-06-26 Thread dn
On 26/06/2022 22.48, נתי שטרן wrote:
> def compile(p, flags=0):
> # internal: convert pattern list to internal format
> 
> if (isinstance(p,str)):
> pattern = p
> p = sre_parse.parse(p, flags)
> else:
> pattern = None
> 
> code = _code(p, flags)
> 
> if flags & SRE_FLAG_DEBUG:
> print()
> dis(code)
> 
> # map in either direction
> groupindex = p.state.groupdict
> indexgroup = [None] * p.state.groups
> for k, i in groupindex.items():
> indexgroup[i] = k
> 
> return sre_compile.compile(
> pattern, flags | p.state.flags, code,
> p.state.groups-1,
> groupindex, tuple(indexgroup)
> )


Why would any code give a recursion error?

With recursion problems, the first question to ask is: how does this
thing stop?

Have you built some test-data with only a handful of items, and thus a
predictable result. Does that result occur? If not, where are the
differences occurring?
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why this code giving recursion error????

2022-06-26 Thread dn
On 26/06/2022 23.00, נתי שטרן wrote:
> I FIXED THE CODE 

For the benefit of future-readers: how did you go about fixing it? What
was wrong?

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Include mailing list

2022-07-09 Thread dn
Dear Mxolisi,

On 09/07/2022 22.08, Mxolisi Mbandezi wrote:
> Dear Python developers
> Please,include me in your mailing list.

Please follow the instructions, at the link which appears below:-

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


FYI: Kiwi PyCon

2022-07-17 Thread dn
The first Kiwi PyCon of the COVID-era takes place in one month's time
(19~22 August), in-person at Ōtautahi Christchurch, and on-line. You
will be most welcome!

New Zealand is in the UTC+12 time-zone.

Tickets are priced according to your choice of in-person or virtual.
Reduced rates are offered to students and others. Professionals and
corporations are invited to provide valuable support through the Kiwi
tradition of buying two tickets - donating the second to someone more
'flush' with enthusiasm for Python than with cash.

More info at kiwipycon.nz.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


UML, CVS, and Crafting Software: NZPUG Auckland Branch

2022-07-17 Thread dn
You commit code to git (or some other CVS) all-day, every-day.
Similarly, you probably work on/from/with UML diagrams. Our PUG seeks
someone willing to demonstrate the very basic use of UML and/or CVS (as
related to Python), please.


We meet (virtually) in the UTC+12 time-zone (0600~0830 UTC) which suits
'late-owls' on the US west coast; everyone across Oceania, Asia, and the
Middle East; through to folk waking-up in the UK and Europe.


We are currently enjoying a bi-monthly "Software Craftsmanship" series
in our monthly 'Presentation Evenings', with a theme of (raising)
professional standards, led by Olaf Thielke.

As you will expect, the illustration of some points uses UML diagrams.
Accordingly, some of our hobbyists, 'Beginners' and 'Journeymen' will
gain more - if they first understand how to read basic UML diagrams!


The branch's 'Coding Evenings' (our second set of monthly meetings)
currently complement the above with a 'code along at home' series called
'Crafting Software' led by dn and DJ. It aims to help coders learn some
Python, acquire coding techniques, and to reflect-on and benefit-from
the principles of Software Craftsmanship (ie approaching from the
bottom-up or what I call: 'SOLID by stealth').

We're coding a (very) simplistic 'Business Rule', and gradually
building-out and improving/refactoring as we go. At each stage we could
retain the code by saving under a different module-name. Alternately,
here is an ideal opportunity to illustrate how a versioning system
enables one to remember, and later review and recall, 'history'!

Here's where a short and practical demo of 'getting started with git'?
(or ... CVS) will fit neatly into the series, perhaps on Wed 3 August.
NB no need for multiple branches, diff-resolution, etc, etc.


What's in it for me? In-return, the PUG's leadership-team will offer
assistance including teaching you how to pull-together a talk (you know
the subject but would like some help in presenting to others), thus
building your competence and profile.

We meet virtually, using the BigBlueButton web-conferencing
software, and will be happy to extend your skills in that direction too!


The PUG's Meetup group is https://www.meetup.com/nzpug-auckland/ More
information about the group is available upon request. Happy to answer
questions.


Please consider offering a short but highly-pragmatic demonstration,
contributing to our professional-improvement.

Reply to me (off-list) and I'll introduce you to the wider
PUG-leadership team...

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: script folder is empty

2022-07-17 Thread dn
On 18/07/2022 16.53, Scott Baer wrote:
> I just installed Python 3.10.5 on a Windows 10 home ( Ver 21H2 OS build
> 1904431826).
> I'm logged in with admin privileges
> I did a custom install with  python-3.10.5-amd64.exe to C:\Program
> Files\Python310
> Installed with both For all Users & PIP selected.
> ;
> once It was done installing, I rebooted and can run python:
> Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64
> bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>>
> 
> when I try to run:  pip --version
> C:\Users\baerr>pip --version
> 'pip' is not recognized as an internal or external command,
> operable program or batch file.
> 
> I've done some troubleshooting, and nothing is in the C:\Program
> Files\Python310\Scripts folder.
> 
> I"m not a noob.. but obviously, I missing something..   I doubt this is a
> bug.
> 
> Any help is much appreciated !!

I don't use MS-Windows. Have you perused the docs?
eg https://docs.python.org/3/using/windows.html?highlight=windows

DuckDuckGo's first 'hit' for "How to Install PIP for Python on Windows"
is https://www.liquidweb.com/kb/install-pip-windows/ - but please be
aware that what comes-with varies according to the source used to obtain
the copy of Python, and (perhaps) the version of MS-Win. YMMV!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Information about updating my python notebook

2022-07-23 Thread dn
On 24/07/2022 04.16, nhlanhlah198506 wrote:
> Can I update my python account Sent from my Galaxy

How did you install Python, and on which OpSys?

In what respect to you want to "update"?
What do you mean by "notebook" - and "account"?

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Object in List : how?

2022-07-23 Thread dn
On 24/07/2022 09.57, MRAB wrote:
> On 23/07/2022 05:28, Khairil Sitanggang wrote:
>> Hello Expert:
>>
>> I just started using python. Below is a simple code.  I was trying to
>> check
>> if, say, NO1 is not in the NODELIST[:].NO
>> How can I achieve this purpose?
>>
>> Regards,
>> -Irfan
>>
>>
>> class Node:
>>  def __init__(self):
>>  self.NO = 0
>>  self.A = 20
>>
>> NODE = Node()
>> NODELIST = []
>>
>> NODE.NO = 10
>> NODELIST.append(NODE)
>>
>> NODE.NO = 20
>> NODELIST.append(NODE)
>>
>> NODE.NO = 30
>> NODELIST.append(NODE)
>>
>>
>> NO1 = 20
>> if NO1 not in NODELIST[:].NO  ???
> 
> No, you can't do it that way. You have to iterate through the list and
> check each member individually:
> 
>     if any(NO1 == N.NO for N in NODELIST):
> 
> And another thing: you've created only 1 node, and you're changing it
> each time before adding it to the list, so the list ends up with 3
> references to the _same_ object.

+1


Imagine the object (Node) was instead a person, and a bunch of us-people
get together in a room. You could shout (above the polite conversation)
"is Fred here?" and Fred will reply - or if Fred is elsewhere, silence
will reign. That works - but only because everyone knows their own name.

Now imagine something like (my) grade school, where the teacher takes a
roll/register to note who is present for (or absent from) class. In this
case another staff-member could enter the room and instead of shouting
(which would be rude), can ask the teacher "is Fred here?". The teacher
is able to answer from the roll.

The former case is (sort of) the solution proposed above - in looking
for Fred, you walk through the room, asking each person in-turn "are you
Fred?".

The latter is the case for Node and what you were hoping to implement.

Thus, an alternate approach is to keep a register of nodes. Note that
this is more than a list, because each element of the list (each node)
is also identified (on the list) by its name. So, two pieces of
(related) data: the id of the node, and the node itself - the name of
the person and the person him-/her-self.

Assuming you only have one ID that will be used to access a node,
Python's built-in dict[ionary] data-structure will provide the advantage
of direct-access (instead of going through (on average) half the nodes,
asking each one in-turn, are you ...

So:

> NODE = Node()
> NODELIST = []
> 
> NODE.NO = 10
> NODELIST.append(NODE)

becomes:

graph = dict{}  # could be written as: graph = {}
node10 = Node( 10 )
graph[ node.id ] = node10

or even:

graph[ 20 ] = Node( 20 )

if you don't need lots of nodes 'hanging around' outside of the 'list'
(actually a dict) representing the graph.


Then:

> NO1 = 20
> if NO1 not in NODELIST[:].NO  ???

becomes a single line:

the_node_required = graph[ 20 ]

where "20" is the search-criteria.

Does that make sense?


If it does, and when you realise that you'd like to do more with the
graph than retrieve single nodes (and more-importantly, should you want
(or dare) to delve further into the depths of Object-Oriented
Programming) you could declare a second class (graph) containing a
number of "methods". If one of the methods implemented is __contains__()
then you could indeed ask:

if 20 in graph:

ie "is Fred in-class today?"
but just as we would ask "is Fred here?" rather than "is someone
identified by the name 'Fred' here?", it would seem better form to write:

if node( 20 ) in graph:

ie is there a node with the id of 20, somewhere within the graph?


Such might involve sub-classing OrderedDict, UserDict, or even UserList,
from the Collections library in the (provided/"batteries-included")
Python Standard Library: https://docs.python.org/3/library/collections.html

If needed, the extra methods you choose to implement might include such
functionality as connecting nodes 10 and 20 with a path/edge, being able
to traverse edges, and so-on...

Thus, we've covered two categories of class/object: one, a 'data-class'
which contains data about a single node; the other a 'collection-class'
which contains multiple nodes making-up the graph. A useful distinction
and a common related-pair of data-constructs!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Object in List : how?

2022-07-24 Thread dn
On 25/07/2022 12.47, Khairil Sitanggang wrote:
> Regarding your comment : "
> *However, usually object creation and initialization iscombined by allowing
> arguments to the initializer:*" , so which one of the two classes Node1,
> Node2 below is more common in practice? Option 2, I guess.
> Thanks,
> 
> 
> # option 1:
> class Node1:
> def __init__(self, a):
> self.a = a
> self.b = self.calculation()
> 
> def calculation(self):
> r = self.a + 10
> return r
> 
> # option 2:
> class Node2:
> def __init__(self, a, b):
> self.a = a
> self.b = b
> 
> self.b = self.calculation()
> 
> def calculation(self):
> r = self.a + 10
> return r
> 
> nd1 = Node1(10)
> nd2 = Node2(10, 0) # 0 is dummy, will be overwritten by the call to
> calculation()

Let's start with calculation() - even though it is not your specific
question:

Given that "self" makes it into an instance-method, it will have access
to self.b! Accordingly, the intermediate variable "r" and its return
serves no purpose - assuming calculation() is only used to produce a
value for self.b - which would leave:

def calculation( self ):
self.b = self.a + 10

At which point, the method becomes pointless - may as well put its
single line in-line within __init__() - as I say, with above assumptions.


Some languages do expect that every identifier (data-attribute in this
case) be declared (as to type) and probably also initialised with a
value. Some languages, and some Style Guides require that all
data-attributes are declared within the constructor/initialiser.

Python requires neither of these.

Accordingly, if the "b" argument will only ever be a "dummy", there is
absolutely no need for it - indeed one could argue that its presence is
confusing because it gives the impression than it could assume any
value. (see elsewhere in this thread).

So, with assumptions and short of facts, "option 1" seems better (with
the additional consideration regarding calculation(), as above).
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python code: brief

2022-07-26 Thread dn
On 27/07/2022 06.24, KK CHN wrote:
> List ,
> 
> I have come across a difficulty to understand the code in this file.  I am
> unable to understand exactly what the code snippet is doing here.
> 
> https://raw.githubusercontent.com/CODARcode/MDTrAnal/master/lib/codar/oas/MDTrSampler.py
> 
> I am new to this type of scientific computing code snippets and it is coded
> by someone.  Due to a requirement I would like to understand what these
> lines of code will do exactly.  If someone  could explain to me what the
> code snippets do in the code blocks, it will be a great help .


Which lines of code, specifically?
Is it some Python idiom that is problematic, or the code-logic?

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which linux distro is more conducive for learning the Python programming language?

2022-08-03 Thread dn
On 04/08/2022 14.31, Paul Bryan wrote:
> I wouldn't say any particular Linux distribution is appreciably better
> for Python development than another. I would suggest using a version of
> a Linux distribution that supports a recent Python release (e.g. 3.9 or
> 3.10).

+1

As a Python-learner (there's no comment about current programming
expertise), it is unlikely to make any difference which Linux distro is
used.

Answers to such open-ended questions are usually seated in bias - which
in-turn is mostly likely to be the same answer as 'which is the Linux
distro *I* use?
(I've used a number, with Python, over the years)

The better alignment is to match the version of Python with the book or
course you are using as learning-materials. That way, there are unlikely
to be surprises.

There are differences in Python implementations between Linux, Mac, and
Windows. However, I can't think of a book or course which spends any
time discussing them, or having a chapter which demands one or other OpSys.

When you become more experienced two things will happen: firstly you
will start using tools which enable the use of different versions of
Python for different dev.projects; and secondly you will form your own
opinions of "best"!
(it's not difficult to change distro)


PS most of us will qualify for RedHat's Developer program[me] and free
copies of software.
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Which linux distro is more conducive for learning the Python programming language?

2022-08-04 Thread dn
>> PS most of us will qualify for RedHat's Developer program[me] and free
>> copies of software.
> 
> I can download free copies of RHEL 7.x, 8.x, and 9.x :) Just that I
> dunno which RHEL version is better. Is RHEL 9.0 the best out of 7.x,
> 8.x and 9.x?

RedHat is a stable OpSys. Accordingly, it doesn't much matter which
version. The general assumption is that the more recent distribution has
more advanced facilities, eg improved security features in RHEL9.

As another post says, Fedora is closer to the bleeding-edge of Linux
development.

Be aware that there are many methods of adding Python. For example, if
your training is based on the Anaconda [Python] distribution, then it is
irrelevant which version of Python comes with the Linux distro. As
mentioned before, if you advance to developing in [Python] virtual
environments, then each of these could run a different version of
Python. Similarly, using a VM...

The question is relatively minor. More important to 'get going'!
(also mentioned previously: relatively easy to change (Python or distro)
'later'!)
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand nested loops

2022-08-05 Thread dn
On 06/08/2022 10.50, Dan Stromberg wrote:
> On Fri, Aug 5, 2022 at 12:35 AM  wrote:
...

> Of if you don't have (or want) a debugger, you could change it to:
> 
> var = 0
> for i in range(3):
>   print('i is', i)
>   for j in range(-2,-7,-2):
> print('j is', j)
> var += 1
> print(var)
> 
> And note that 3 times 3 is 9.

Combining the above advice and illustration, with several more recent
comments about indentation revealing structure, should the above be
amended to:

indent = ""  # your choice of how many spaces/tabs
...
  print( "i is", i )
...
print( indent + "j is", j )
...
  print( indent + indent, var )  # add sep="" if pernickety
...

Thus, the output matches the code and each complements the other's view
of structure!

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand nested loops

2022-08-05 Thread dn
On 06/08/2022 11.41, avi.e.gr...@gmail.com wrote:
> I wonder if someone is pulling our leg as they are sending from an invalid
> email address of "GB " which is a bit sick.

There are a number of folk who use evidently false email addresses - the
OP's had me amused.

Such 'hiding' is a matter for the List-Admins (thanks for all the work
exerted on our behalf!) and how it fits with the Code-of-Conduct.


> I have trouble imagining ANYONE learning a language like python without
> rapidly being told that python uses indentation instead of various ways to
> detect when a body of text is considered a single composite item.
> 
> And code like their example is also nonsense:
> 
> print(var)
>  print(var)
>  print(var)

Another way to look at that post, and what the author may have meant; is
that the final print(), incorrectly indented in the OP, could have been
written with three different indentations, and thus have three very
different effects (cf that they are all to be used, as-is).
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exclude 'None' from list comprehension of dicts

2022-08-15 Thread dn
On 16/08/2022 00.56, Antoon Pardon wrote:
> Op 5/08/2022 om 07:50 schreef Loris Bennett:
>> Antoon Pardon  writes:
>>
>>> Op 4/08/2022 om 13:51 schreef Loris Bennett:
>>>> Hi,
>>>>
>>>> I am constructing a list of dictionaries via the following list
>>>> comprehension:
>>>>
>>>>     data = [get_job_efficiency_dict(job_id) for job_id in job_ids]
>>>>
>>>> However,
>>>>
>>>>     get_job_efficiency_dict(job_id)
>>>>
>>>> uses 'subprocess.Popen' to run an external program and this can fail.
>>>> In this case, the dict should just be omitted from 'data'.
>>>>
>>>> I can have 'get_job_efficiency_dict' return 'None' and then run
>>>>
>>>>     filtered_data = list(filter(None, data))
>>>>
>>>> but is there a more elegant way?
>>> Just wondering, why don't you return an empty dictionary in case of a
>>> failure?
>>> In that case your list will be all dictionaries and empty ones will
>>> be processed
>>> fast enough.
>> When the list of dictionaries is processed, I would have to check each
>> element to see if it is empty.  That strikes me as being less efficient
>> than filtering out the empty dictionaries in one go, although obviously
>> one would need to benchmark that.
> 
> I may be missing something but why would you have to check each element
> to see if it is empty? What would go wrong if you just treated empty
> dictionaries the same as non-empty directories?

'Truthiness':-

>>> bool( {} )
False
>>> bool( { "a":1 } )
True

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: UTF-8 and latin1

2022-08-17 Thread dn
On 18/08/2022 03.33, Stefan Ram wrote:
> Tobiah  writes:
>> I get data from various sources; client emails, spreadsheets, and
>> data from web applications.  I find that I can do 
>> some_string.decode('latin1')
> 
>   Strings have no "decode" method. ("bytes" objects do.)
> 
>> to get unicode that I can use with xlsxwriter,
>> or put  in the header of a web page to display
>> European characters correctly.
> 
> |You should always use the UTF-8 character encoding. (Remember
> |that this means you also need to save your content as UTF-8.)
> World Wide Web Consortium (W3C) (2014)
> 
>> am using data from the wild.  It's frustrating that I have to play
>> a guessing game to figure out how to use incoming text.   I'm just wondering
> 
>   You can let Python guess the encoding of a file.
> 
> def encoding_of( name ):
> path = pathlib.Path( name )
> for encoding in( "utf_8", "cp1252", "latin_1" ):
> try:
> with path.open( encoding=encoding, errors="strict" )as file:
> text = file.read()
> return encoding
> except UnicodeDecodeError:
> pass
> return None
> 
>> if there are any thoughts.  What if we just globally decided to use utf-8?
>> Could that ever happen?
> 
>   That decisions has been made long ago.

Unfortunately, much of our data was collected long before then - and as
we've discovered, the OP is still living in Python 2 times.

What about if the path "name" (above) is not in utf-8?
eg the OP's Montréal in Latin1, as Montréal.txt or Montréal.rpt
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: install

2022-08-17 Thread dn



On 18/08/2022 08.54, Sherea Washington wrote:
> -- Forwarded message -
> From: Sherea Washington 
> Date: Wed, Aug 17, 2022 at 4:41 PM
> Subject: install
> To: 
> 
> 
> Hi
> 
> I'm trying to install this. I have used all of these options below, but I
> can't anywhere. it keeps looping back to this when I click on the download.
> Please help. cell 843-364-2212
> 
> [image: image.png]


Welcome to the list.

Sadly, no graphics are allowed.

The cell number does not appear to include an international code.

Please review the documentation: 4. Using Python on Windows
https://docs.python.org/3/using/windows.html
and advise if that does not solve the problem.

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Mutating an HTML file with BeautifulSoup

2022-08-19 Thread dn
On 20/08/2022 09.01, Chris Angelico wrote:
> On Sat, 20 Aug 2022 at 05:12, Barry  wrote:
>>
>>
>>
>>> On 19 Aug 2022, at 19:33, Chris Angelico  wrote:
>>>
>>> What's the best way to precisely reconstruct an HTML file after
>>> parsing it with BeautifulSoup?
>>
>> I recall that in bs4 it parses into an object tree and loses the detail of 
>> the input.
>> I recently ported from very old bs to bs4 and hit the same issue.
>> So no it will not output the same as went in.
>>
>> If you can trust the input to be parsed as xml, meaning all the rules of 
>> closing
>> tags have been followed. Then I think you can parse and unparse thru xml to
>> do what you want.
>>
> 
> 
> Yeah, no I can't, this is HTML 4 with a ton of inconsistencies. Oh
> well. Thanks for trying, anyhow.
> 
> So I'm left with a few options:
> 
> 1) Give up on validation, give up on verification, and just run this
> thing on the production site with my fingers crossed
> 2) Instead of doing an intelligent reconstruction, just str.replace()
> one URL with another within the file
> 3) Split the file into lines, find the Nth line (elem.sourceline) and
> str.replace that line only
> 4) Attempt to use elem.sourceline and elem.sourcepos to find the start
> of the tag, manually find the end, and replace one tag with the
> reconstructed form.
> 
> I'm inclined to the first option, honestly. The others just seem like
> hard work, and I became a programmer so I could be lazy...
+1 - but I've noticed that sometimes I have to work quite hard to be
this lazy!


Am assuming that http -> https is not the only 'change' (if it were,
you'd just do that without BS). How many such changes are planned/need
checking? Care to list them?

-- 
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Mutating an HTML file with BeautifulSoup

2022-08-20 Thread dn
On 20/08/2022 12.38, Chris Angelico wrote:
> On Sat, 20 Aug 2022 at 10:19, dn  wrote:
>> On 20/08/2022 09.01, Chris Angelico wrote:
>>> On Sat, 20 Aug 2022 at 05:12, Barry  wrote:
>>>>> On 19 Aug 2022, at 19:33, Chris Angelico  wrote:
>>>>>
>>>>> What's the best way to precisely reconstruct an HTML file after
>>>>> parsing it with BeautifulSoup?
...

>>> well. Thanks for trying, anyhow.
>>>
>>> So I'm left with a few options:
>>>
>>> 1) Give up on validation, give up on verification, and just run this
>>> thing on the production site with my fingers crossed
>>> 2) Instead of doing an intelligent reconstruction, just str.replace()
>>> one URL with another within the file
>>> 3) Split the file into lines, find the Nth line (elem.sourceline) and
>>> str.replace that line only
>>> 4) Attempt to use elem.sourceline and elem.sourcepos to find the start
>>> of the tag, manually find the end, and replace one tag with the
>>> reconstructed form.
>>>
>>> I'm inclined to the first option, honestly. The others just seem like
>>> hard work, and I became a programmer so I could be lazy...
>> +1 - but I've noticed that sometimes I have to work quite hard to be
>> this lazy!
> 
> Yeah, that's very true...
> 
>> Am assuming that http -> https is not the only 'change' (if it were,
>> you'd just do that without BS). How many such changes are planned/need
>> checking? Care to list them?

This project has many of the same 'smells' as a database-harmonisation
effort. Particularly one where 'the previous guy' used to use field-X
for certain data, but his replacement decided that field-Y 'sounded
better' (or some such user-logic). Arrrggg!

If you like head-aches, and users coming to you with ifs-buts-and-maybes
AFTER you've 'done stuff', this is your sort of project!


> Assumption is correct. The changes are more of the form "find all the
> problems, add to the list of fixes, try to minimize the ones that need
> to be done manually". So far, what I have is:

Having taken the trouble to identify this list of improvements and given
the determination to verify each, consider working through one item at a
time, rather than in a single pass. This will enable individual logging
of changes, a manual check of each alteration, and the ability to
choose/tailor the best tool for that specific task.

In fact, depending upon frequency, making the changes manually (and with
improved confidence in the result).

The presence of (or allusion to) the word "some" in this list-items is
'the killer'. Automation doesn't like 'some' (cf "all") unless the
criteria can be clearly and unambiguously defined. Ouch!

(I don't think you need to be told any of this, but hey: dreams are free!)


> 1) A bunch of http -> https, but not all of them - only domains where
> I've confirmed that it's valid

The search-criteria is the list of valid domains, rather than the
"http/https" which is likely the first focus.


> 2) Some absolute to relative conversions:
> https://www.gsarchive.net/whowaswho/index.htm should be referred to as
> /whowaswho/index.htm instead

Similarly, if you have a list of these.


> 3) A few outdated URLs for which we know the replacement, eg
> http://www.cris.com/~oakapple/gasdisc/ to
> http://www.gasdisc.oakapplepress.com/ (this one can't go on
> HTTPS, which is one reason I can't shortcut that)

Again.


> 4) Some internal broken links where the path is wrong - anything that
> resolves to /books/ but can't be found might be better
> rewritten as /html/perf_grps/websites/ if the file can be
> found there

Again.


> 5) Any external link that yields a permanent redirect should, to save
> clientside requests, get replaced by the destination. We have some
> Creative Commons badges that have moved to new URLs.

Do you have these as a list, or are you intending the automated-method
to auto-magically follow the link to determine any need for action?


> And there'll be other fixes to be done too. So it's a bit complicated,
> and no simple solution is really sufficient. At the very very least, I
> *need* to properly parse with BS4; the only question is whether I
> reconstruct from the parse tree, or go back to the raw file and try to
> edit it there.

At least the diffs would give you something to work-from, but it's a bit
like git-diffs claiming a 'change' when the only difference is that my
IDE strips blanks from the ends of code-lines, or some-such silliness.

Which brings me to ask: why "*need* t

Re: Mutating an HTML file with BeautifulSoup

2022-08-20 Thread dn
On 21/08/2022 13.00, Chris Angelico wrote:
> On Sun, 21 Aug 2022 at 09:48, dn  wrote:
>> On 20/08/2022 12.38, Chris Angelico wrote:
>>> On Sat, 20 Aug 2022 at 10:19, dn  wrote:
>>>> On 20/08/2022 09.01, Chris Angelico wrote:
>>>>> On Sat, 20 Aug 2022 at 05:12, Barry  wrote:
>>>>>>> On 19 Aug 2022, at 19:33, Chris Angelico  wrote:

>>>>> So I'm left with a few options:
>>>>>
>>>>> 1) Give up on validation, give up on verification, and just run this
>>>>> thing on the production site with my fingers crossed
>>>>> 2) Instead of doing an intelligent reconstruction, just str.replace()
>>>>> one URL with another within the file
>>>>> 3) Split the file into lines, find the Nth line (elem.sourceline) and
>>>>> str.replace that line only
>>>>> 4) Attempt to use elem.sourceline and elem.sourcepos to find the start
>>>>> of the tag, manually find the end, and replace one tag with the
>>>>> reconstructed form.
>>>>>
>>>>> I'm inclined to the first option, honestly. The others just seem like
>>>>> hard work, and I became a programmer so I could be lazy...
>>>> +1 - but I've noticed that sometimes I have to work quite hard to be
>>>> this lazy!
>>>
>>> Yeah, that's very true...
>>>
>>>> Am assuming that http -> https is not the only 'change' (if it were,
>>>> you'd just do that without BS). How many such changes are planned/need
>>>> checking? Care to list them?
>>
>> This project has many of the same 'smells' as a database-harmonisation
>> effort. Particularly one where 'the previous guy' used to use field-X
>> for certain data, but his replacement decided that field-Y 'sounded
>> better' (or some such user-logic). Arrrggg!
>>
>> If you like head-aches, and users coming to you with ifs-buts-and-maybes
>> AFTER you've 'done stuff', this is your sort of project!
> 
> Well, I don't like headaches, but I do appreciate what the G&S Archive
> has given me over the years, so I'm taking this on as a means of
> giving back to the community.

This point will be picked-up in the conclusion. NB in the same way that
you want to 'give back', so also do others - even if in minor ways or
'when-relevant'!


>>> Assumption is correct. The changes are more of the form "find all the
>>> problems, add to the list of fixes, try to minimize the ones that need
>>> to be done manually". So far, what I have is:
>>
>> Having taken the trouble to identify this list of improvements and given
>> the determination to verify each, consider working through one item at a
>> time, rather than in a single pass. This will enable individual logging
>> of changes, a manual check of each alteration, and the ability to
>> choose/tailor the best tool for that specific task.
>>
>> In fact, depending upon frequency, making the changes manually (and with
>> improved confidence in the result).
> 
> Unfortunately the frequency is very high.

Screechingly so? Like you're singing Three Little Maids?


>> The presence of (or allusion to) the word "some" in this list-items is
>> 'the killer'. Automation doesn't like 'some' (cf "all") unless the
>> criteria can be clearly and unambiguously defined. Ouch!
>>
>> (I don't think you need to be told any of this, but hey: dreams are free!)
> 
> Right; the criteria are quite well defined, but I omitted the details
> for brevity.
> 
>>> 1) A bunch of http -> https, but not all of them - only domains where
>>> I've confirmed that it's valid
>>
>> The search-criteria is the list of valid domains, rather than the
>> "http/https" which is likely the first focus.
> 
> Yeah. I do a first pass to enumerate all domains that are ever linked
> to with http:// URLs, and then I have a script that goes through and
> checks to see if they redirect me to the same URL on the other
> protocol, or other ways of checking. So yes, the list of valid domains
> is part of the program's effective input.

Wow! Having got that far, you have achieved data-validity. Is there a
need to perform a before-after check or diff?

Perhaps start making the one-for-one replacements without further
anxiety. As long as there's no silly-mistake, eg failing to remove an
opening or closing angle-bracket; isn't that about all the checking needed?
(for thi

Re: How to make a variable's late binding crosses the module boundary?

2022-08-29 Thread dn
On 30/08/2022 06.45, Peter J. Holzer wrote:

> The module is imported but it isn't bound to any name in the current
> (global) namespace (obviously there must be some variable bound to it, but
> that's probably a local variable in the importer and it isn't called
> `x`). Then the object bound to the name `y` in the loaed module is bound
> to the name `y` in the current namespace.


Correct!

Build module.py as:
***
CONSTANT = 1

def func():
pass
***

then in the terminal:
***
Python 3.9.13 (main, May 18 2022, 00:00:00)
[GCC 11.3.1 20220421 (Red Hat 11.3.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from module import func as f
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': , '__spec__':
None, '__annotations__': {}, '__builtins__': , 'f': }
>>> f

>>> f.CONSTANT
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'function' object has no attribute 'CONSTANT'
>>> module.CONSTANT
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'module' is not defined

# no mention of module and no access to CONSTANT

>>> import module as m
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': , '__spec__':
None, '__annotations__': {}, '__builtins__': , 'f': , 'm': }
>>> m

>>> m.func

>>> m.CONSTANT
1
>>> module
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'module' is not defined

# name module is bound as m, and not available as module

>>> import module
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': , '__spec__':
None, '__annotations__': {}, '__builtins__': , 'f': , 'm': , 'module':
}
>>> module.func

>>> module.CONSTANT
1
>>> module


# now it is available
# also notice how the function (func) now has three
'names'/access-methods but all lead to the same location
***

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to make a variable's late binding crosses the module boundary?

2022-08-30 Thread dn
On 31/08/2022 05.26, Schachner, Joseph (US) wrote:
> The way we do this, is in main.py, call a "globalizer" function in each other 
> file:
> 
> # call globalizers to get shortcuts as global variables
> funcs.globalizer(interface, variable_dict)
> util.globalizer(interface, variable_dict)
> sd.globalizer(interface, variable_dict)
> tests.globalizer(interface, variable_dict)
> ut.globalizer(interface, variable_dict)
> 
> Obviously, you may not need a shared interface in which case you can just 
> pass the variable dictionary.
> 
> In each file, you have a function:
> def globalizer(interface, variables_dict):
> # create global variables for this .py file for shared interface and the 
> variables
> 
> 
> This works well, making sure separate python files shared exactly the same 
> things we want to be global.
> 
>  Joseph S.
> 
> Teledyne Confidential; Commercially Sensitive Business Data
> 
> -Original Message-
> From: Stefan Ram  
> Sent: Tuesday, August 30, 2022 1:09 AM
> To: python-list@python.org
> Subject: Re: How to make a variable's late binding crosses the module 
> boundary?
> 
> dn  writes:
>> Build module.py as:
>> ***
>> CONSTANT = 1
> 
>> def func():
>>pass
>> ***
> 
>> then in the terminal:
>> ***
>> Python 3.9.13 (main, May 18 2022, 00:00:00) [GCC 11.3.1 20220421 (Red 
>> Hat 11.3.1-2)] on linux Type "help", "copyright", "credits" or 
>> "license" for more information.
>>>>> from module import func as f
> 
>   In CPython one then can also:
> 
> print( f.__globals__[ "CONSTANT" ])
> import sys
> module = sys.modules[ f.__globals__[ "__name__" ]] print( module.CONSTANT ) 
> CONSTANT = module.CONSTANT print( CONSTANT )


The conversation seems to be wandering some way from the OP. Whereas
both of these answers are clever (and I assume work), the question
becomes: why would you want to do this? (especially as it looks ugly and
'smells' a bit convoluted). An example use-case from your experience?


Delving into the list-archive, to get back to the OP: the first message
in the thread quotes another message that's (apparently) not present.

However, in there somewhere is:

> from test import *

So, the elephant-in-the-room has always been a very stinky 'code-smell'
- which pretty much every text or web-tutorial will say is a bad idea.

Why is a bad idea?
Why is it there then?
When to use it?
[Socratic questioning]

Same question, but the other way around: why has Python been equipped
with modules, classes, functions, etc? To quote The Zen of Python:
"Namespaces are one honking great idea -- let's do more of those!".
Programming paradigms and architectural principles all contain reference
and recommendation to independent code-units, coupling and cohesion,
boundary crossing and interfaces (etc). Python doesn't enact a formal
interface construct (thank you great, high, Python, gods!), but that
doesn't remove the issues behind them (as the OP-code demonstrates).
Instead it requires a Python-idiomatic approach.

Should the question be: "how to I smash two namespaces into one and have
it work 'my way'?", or should the question become "how does Python
enable passing/retention of values between namespaces?".

NB The OP likely reduced the 'problem' to 'minimum-code' for the benefit
of the list, but what is the motivation behind it? Why would one want to
be able to do this? Rationale? Use-case?

Enquiring minds and all that...
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to make a variable's late binding crosses the module boundary?

2022-08-31 Thread dn
On 31/08/2022 19.38, Antoon Pardon wrote:
> 
> 
> Op 30/08/2022 om 23:52 schreef dn:
>> The conversation seems to be wandering some way from the OP. Whereas
>> both of these answers are clever (and I assume work), the question
>> becomes: why would you want to do this? (especially as it looks ugly and
>> 'smells' a bit convoluted). An example use-case from your experience?
>>
>>
>> Delving into the list-archive, to get back to the OP: the first message
>> in the thread quotes another message that's (apparently) not present.
>>
>> However, in there somewhere is:
>>
>>> from test import *
>> So, the elephant-in-the-room has always been a very stinky 'code-smell'
>> - which pretty much every text or web-tutorial will say is a bad idea.
> 
> No that is a red herring. If for some reason a variable in a module has
> to be (re)set after import time, it doesn't matter whether someone uses
> 
>     from module import *
> 
> or
> 
>     from module import resetable_variable
> 
> in both cases the module that did the import will not notice the change
> in the original module.
> 
> focussing on the code smell, is leading the attention away from the
> problem.


Are you the OP?

The behavior has been shown to be exactly that which is (should be)
expected.

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about learning Python

2022-09-07 Thread dn
On 08/09/2022 07.15, Chris Angelico wrote:
> On Thu, 8 Sept 2022 at 05:09, Grant Edwards  wrote:
>>
>> On 2022-09-07, Chris Angelico  wrote:
>>> On Thu, 8 Sept 2022 at 04:54, Grant Edwards  
>>> wrote:
>>>
>>>> If you're a beginning programmer, then IMO learning C first is
>>>> probably detrimental. [...]
>>>
>>> Not as detrimental as starting with BASIC, and then moving on to x86
>>> assembly language, and trying to massage the two together using CALL
>>> ABSOLUTE in order to get mouse input in your GW-BASIC programs.
>>
>> Ah the "good old days".
>>
> 
> Indeed. The 1990s gave me all manner of skills, including the
> aforementioned mouse control in a BASIC program, writing a
> Terminate-and-Stay-Resident program that hooks an interrupt, tricks
> for *not* writing a TSR and still acting like one, building GUIs using
> pixel precision, building GUIs using pixel precision but fully
> automatically, using HTML tables to create layouts oh, yes, so
> many skills... To anyone suffering from https://xkcd.com/1479/ right
> now, I can assure you, quite a lot of that knowledge DOES eventually
> become obsolete when better methods come along. It just sometimes
> takes a decade or more.
> 
> (And then occasionally it still haunts you. I'm finding table-based
> layouts in a site that I now have to manage. Eventually I'll fix it
> all, eventually)

OP: Python!

Python has become one of the most popular first-languages to use in
universities (etc). On-the-ground this varies by country, even by
province/state. However, starting at a higher-level is recommendable -
and should the learner decide that 'this computer stuff is not for me'
(XKCD not withstanding) then the cost of effort-expended will be less.
Also, there are are plenty of coders 'out there' who don't seem to have
learned, or even need, the detail one acquires using a lower-level
language. (no further comment on that!)


TSRs? Now that was an ugly period of history! (trying to make a
single-process operating system do multi-processing - only to find that
many program[me]s assumed they had full use and undisputed control of
the computer. Happy days...)

History has its value. Talking to a group the other day, showed how
IT-skills from patterns (eg Factory, Strategy, Decorator) and paradigms
(eg Modular Programming, Structured Programming) through to
Architectural Principles (eg SOLID) and project management approaches
(eg Waterfall, Agile, SCRUM) all descend from hard-won knowledge and
sometimes bitter-experience. Chunks of which pre-date Dartmouth BASIC,
PCs, mini-computers, and 'family'/standardised-hardware operating systems!

On the other hand, one can start too 'high' or too 'modern'. Like the
person enthusing about MSFT's and AWS' programming AIs, thinking that
such tools will replace programmers (one of the aims of the COBOL
language back in the 1960s). His short-form description spoke volumes:
'it saves anyone from having to look-up Stack Overflow any more' - a
'blind' cut-and-paste prospect that saves the 'author' from the
difficulties of 'learning stuff'; until it is time to, um, learn-stuff -
to know why one needs to learn-stuff BEFORE taking from SO/AI.

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Virtual PUG-meeting: An applied introduction to Finite State Machines

2022-09-13 Thread dn
An applied introduction to Finite State Machines
0730 UTC, Wed 21 Sep 2022

The basics of Finite State Machines and what they are good for. How to
use FSM for solving optimization problems.

- A simple traffic jam
- A bigger traffic jam
- A sudoku

After this lecture there won't be any discrete optimization problem you
won't be able to solve.

Dr. Bjorn Madsen solves optimization problems using Python, for DoD,
LEGO, Coca Cola, Airbus and many other companies.


These meetups have two sessions. At least one is aimed at a beginner
level - in either Python or FSMs.

Sign-up and more details from https://www.meetup.com/nzpug-auckland/
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Virtual PUG-meeting: An applied introduction to Finite State Machines

2022-09-13 Thread dn
On 14/09/2022 10.18, Sam Ezeh wrote:
> That seems interesting.
> 
> Is this hosted online? And are there any suggested reading materials for
> those who might not be able to attend?


Yes there are - if you'd like to follow the link (below), the published
meeting-details include references.

One of my colleagues on the PUG Leadership Team has organised the
speaker, but I recall mention of "notebooks", etc. So, there may be
further resources which will be made-available during/after the talk
itself...

If you are a 'late-owl' in the (US) Pacific Time-Zone, you may like to
join us 'live'. Sadly, the timings rapidly become anti-social for more
easterly time-zones in the Americas.

If you are anywhere in the rest of the world, you will find that the
meeting falls sometime during your working-day, through to Europeans
at-breakfast!

You'll be most welcome!


> Kind regards,
> Sam Ezeh
> 
> On Tue, 13 Sept 2022 at 22:53, dn  <mailto:pythonl...@danceswithmice.info>> wrote:
> 
> An applied introduction to Finite State Machines
> 0730 UTC, Wed 21 Sep 2022
> 
> The basics of Finite State Machines and what they are good for. How to
> use FSM for solving optimization problems.
> 
> - A simple traffic jam
> - A bigger traffic jam
> - A sudoku
> 
> After this lecture there won't be any discrete optimization problem you
> won't be able to solve.
> 
> Dr. Bjorn Madsen solves optimization problems using Python, for DoD,
> LEGO, Coca Cola, Airbus and many other companies.
> 
> 
> These meetups have two sessions. At least one is aimed at a beginner
> level - in either Python or FSMs.
> 
> Sign-up and more details from https://www.meetup.com/nzpug-auckland/
> <https://www.meetup.com/nzpug-auckland/>
> -- 
> Regards,
> =dn
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> <https://mail.python.org/mailman/listinfo/python-list>
> 


-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python is not working on my desktop

2022-09-19 Thread dn
Regret to advise that many members will not click on links, and
particularly not when the link is the only message-content. (flagged as
likely spam-email!)

Please describe the problem, including an explanation of from where the
Python interpreter was downloaded, which OpSys is in-use, what commands
were issued at the desktop, and copy-paste any results.

Does the Python documentation (including the specific page covering
installing Python on MS-Windows) help with the above?

List-members are volunteers and not $paid. Please help us to help you!
Also, please be advised that there is a Python-Tutor Discussion List
which handles beginner and learner conversations.


On 19/09/2022 23.43, python 3.0 is not working wrote:
> 
> 
> 
> 
>Sent from [1]Mail for Windows

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


NZPUG: Smart Iterator Challenge

2022-09-22 Thread dn
A week-by-week Challenge series.
A new venture by the Auckland Branch of the New Zealand Python Users'
Group (AuckPUG)

Challenge-week 1: Implementing a monolithic solution, starts today!

All welcome!
- will suit Python-Apprentices ready to move-on from 'the basics' and
Python-Journeymen
- will welcome participation and coaching-contributions from
Python-Masters, with a special Challenge to be issued at that level

Kiwi accent optional (most people are no-good at it anyway).

With special thanks to our own Leam Hall, for feedback and advice
- that said, all errors and omissions are mine.


To avoid OT traffic on-list, please find all details, and file any
follow-up questions through the Meetup-site:
https://www.meetup.com/nzpug-auckland/ (or email myself directly).


Are you up for a challenge?
Regards =dn (for Pete and DJ)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Implementation of an lru_cache() decorator that ignores the first argument

2022-09-28 Thread dn
On 29/09/2022 07.22, Robert Latest via Python-list wrote:
...

> This is what I came up with. I'm quite happy with it so far.  Question: Am I
> being too clever? is it too complicated? Am I overlooking something that will
> come back and bite me later? Thanks for any comments!

Thank you for the chuckle: "Yes", you are clever; and "yes", this is
likely a bit too clever (IMHO).

The impression is that LRU will put something more-concrete, 'in front
of' SQLAlchemy - which is more abstract, and which is in-turn 'in front
of' the RDBMS (which is concrete...). Is this the code-smell making
one's nose suspicious?

The criticism is of SQLAlchemy. If the problem can't be solved with that
tool, perhaps it is not the right-tool-for-the-job...

Bias: With decades of SQL/RDBMS experience, it is easy to say, "drop the
tool".

+1 @Chris: depending upon how many transactions-between, it seems likely
find that the RDBMS will cache sufficiently, as SOP.

YMMV, ie there's only one way to find-out!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing 'Scripts/*.exe'

2022-10-01 Thread dn
On 02/10/2022 04.50, Gisle Vanem via Python-list wrote:
> Hello list.
> 
> I'm moved my old Python27 installation from
>   f:\ProgramFiler\Python27  ( == 'ProgramFiles')
> to
>   f:\gv\Python27
> 
> and now many 'scripts/*.exe' program fails
> to start since the old path to 'Python.exe'
> is wrong.
> 
> E.g. 'Scripts/pip2.exe' has the path
> "f:\programfiler\python27\python.exe" hard-coded
> inside it.
> 
> Is there a easy way to fix this w/o re-installing this
> old Python?

Yes, by putting a symbolic-link at the old 'programfiler' location which
points to the new 'gv' installation.

Regret that not using MS-Windows, can't give exact instruction. Please
review:

Symbolic link: https://www.computerhope.com/jargon/s/symblink.htm
Symbolic Links:
https://learn.microsoft.com/en-us/windows/win32/fileio/symbolic-links

-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing 'Scripts/*.exe'

2022-10-03 Thread dn
On 03/10/2022 20.48, Gisle Vanem via Python-list wrote:
> dn wrote:
> 
>>> E.g. 'Scripts/pip2.exe' has the path
>>> "f:\programfiler\python27\python.exe" hard-coded
>>> inside it.
>>>
>>> Is there a easy way to fix this w/o re-installing this
>>> old Python?
>>
>> Yes, by putting a symbolic-link at the old 'programfiler' location which
>> points to the new 'gv' installation.
> 
> I'm suspicious about sym-links.

OT: I'm sufficiently intrigued to ask "why?" - or are you only talking
of the MS-Windows implementation?


> Instead for 'pip' I just did a 'py -2 get-ip.py' which seems
> to have fixed it. The newly generated 'f:\gv\Python27\Scripts\pip2.exe'
> seems to work fine; the list from 'pip2.7.exe list' is correct.

As long as things are working again, we're all happy!
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Changing 'Scripts/*.exe'

2022-10-03 Thread dn
On 04/10/2022 14.10, Meredith Montgomery wrote:
> r...@zedat.fu-berlin.de (Stefan Ram) writes:
> 
>> Meredith Montgomery  writes:
>>> Wouldn't it be great if it were portable by default?
>>
>>   I think under Windows there is a division of software
>>   suggested by Microsoft, a division of software into
>>   executable code and data (data may change in time).
>>
>>   The executable code is supposed to rest under
>>   "C:\Program Files" the contents of which cannot be
>>   modified by user processes easily. Program configuration
>>   can be stored below "AppData" in the user directory.
>>   It is supposed to be more secure when executable code
>>   cannot be modified easily by user processes.
>>
>>   So far, Python has decided to ignore this and install
>>   everything under AppData as I understand it. So one 
>>   gets neither the security of "Program Files" nor the
>>   possibility to move it to another directory easily.
> 
> Interesting.  I like portable things.  You copy from one place to

At which point we mention that this is exactly how Linux works. A 'zen'
of Linux applications and utilities has always been: "do one thing, and
do it well".

Then directory/file access controls aim to keep users in 'userland' and
away from 'system', and for folk who want more there are security
features such as apparmor which limit the types of usage of files (as
well as resisting external threats).

Extending this a little further: such philosophy enables Linux users to
more-easily install (and run) multiple versions of Python*, Firefox,
Chromium, etc, without resorting to containers or VMs.

* eg v2 and v3 installed concurrently, to possibly suit OP

> another and it just runs.  As it should.  Things should be simple.

+1
-- 
Regards,
=dn
-- 
https://mail.python.org/mailman/listinfo/python-list


From NZPUG: Smart Iterator Challenge

2022-10-06 Thread dn

A week-by-week Challenge series.
A new venture by the Auckland Branch of the New Zealand Python Users'
Group (AuckPUG)

Challenge-week 2: Modular programming - starts today
Please note: all times are NZDT, ie UTC+13


All welcome!

- will suit Python-Apprentices ready to move-on from 'the basics' and
Python-Journeymen
- will welcome participation and coaching-contributions from
Python-Masters, with a special Challenge to be issued at that level

Kiwi accent optional (most people are no-good at it anyway).


With special thanks to our own Leam Hall, for feedback and advice
- that said, all errors and omissions are mine.


To avoid OT traffic on-list, please find all details, and file any
follow-up questions through the Meetup-site:
https://www.meetup.com/nzpug-auckland/events/288813698/ (or email myself 
directly).



Are you up for a challenge?
Regards =dn (for Pete and DJ)

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


Re: for -- else: what was the motivation?

2022-10-09 Thread dn
item ):
if not_this_one(item):
continue
if neither_this_one(item):
continue
if cant_continue(item):
raise CustomBreakException  # was break
if oopsie():
raise SomeError()


It is now easier to understand 'the happy line', ie the thinking of the 
original-coder, and the 'small print' has been relegated to such and can 
be cheerfully disregarded.


Whereas, if 'exceptional circumstances' is the reason one is inspecting 
the code in the first-place, then it also helps to have separated-out 
the ifs-buts-and-maybes, and into a structure which can be as closely 
(and exhaustively) tested, as may be required.



In some ways, (IMHO) there are reasons to feel disquiet over this style 
of coding. Learning "Modular Programming", and slightly-later 
"Structured Programming", when they were still new (?fresh, ?exciting), 
we were inculcated with the 'one way in, one way out' 
philosophy-of-correctness. This applied to "blocks" of code (per 
"module"), as well as formal units, eg functions.


Accordingly, am slightly unnerved by seeing Exceptions being used to 
'jump out' of interior/nested blocks, rather than using the 
return-mechanism (taking their turn like all the good little boys and 
girls). That said, it makes for tidier code - so I'll stop muttering 
into my (grey) beard ...



The alternative, assuming the 'errors and omissions' function is a 
possible tactic(!), would be to return a boolean, eg


def is_clean_data( item )->bool:
is_verified = False
if ...
...
return is_verified

- thus the do-stuff calls will become a 'successful' if-then 'suite'.


There is more code to write/read - and the toy-example lends itself to 
such a tactic. In other situations, perhaps some refactoring or 
pre-processing, even a decorator, might remove (or reduce) the need for 
so much checking within the loop/block.



When to use one or the other approach?

We could hide behind some 'mystery', and say "I just know from 
experience", but that smacks of a secret coin-toss (human 'gut feelings' 
not being particularly indicative of success). So, here's a stab at it 
which harks back to the learn/use 'COBOL or FORTRAN' [argument] days:


If the purpose/considerations of the for-loop (block), are:-
- data-related: check-first
(and thus consider extract and/or invert to promote readability)
- logic/algorithmic implementation, take 'the happy line' first
(and deal with the exceptions ("small print") later)


Worthy of consideration, is that Python is (still) fast-developing. The 
switch-case construct of v3.10, and protocols and beefed-up descriptors 
(?interfaces?) could have quite an impact on such thinking, and in the 
relatively near-future...



* back in the ?bad old days when testing was something that was (only) 
done AFTER coding was complete, ie ego-driven development. The 
traditional response to the question: "are you coming to 
lunch/dinner/supper/break/the party/bed/...?" was "in a moment - 
[surely?] there's only one more bug"!



I've been 'dipping into' Martin Fowler's "Refactoring", 2e, Pearson, 
2019; but don't have it with me to point to useful references. What I do 
have to-hand, because it has just arrived, is Mariano Anaya's "Clean 
Code in Python", (also 2e), Packt, 2020* - although I didn't see its 
previous edition, and have read nothing beyond the Contents(!) to-date; 
it talks of "Design by Contract", "Defensive Programming", "Separation 
of Concerns" indicating it may have thinking to offer.


* the reviewer was Tarek Ziadé, author of "Expert Python", which is 
worth reading - as are his other works (in English and in French)

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-09 Thread dn




On 10/10/2022 13.47, MRAB wrote:

On 2022-10-10 00:40, dn wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
 wrote:


"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did
for others.

Enquiring minds want to know... Played Duck, duck, go on this: zero hits
amongst a pile of similar phrases - turns-out there's an algorithm with
a similar name, but not related, and an electronics approach (way too
'low' a level for translation to us though).

Tried prefixing with "program" but no such advice to programmers or
program[me] designers.

Tried prefixing with "python", but equal lack of joy.

Would OP please quote source?


[snip]
After a few minutes searching I found this:

https://docs.typo3.org/m/typo3/reference-coreapi/9.5/en-us/CodingGuidelines/CglPhp/PhpFileFormatting/PhpSyntaxFormatting.html

"""It is recommended to create conditions so that the shortest block of 
code goes first."""


Thanks for this!

So, a Domain-Specific Language for a CMS.

If this is only reference, then hardly a tenet of ComSc thinking or 
programming-languages!



For fun: Typo3 is based on PHP. Advice (apparently) not replicated in 
PHP-docs (if, else, etc).

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


[Meeting] Problem-solving, perspectives, programming, and presentation, 19Oct

2022-10-11 Thread dn
With all that "p"-alliteration, it must be a Pppresentation with the 
virtual-Auckland branch of NZPUG!


Wed 19 Oct,
1800 for 1830 ~ 2030 NZDT
0500, 0530, and 0730 UTC+13 resp
by web-conference

Nathan Smith had an 'itch' caused by a problem related to the game of 
Scrabble. Solving a problem with Python, from start-to-finish. A journey 
of challenges, a lesson of not giving in and hopefully a good story all 
round. Featuring, steps forwards, brick-walls, data-structures related 
to words, dictionaries (of both definitions) and Directed Acyclic Word 
Graphs (DAWG - application of DAG graph/network structures). Plus, a 
blind person's perspective on coding through the project, presenting 
overview information on the way a blind person may access code and what 
similarities or differences may crop up.



Creative Coding With Python: Learn how to code simple visuals in Python 
for games, innovative stats, simulations and generative art using a 
flavour of the processing library. This can be incredibly useful for 
teaching programming, visualising concepts and sharpening thinking 
skills. This list's own Abdur-Rahman Janhangeer organises the Python 
Mauritius User Group and FlaskCon* (amongst many other contributions to 
the Python Community including graphic presentation libraries)

* Flask is a very popular web framework


More info about the group, and to RSVP (and thus receive the meeting 
URL) see Meetup group at: 
https://www.meetup.com/nzpug-auckland/events/njdjssydcnbzb/



Regards =dn (Pete and DJ)
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-11 Thread dn

On 10/10/2022 16.19, avi.e.gr...@gmail.com wrote:

I won't reply to everything Dave says and especially not the parts I fully 
agree with.

I think in many situations in life there is no ONE way to do things so most 
advice is heuristic at best and many exceptions may exist depending on your 
chosen approach. As such, I do not really think in PYTHON when writing code but 
an amalgam of many languages with all kinds of ways of doing things and then 
zoom in on how to do it in the current language be it Python or R or JavaScript 
and so on. Yes, I am in some sense focused but also open, just as in Human 
languages I may mostly be thinking in English but also sometimes see words and 
phrases pop into my mind from other languages that mean about the same thing 
and then filter it out to focus on whichever language I am supposed to be using 
at the time.


Given that we can both remember programming last-century, this 
surprised. (or may have misunderstood!)



If we think, in German, of some parting words for an older friend 
departing on a long trip, and translate word-for-word into English we 
might come out with: "May God pickle you".


There is a second step, which is to examine the 'solution' in terms of 
its expression (how the communication will be received), and thus the 
more-correct English expression would be: "May God preserve you"!


The two p-words are sufficiently-similar in meaning to appear 
synonymous, when examined in-isolation. However, that first expression 
would at least bemuse an (only) English-speaker, and quite possibly confuse!



One of the problems which 'appeared' when programmers were first given 
direct-access to the computer, eg time-sharing mini-computers; and which 
persists to this day, is "the rush to code". Indeed there are (still) 
some 'managers' who think that unless a programmer is writing code (s)he 
isn't 'working' - but we're only interested in our own behavior.


Accordingly, "design" and "development".

Back-when, some lecturers insisted that we first create a flow-chart or 
a pseudo-code solution for an assignment - BEFORE we coded in COBOL, 
FORTRAN, or whatever. In many ways, because we were learning the 
programming-language, most felt it very difficult to draw a flow-chart 
that didn't merely look like FORTRAN.
(to make that worse (for ourselves) I suspect many of us performed the 
latter first, and then ...) Many of us will have felt this some sort of 
academic-exercise or even 'a nuisance', but there was 'method in their 
madness'!



Relating back to the comment (above): when *designing* a 
solution/flow-charting/pseudo-code, an "amalgam" of programming 
constructs and human-language expressions will indeed add richness, 
opportunity, and alternatives. All serving to amplify analytic and 
design skill.


Conversely, when *coding*, the skill comes from employing the (specific, 
programming) language to best advantage. At which time, one's 
JS-knowledge is almost irrelevant, because the task is to convert a 
design outline or planned-solution, into Python.

(idiomatic, pythonic, efficient, readable, ...)
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: flattening lists

2022-10-11 Thread dn

On 12/10/2022 08.32, SquidBits _ wrote:

Does anyone else think there should be a flatten () function, which just turns 
a multi-dimensional list into a one-dimensional list in the order it's in. e.g.

[[1,2,3],[4,5,6,7],[8,9]] becomes [1,2,3,4,5,6,7,8,9].

I have had to flatten lists quite a few times and it's quite tedious to type 
out. It feels like this should be something built in to python, anyone else 
think this way?



There is a flatten function!

First though, are we ONLY talking about 'flattening' a 2D list (per 
example, above) or might the requirements extend to multiple-dimensions? 
The solutions vary accordingly!



Two-dimensions:
(don't think this method previously-mentioned, but very readable)

>>> l = [[1,2,3],[4,5,6,7],[8,9]]
>>> flattened = list()
>>> for element in l:
... flattened += element
...
>>> flattened
[1, 2, 3, 4, 5, 6, 7, 8, 9]

(NB if "l" were three-dimensional, "flattened" would become 2D)


Multi-dimensional:
Reach for itertools:
(https://docs.python.org/3/library/itertools.html#itertools.chain)

>>> import itertools as it
>>> iter_flattened = it.chain( *l )
>>> list( iter_flattened )
[1, 2, 3, 4, 5, 6, 7, 8, 9]


Wrt "I have had to flatten lists quite a few times and it's quite 
tedious to type out.", isn't this a "code-smell"?


Certainly motivation to generalise and write a solution as a function. 
Do it once, and do it right!


Hence advice elsewhere to build a list-processing utility-library.

On the other hand, has it already been done for us?


An exercise for the reader:
is reaching for itertools 'over-kill' in 2D?
- speed-comparison between loading the itertools library and then 
employing the speedy method, or using a (built-in) for-loop at 
Python-speed with no import-overhead?
(results will vary significantly according to len( l ), but do they 
remain consistently in-favor or one method or the other?)

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help, PyCharm fails to recognize my tab setting...See attached picture of the code.

2022-10-11 Thread dn

On 11/10/2022 10.48, Kevin M. Wilson via Python-list wrote:

C:\Users\kevin\PycharmProjects\Myfuturevalue\venv\Scripts\python.exe 
C:\Users\kevin\PycharmProjects\Myfuturevalue\FutureValueCal.py   File 
"C:\Users\kevin\PycharmProjects\Myfuturevalue\FutureValueCal.py", line 31    elif 
(years > 50.0) or (years < 1.0) :    ^IndentationError: expected an indented block after 
'if' statement on line 29
Process finished with exit code 1


Indentation depends upon what went before, as well as what is being 
indented 'right now'.


As you can see from the reproduction of the OP (above), any comment on 
formatting would be a guess.


Please copy-paste the entire block of the if-statement and its nested 
suites...

(this list will not pass-along images)
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: What to use for finding as many syntax errors as possible.

2022-10-12 Thread dn
he first error on line 25
Unresolved reference 'fyibonacci_number':28
# ahah! Apparently trying to use an identifier before declaring/defining
# in reality, just another typo
# that said, I created the issue by inserting the "y"
# if I'd mistyped the entire identifier upon first-entry,
# the IDE's code-completion facility would have given choices and 'saved me'

NB the content displayed in the Problems Tool Window is dynamic. 
Accordingly, because of the way Python works, if one 'fixes' errors in 
line-number sequence, closing an error 'higher up' may well cause 
a(nother) error 'lower down' to disappear - thus reducing the number of 
spurious errors one is likely to encounter as a limitation of the 
automated code-evaluation!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: for -- else: what was the motivation?

2022-10-12 Thread dn




On 11/10/2022 02.13, Grant Edwards wrote:

On 2022-10-10, Chris Angelico  wrote:

On Mon, 10 Oct 2022 at 11:52, MRAB  wrote:


On 2022-10-10 00:40, dn wrote:

On Sun, 9 Oct 2022 at 15:39, Axy via Python-list
 wrote:


"shortest block first"


Have never heard this advice before. Kind-of rankled with me, as it did
for others.


I've followed that advice for several decades. I find it much easier
to read code that's organized that way -- particularly when the
difference in block sizes is large (e.g. the first block is one line,
and the second is a a hundred).


Makes sense. Keep the 'cause' and 'effect' close together. In other 
words, making it easy to look 'up' from one of the 'suites' to see the 
if-statement/condition which directs that logic-branch.



Contrarily, (see @Karsten, earlier) the preference to bundle the 
"hundred" into one or more functions, rather than present as a 'wall of 
text'. Added advantage: well-chosen function names(!) will remind the 
reader of the purposes(!) of the "hundred".


Once both suites are short[ened], visibility improves (readability), and 
the above contention goes-away. Thus the sense of the condition becomes 
the most worthy consideration.


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: What might suddenly provoke this poplib error?

2022-10-13 Thread dn

On 14/10/2022 01.47, Chris Green wrote:

I have a short python3 program that collects E-Mails from a 'catchall'
mailbox, sends the few that might be interesting to me and dumps the
rest.

It has suddenly (after working for some years) started throwing the
following:-

 Traceback (most recent call last):
   File "/home/chris/.mutt/bin/getCatchall.py", line 83, in 
 pop3.pass_('brzmilla')
   File "/usr/lib/python3.10/poplib.py", line 218, in pass_
 return self._shortcmd('PASS %s' % pswd)
   File "/usr/lib/python3.10/poplib.py", line 181, in _shortcmd
 return self._getresp()
   File "/usr/lib/python3.10/poplib.py", line 157, in _getresp
 raise error_proto(resp)
 poplib.error_proto: b'-ERR internal server error'


The section of code throwing the error is as follows:-

 #
 #
 # Connect to the POP3 server, get message count, exit if no messages
 #
 for t in range(10): # retry 10 times
 try:
 pop3 = poplib.POP3_SSL('mail3.gridhost.co.uk',timeout=300)
 break
 except TimeoutError:
 if t == 9:
 log.err("Timed out 10 times, giving up")
 exit(1)
 else:
 log.warn("Timed out, try " + str(t))

 pop3.user('catch...@isbd.net')
 pop3.pass_('brzmilla')
 numMessages = len(pop3.list()[1])
 if (numMessages == 0):
 break


It seems to be saying that the POP3 server has a problem, if so there's not
much I can do about it as it's my hosting provider's mail server.  Is it
really saying the server has a problem?



There's a range of possibilities here. The first question to ask (as you 
probably have) is "what has changed?" - has the Python/PSL on this 
computer been updated*, has the computer's SSL/TLS library been updated, 
etc. Then there are possible changes at 'the other end' - per previous 
responses.


* IIRC the last changes to email lib were circa 3.5, but poplib's doc 
page shows more recent updates - including to timeouts in v3.9 (YMMV).



There are changes afoot in the TLS arena. Older algorithms being dumped, 
and newer, stronger, harder, faster, better mechanisms (with racing 
stripes) being added. Not using POP3, I can't say how much impact such 
may have...


Try using an independent checker to investigate continuity of access. 
From your own machine (I use "s_client -connect..." but for IMAP), thus 
should be able to replicate the 'error' conversation at the level of the 
POP3 'conversation'. Alternately, use an on-line service such as: 
https://www.wormly.com/test-pop3-mail-server
Disclaimer: again, not using POP3, I have never used this service, it 
'popped-up' whilst searching on DuckDuckGo.



Many general-purpose service/server-providers seem rather heavy-handed 
when it comes to email security, often as a result of some knee-jerk 
response to a 'live-issue' - ultimately caused by them not having 
competent email-specialists on-staff. Accordingly, they may have 
'changed policy' and 'forgotten' to let mere-clients know. (although, if 
your standard email access continues unabated, this seems less-likely) 
That said, it never hurts to ask/be in friendly-contact...



PS is that really your password? If so, ...
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Third round of the Smart Iterator Challenge: September-October 2022

2022-10-20 Thread dn

Challenge-week 3: Generalising the solution, starts today!
Details from the Meetup site: 
https://www.meetup.com/nzpug-auckland/events/288813734/
A virtual event run by the Auckland Branch of the New Zealand Python 
Users' Group.



It's Week 3 of the Smart Iterator Challenge! Time to see how modules and 
namespaces provide building-blocks which enable us to cope with change. 
Can you anticipate and manage change? The tutorial demonstrates SOLID's 
SRP (and a bit of OCP) for those who want to learn more than Python-coding.


This Challenge will interest Python-Journeymen, and Python-Apprentices 
ready to move-on from ‘the basics’. There is a separate-but-related 
question for Python-Masters and any advanced Journeymen who are finding 
the main Challenge too-easy (available upon personal request), in 
recognition of being prepared to help others.


We start with a review of Challenge-week 2 and a sample-answer to 
download and compare with your own efforts. Challenge-week 3 starts with 
either your own or a provided template-script, so you don't have to have 
completed Challenge-weeks 1 and 2 (but it will help). Again, there is a 
tutorial in case you haven't met namespaces before. Followed by multiple 
specifications to implement.


In many ways, the challenge is not so much writing code, as it is 
designing a code-solution. Putting code-modules together, something like 
a jig-saw puzzle!



Challenge Schedule: Generalising the solution
Starting: Sat 22 Oct Office Hours: 1830*, Wed 26 Oct Concluding: 
midnight after Sun 30 Oct

* all times NZDT (UTC+13)


Are you up for a challenge?
Regards =dn (for Pete and DJ)
--
https://mail.python.org/mailman/listinfo/python-list


Crafting Software (PUG practical meeting)

2022-10-27 Thread dn

Wed, 2 Nov 2022 at 1830~2030 NZDT (0530~0730 UTC)

Come to our Coding Evening with your Python questions, suggestions, 
problems, etc; and/or bring a Lightning Talk about your current 
topic-of-interest - something new, a recent discovery, a contribution 
you have made...


Thereafter, we will continue the Crafting Software series. These are 
code-along-at-home exercises. The initial sessions were designed for 
Beginners, and have gradually 'grown' into areas which will challenge 
and benefit Journeyman Python Programmers and even Masters. The aim is 
to complement our Software Craftsmanship Presentation series with 
practical coding and observing the advantages of craftsmanship, as 
we/the code becomes more sophisticated.


We are enjoying meeting attendees from all over the world (Europeans 
invert their screens to be able to see us 'right way up' (!?))


Please RSVP to be advised of the web-conference URL, and QuickStart 
Guide. https://www.meetup.com/nzpug-auckland/events/hgxmwsydcpbdb/


--
Regards,
=dn
Auckland Branch, New Zealand Python Users' Group
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-29 Thread dn
Out of interest, tested snippet in PyCharm, cf native-mypy. It flags the 
original:


GLOBALS.foos: Optional[Foos]=Foos()

but not the fall-back:

GLOBALS.foos=Foos()


Must admit, the first query coming to mind was: why is the typing taking 
place at initialisation-time, rather than within the (class) definition? 
At definition time "foos" has already been typed as None by implication!



Solution (below) will not work if the mention of Foos in GLOBALS is a 
forward-reference. Either move GLOBALS to suit, or surround "Foos" with 
quotes.



Also, these days (Python version allowing) importing "List" is 
unnecessary. Instead could use "list".




On 30/10/2022 10.23, Sam Ezeh wrote:

Do you want the following?

```
from typing import List, Optional


class GLOBALS:
 foos: Optional[Foos] = None


class Foo:
 def __init__(self):
 pass


class Foos:
 Foos: List[Foo] = []

 def __init__(self):
 pass


GLOBALS.foos = Foos()
```

Kind regards,
Sam Ezeh

On Sat, 29 Oct 2022 at 22:13, Paulo da Silva <
p_d_a_s_i_l_v_a...@nonetnoaddress.pt> wrote:


Hi!

Consider this simple script ...

___
from typing import List, Optional

class GLOBALS:
  foos=None

class Foo:

  def __init__(self):
  pass

class Foos:
  Foos: List[Foo]=[]
  # SOME GLOBALS ARE USED HERE in a real script

  def __init__(self):
  pass

GLOBALS.foos: Optional[Foos]=Foos()
___

Running mypy on it:
pt9.py:18: error: Type cannot be declared in assignment to non-self
attribute
pt9.py:18: error: Incompatible types in assignment (expression has type
"Foos", variable has type "None")
Line  18 is last line and pt9.py is the scrip.

Replacing last line by
GLOBALS.foos=Foos()
and running mypy still gives the second error.
pt9.py:18: error: Incompatible types in assignment (expression has type
"Foos", variable has type "None")

What is the common practice in these cases?

Thank you.

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



--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-29 Thread dn

On 30/10/2022 11.59, Paulo da Silva wrote:
Solution (below) will not work if the mention of Foos in GLOBALS is a 
forward-reference. Either move GLOBALS to suit, or surround "Foos" 
with quotes.
This is the problem for me. So far, without typing, I used to have some 
config and globals classes, mostly to just group definitions an make the 
program more readable. A matter of taste and style.


Agreed, a good practice.


Now, "typing" is breaking this, mostly because of this forward reference 
issue.


As a first step, use the quotation-marks to indicate that such will be 
defined later in the code:-



class GLOBALS:
Foos: Optional[Foos]=None 


class GLOBALS:
Foos: Optional["Foos"]=None


Later, as gather (typing) expertise, can become more sophisticated, 
as-and-when...



The funny thing is that if I replace foos by Foos it works because it 
gets known by the initial initialization :-) !


Is the objective to write (good) code, or merely to satisfy the 
type-checker?


Something that is misleading is not going to be appreciated by others 
(including the +6-months you), eg


a = a + 1   # decrement total

Typing is not compulsory, and has been designed so that we can implement 
it a bit at a time, eg only one function amongst many contained by a 
module - if that's the only code that requires maintenance/update.


Best not to create "technical debt" though!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-30 Thread dn

On 30/10/2022 17.48, Paulo da Silva wrote:

Às 02:32 de 30/10/22, dn escreveu:

On 30/10/2022 11.59, Paulo da Silva wrote:
Solution (below) will not work if the mention of Foos in GLOBALS is 
a forward-reference. Either move GLOBALS to suit, or surround "Foos" 
with quotes.
This is the problem for me. So far, without typing, I used to have 
some config and globals classes, mostly to just group definitions an 
make the program more readable. A matter of taste and style.


Agreed, a good practice.

Thank you.



Now, "typing" is breaking this, mostly because of this forward 
reference issue.


As a first step, use the quotation-marks to indicate that such will be 
defined later in the code:-



class GLOBALS:
    Foos: Optional[Foos]=None 


class GLOBALS:
 Foos: Optional["Foos"]=None


Later, as gather (typing) expertise, can become more sophisticated, 
as-and-when...



The funny thing is that if I replace foos by Foos it works because it 
gets known by the initial initialization :-) !


Is the objective to write (good) code, or merely to satisfy the 
type-checker?


Something that is misleading is not going to be appreciated by others 
(including the +6-months you), eg


a = a + 1   # decrement total

Typing is not compulsory, and has been designed so that we can 
implement it a bit at a time, eg only one function amongst many 
contained by a module - if that's the only code that requires 
maintenance/update.


Best not to create "technical debt" though!

The main idea is to eventually catch some, otherwise "hidden", errors 
and produce better and cleaner code. Documentation is also a must.



Good idea!

All-along typing has been regarded as a tool for dev.aids, eg IDEs like 
PyCharm and tools such as mypy - rather than a (compulsory) component of 
the Python language itself. This means the folk who decide they don't 
like the idea can happily (and safely) ignore it - and continue to write 
code in perfect-Python. Also, that 'old program[me]s' will continue to 
operate, just as well as they ever did, without any reference to the 
typing library/ies at all. So, there is no imposed-cost, or 'pressure' 
to (wait to) upgrade (such as there was with the jump from Python 2 to 
Python 3).



IMHO I'm finding that the auto-checking performed by the IDE is very 
helpful and stops my imagination from outstripping my coding-abilities 
(in the way that my eyes for chocolate cake are bigger than my 
stomach!). I'll go so far as to say that the discipline imposed/flagged 
by typing has been more beneficial, than my flirtation with an 'AI 
assistant' suggesting what I should code next! The assistant rarely 
seems to correctly anticipate my thinking*, whereas typing pulls me up 
when the code falls-short and prevents me from falling flat on my face!


* which may say something unfortunate about my coding/design, or may 
simply show that SODD (Stack Overflow Driven Development - or the GitHub 
equivalent) leaves much to be desired. Hence the gold-plated advice: 
never copy-paste code without understanding it first!



As time goes by, 'The Python Gods' have been introducing more and more 
capability under the typing banner. Which makes the policy as-outlined, 
the sensible (and parallel) course. S/w architecture and coding-quality 
books talk about "The Boy Scout Rule" (leave the camp-site in better 
condition than you found it). Accordingly, when performing 
user-specified updates, while we are 'there', we have the option/ability 
to add typing to a module/class/function - just as we might perform 
other "refactoring" tasks (one 'green-thumb' I know, referred to it as 
'gardening').



Evidently, the OP introduced typing into his/her code-base with the 
likes of List*. Thereafter, added the Optional, er, option. Now, we're 
talking about forward-references. Plus alluding to more recent 
developments (many of which are version-dependent!).


Accordingly, we see another attribute of a gradual-introduction policy - 
the practitioner learning and becoming confident that (s)he has mastered 
basic techniques, before striding onwards to 'the next level'!



* and for the above reason, I wondered, belatedly, if earlier advice to 
'graduate' to "list", might be premature.



PS and on a personal note, this policy is the one I'm following. So, 
given that we-two are on the same track, we must be "correct" - and also 
the best Python programmers in the world!

(pardon me, I seem over-taken by a coughing fit...)

YMMV!
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-30 Thread dn

On 31/10/2022 06.06, Stefan Ram wrote:

Paulo da Silva  writes:

Is there anything to do without loosing my script structure and usual
practice?


   to lose (losing): to stop having something
   to loose (loosing): to let or make loose (see next line)
   loose (adj.): not firmly attached/tied/fastened/controlled
   to loosen: similar to "to loose"



Hay, your write*!

Well done. There's many a native-speaker who doesn't know the 
distinction, or doesn't care about accuracy.


It's a pity that there's no decent typing module for the English language!



* yes, each word sounds about-right, but is totally wrong...
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-30 Thread dn

On 31/10/2022 11.44, Chris Angelico wrote:

On Mon, 31 Oct 2022 at 09:39, dn  wrote:


On 31/10/2022 06.06, Stefan Ram wrote:

Paulo da Silva  writes:

Is there anything to do without loosing my script structure and usual
practice?


to lose (losing): to stop having something
to loose (loosing): to let or make loose (see next line)
loose (adj.): not firmly attached/tied/fastened/controlled
to loosen: similar to "to loose"



Hay, your write*!

Well done. There's many a native-speaker who doesn't know the
distinction, or doesn't care about accuracy.



I'm curious to what extent sloppy English correlates with sloppy code.
Do people care about learning proper Python but not about proper
English, or do they think there's no such thing as proper English just
because there's no English Steering Council?

A lot of people seem to treat English the way web browsers treat HTML
- as long as you can make some sense out of it, it's good enough. Some
nerds treat English the way the W3C treats HTML - there actually is a
standard and everything has defined rules. I know which camp I prefer
to communicate with.



There are two distinctions to make: what is "correct", and how correctly 
we practice!


Various languages do have a 'standards body', eg French and the group 
known as "l'Académie (française)". However, no matter how much they try 
to push-back against the encroachment of words from other languages (eg 
"le weekend"), even they admit that it is a losing battle (see also: 
King Canute).


English is, and has long-been, an "acquisitive language". It takes words 
from other languages, often as attempted-homophones, and makes them 
"English": verandah, foreign, algebra, ... (and seeing I mentioned 
French: "maitre d'" because it makes the restaurant sound 'posh'; 
champagne because you can then charge more for the bubbles, and 
omelet/omelette because I'm feeling hungry...). Indeed yous-Australians 
are also manipulators of the language, eg "tradies" for 
tradesmen/trades-people (see also: "They're a Weird Mob" - in case you 
haven't read that hilarious piece of Aussie Kulcha).


There have been various attempts at standardising English. Indeed for 
our Internet-based training courses and courseware, I went looking for 
an 'international English'. There is no such thing. The closest is more 
to do with accent than text, ie speaking the Queen's/King's English, is 
really a euphemism for a (plummy) Oxford accent (or BBC accent - also 
fading into the past). A good starting-point: 
https://www.cambridge.org/highereducation/books/the-cambridge-encyclopedia-of-the-english-language/2B10AC8766B73D09955C899572C1E7EC#overview 
- a tome compiled by a man living in Wales (go figure!).


The earliest attempts would include Samuel Johnson's Dictionary of the 
English Language (which preceded 'your' Lewis Carroll's playing with 
language by about half a century). Around-about one-century after that 
came the OED (Oxford English Dictionary), which is the closest thing to 
an idea of 'standard spelling'. (and at times differs significantly from 
alternate tomes describing American-English).


As for grammar, I must admit deferring (and devolving?) such to style 
manuals, such as The Times of London, Strunk and White, etc. (but 
perhaps only later and lesser: Kernighan and Plauger's similarly named 
"Elements of Programming Style"). In this case, my multi-cultural 
education (or lack of application to my school-work?) has caused me many 
a stumble. Certainly, I've never taught the subject. Perhaps someone is 
better-acquainted with works used by The British Council, et al, in 
their English as a Second Language (and related) courses?



The other side of this topic, that of accuracy and precision, involves 
aspects which were driven into us at school - that is, those of us with 
Optional[grey] hair! These days, teaching good-grammar, spelling, and 
so-on, are deemed unnecessarily restrictive, perhaps even cruel, but 
certainly far too boring (see also: "joined-up" hand-writing). "Drill" 
(aka "deliberate practice") is rarely employed as a teaching/learning 
technique in schools. Cue "amo, amas, amat, amamus, amatis, amant" 
(Latin - although quite why, as six-year olds, the teachers ("Masters") 
thought we should be speaking of love escapes me) and "Je suis, tu es, 
il est, ..." (French - which always reminds me of Rodin's sculpture and 
Descartes exclamation)*


I've even (as an adult) had a (school) Department Head reply to such 
criticism with "but you understood me, didn't you?". So, with teachers 
like that, the kids are 'on a hiding to nothing'. The prevailing-theory 
seems to be

Re: an oop question

2022-10-30 Thread dn

On 31/10/2022 09.22, Stefan Ram wrote:

Giorgio Pastore  writes:

You may find useful to learn about the possibilities of using Python
tools to implement a stack data structure and its manipulation methods.
A good introduction is at
https://realpython.com/how-to-implement-python-stack/


   I can't see how lists are not stacks.


Agreed - in terms of functionality(!)


|>>> s=[]
|>>> s.append(1)
|>>> s.append(2)
|>>> s.pop()
|2
|>>> s.pop()
|1
|>>> s.pop()
|Traceback (most recent call last):
|  File "", line 1, in 
|IndexError: pop from empty list

   So, for practical purposes, there is no need to implement a
   stack class as far as I can understand it.

   Maybe the OP wanted to implement a stack in a special way,
   so that this stack is immutable and its implementation is
   based on something like dotted pairs.



Code is for humans to read too. Accordingly, instead of "s", preference 
for "stack" - per OP terminology.


The OP has coded pop() and push() methods, which are familiar/taught as 
'the' stack operations in every 'intro to algorithms' (or intermediate 
'data-structures') class.


Sadly, whereas there is list.pop(), the equivalent "push" method is 
append(). Thus, a (small) dissonance in one's mind.


Writing a Stack class is unnecessary - at least given list, it is. 
However, having called the structure "stack" to be descriptive and 
helpful, it seems logical to continue by referring to the methods as 
"push" and "pop".
(which is why many of us have such 'utilities'/snippets sitting-ready in 
a personal library)


The OP has already coded such, so no cost to keep.


(returning to the OP)
Like @Gerard, am confused. There are two types: Pair and Empty. 
Thereafter the need is to keep them on a stack. The stack is a 
collection, an aggregate of 'whatever'. Why inherit from/to Stack?

(is this a 'Lisp thing'?)

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Weired behaviour - The slice of empty string not return an error

2022-10-30 Thread dn

On 31/10/2022 03.59, Yassine Nasri wrote:

PS: The ''[::] should  return an error logically.

Le dim. 30 oct. 2022 à 15:57, Yassine Nasri  a
écrit :


Hello,

len('')  # => 0''[0]# => error''[::]   # => ''''[::]   # <=> ''[0:len(''):1]

the syntax of slice:

slice(start, end, step)

The start in ''[::] equivalent at index 0 of the ''

Since the index 0 of '' returns an error.

The ''[::] should not return an error logically.



Perhaps it will help to say:

- "indexing" one "element" from a "sequence" will yield a single result 
of the type of that element


- "slicing" a "sequence" will yield a result of the same type as the 
original sequence


The corollary to the first is expected: that if there is no element at 
the stated index/position, something is wrong.


However, what is not necessarily apparent, is that because the result is 
of the same type as the original sequence, and an empty-sequence is 
perfectly legal; so is it possible to slice something and receive back 
'nothing'.



The second 'saying' is to use the correct jargon:

- in a[ i ] i is an "index"

- in a[ i:j ] i and j are "parameters"

A parameter does not (also) need to be a legal index!


This is proven (as you have discovered (but is difficult to read, above):

>>> sequence = []
>>> len( sequence )
0
>>> sequence[ 0 ]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range
>>> sequence[ 0:1 ]
[]


The question (and assertion) are discussed in the manual:
«Sequences

These represent finite ordered sets indexed by non-negative 
numbers. The built-in function len() returns the number of items of a 
sequence. When the length of a sequence is n, the index set contains the 
numbers 0, 1, …, n-1. Item i of sequence a is selected by a[i].


Sequences also support slicing: a[i:j] selects all items with index 
k such that i <= k < j. When used as an expression, a slice is a 
sequence of the same type. This implies that the index set is renumbered 
so that it starts at 0.


Some sequences also support “extended slicing” with a third “step” 
parameter: a[i:j:k] selects all items of a with index x where x = i + 
n*k, n >= 0 and i <= x < j.

»

Thus, an index must point to an existing element, whereas the parameters 
of a slice need not. If the slice-specification calls for elements 
'beyond' the end of the sequence, then the result will only contain 
items up-to the last element, ie the length of the resultant-sequence 
will be shorter than j - i, where j > len( sequence ).



# Proof (which concurs with the OP's observations)

# playing with a tuple's indexes/indices

>>> sequence = 1,2,3
>>> sequence[ 1 ]
2

# notice the result's type!

>>> sequence[ 9 ]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: tuple index out of range

# the above index is plainly 'beyond' len( sequence )
# do you know about negative indexes/indices?

>>> sequence[ -1 ]
3
>>> sequence[ -9 ]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: tuple index out of range

# again this index is 'beyond' the first element of the sequence


# let's play with some slicing;

>>> sequence[ 0:3 ]
(1, 2, 3)
>>> [ 1, 2, 3 ][ 0:3 ]
[1, 2, 3]

# same applies to lists (and strings, etc)
# notice the types!

>>> sequence[ 1:1 ]
()
>>> sequence[ 1:2 ]
(2,)
>>> sequence[ -1:2 ]
()
>>> sequence[ -1:-2 ]
()
>>> sequence[ -1:-2:-1 ]
(3,)
>>> sequence[ -1:-3:-1 ]
(3, 2)

# OK, what happens when parameters point to non-existent indexes?

>>> sequence[ 1:9 ]
(2, 3)
>>> sequence[ 1:-9 ]
()
>>> sequence[ -1:-9:-1 ]
(3, 2, 1)
>>> sequence[ -9:-1:-1 ]
()

# yes, they are parameters and not strictly indexes/indices!


https://docs.python.org/3/reference/datamodel.html?highlight=slicing#the-standard-type-hierarchy
for "sequences" and "slice objects"

Note that a Python set is "collection" but not a "sequence". Which means 
that neither indexing nor slicing (per above) will work on a set. We can 
ask if a particular value appears in a set ("contains") but cannot ask 
for the n-th element. To be able to index or slice it, a sequence must 
offer a __getitem__() method - tuple, list, and string do; but set does 
not. (check for yourself: help( set ) )


https://docs.python.org/3/library/collections.abc.html?highlight=collection

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: A typing question

2022-10-31 Thread dn

On 01/11/2022 01.56, Stefan Ram wrote:

dn  writes:

On 31/10/2022 11.44, Chris Angelico wrote:

...

I'm curious to what extent sloppy English correlates with sloppy code.

...

When it comes to CVs/resumés (see what I did there?), I must admit that
the most egregious of errors in spelling or grammar do ensure that an
applicant's 'work' is quickly routed to "file 13" (an American-English
term, many other English-speakers will not have heard previously).


   This discussion reminds me of something Eric Raymond said:

|While sloppy writing does not invariably mean sloppy thinking,
|we've generally found the correlation to be strong -- and we
|have no use for sloppy thinkers. If you can't yet write
|competently, learn to.
Eric Raymond

   . Other relevant quotations are:

|Besides a mathematical inclination, an exceptionally good
|mastery of one's native tongue is the most vital asset of a
|competent programmer.
Edsgar Dijkstra

|I've found that some of the best [Software ]developers
|of all are English majors. They'll often graduate with
|no programming experience at all, and certainly without
|a clue about the difference between DRAM and EPROM.
|
|But they can write. That's the art of conveying
|information concisely and clearly. Software development
|and writing are both the art of knowing what you're going
|to do, and then lucidly expressing your ideas.
|
Jack Ganssle

|The narrative measures of conjunction use, event
|content, perspective shift, and mental state reference
|were significantly predictive of later Math scores.
"Evidence of a Relation between Early Narrative and ..." (2004)
- DK O’Neill

|I have never, ever, ever seen a great software developer
|who does not have amazing attention to detail.
(2006-08-20) - Rob Walling


+1 Thanks for these!
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: typing: property/setter and lists?

2022-11-03 Thread dn

On 03/11/2022 16.24, Paulo da Silva wrote:

class C:
 def __init__(self):
     self.__foos=5*[0]

 @property
 def foos(self) -> list[int]:
     return self.__foos

 @foos.setter
 def foos(self,v: int):
     self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int", 
variable has type "List[int]")



To help us to help you please copy-paste the *exact* message - 
especially which line is in-question.



The above code passes without complaint in PyCharm, and executes.


However, the general rule?convention would be to establish type at the 
first mention of the identifier, eg


def __init__(self):
self.__foos:list[int] = 5 * [ 0 ]
# or [ 0, 0, 0, 0, 0, ]


Why the "__i", and not "i", or "_"?
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Challenge-week 4: Groups of solutions, starts today!

2022-11-03 Thread dn
A virtual event run by the Auckland Branch of the New Zealand Python 
Users' Group. Details from the Meetup site: 
https://www.meetup.com/nzpug-auckland/events/289531194/ where you may 
also sign-up.



It's Week 4 of the Smart Iterator Challenge! We've looked at taking our 
early results and generalising them to suit various solutions. The next 
view is how a range of similar solutions might be grouped - and 
re-shaped to enable us to re-use and share code.


We commence with a review of Challenge-week 3 and sample-code to 
download and compare with your own efforts. This time there is no 
tutorial-content. Even the provided testing/proofs are rather sparse - 
and really only there to make sure you're on-the-right-track. In many 
ways, the challenge is not so much writing code, as it is designing 
code-solutions. Putting code-modules together, and then pulling them 
apart to satisfy groups of solutions. Ooh mysterious!



This Challenge will interest Python-Journeymen, and Python-Apprentices 
ready to move-on from ‘the basics’. As usual, there are "Extra Credit" 
challenges which will 'push' Python-Masters and advanced Journeymen.


It's not a requirement that you have completed the previous challenges - 
but they will help. Challenge-week 4 starts with either your own or a 
provided template-script. So, you don't have to have completed 
Challenge-weeks 1, 2, and 3 (but it would help - there's nothing to stop 
you from 'catching up' and gaining full benefit from the exercise). 
There's some 'template code' which will enable starting from this week.



Challenge Schedule: Groups of solutions
Starting: Sat 5 Nov
Office Hours: 1830*, Wed 9 Nov
Concluding: midnight after Sun 13 Nov
* all times NZDT (UTC+13)


Are you up for a challenge?
Regards =dn (for Pete and DJ)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Issues in python 3.11.0 (64-bit) installation

2022-11-03 Thread dn

On 04/11/2022 04.20, Suresh Babu wrote:

 I downloaded the latest version of python i.e. python 3.11.0 ( 64-bit)
in my laptop recently. But the " py launcher " and " available for all
users " option is not working in the customization menu of python 3.11.0 .
Kindly help me in solving this issue.

My operating system is Windows 11. Kindly guide me in this regard.


Has the documentation left questions?
https://docs.python.org/3/using/windows.html

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: typing: property/setter and lists? [RESOLVED ERRATA]

2022-11-04 Thread dn

On 04/11/2022 07.50, Chris Angelico wrote:

On Fri, 4 Nov 2022 at 05:48, Paulo da Silva
 wrote:


Às 05:32 de 03/11/22, Paulo da Silva escreveu:

Às 03:24 de 03/11/22, Paulo da Silva escreveu:

Hi!

And a typing problem again!!!
___
class C:
  def __init__(self):
  self.__foos=5*[0]

  @property
  def foos(self) -> list[int]:
  return self.__foos

  @foos.setter
  def foos(self,v: int):
  self.__foos=[v for __i in self.__foos]

c=C()
c.foos=5
print(c.foos)
___

mypy gives the following error:
error: Incompatible types in assignment (expression has type "int",
variable has type "List[int]")

How do I turn around this?


Changing def foos(self) -> list[int]:  to
   def foos(self) -> Union[list[int]]:

I meant, of course,
def foos(self) -> Union[list[int],int]:



Ohhh! I thought this was triggering a strange quirk of the checker in
some way...



Yes, these personal styles (?quirks) are off-putting to others.

Plus "_" means (more or less) "not used anymore"
and for most of us, a weak-identifier name such as "i" is indeed "an 
indexer/counter/... "
Accordingly, the question becomes: why not follow the crowd - unless you 
tell me that this is a team/company convention?


...and whilst I'm griping,
"To help us to help you please copy-paste the *exact* message"
has been followed by:
"I'm sorry. A bad transposition of the text."

copy-paste for the win!
(and to keep others happy to spend their voluntary time helping you - 
more working-with-the-team thinking to consider - please)

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Argument name should be lowercase

2022-11-11 Thread dn
PyCharm is warning against using an identifier of all upper-case letters 
as a function's parameter, saying "Argument name should be lowercase". 
(weak, code smell)



The application consists of three+ files:
- configuration
- mainline script
- module of workbook functions

The mainline reads the configuration parameters to set the application's 
environment. All of the config/settings are constants. Some of them 
appear as a dictionary (PRICES_WORKBOOK) defining a workbook's 
(spreadsheet's) parameters, eg the filename, which work-sheet to use, etc.



The mainline calls the relevant functions from within the module, 
as-needed:-


import prices_workbook as pw
...
product_prices = pw.build_product_prices_dictionary( PRICES_WORKBOOK )


The module's function definition is:

def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict:
...
price_array = xl.iget_array(
file_name=WORKBOOK_DEFINITIONS[ "file_name" ],
...

(the function def is flagged, as above)


A quick scan of PEP-008 failed to yield anything relevant. Why is this 
frowned upon as poor Python, or a matter of style?


Yes, a dict is mutable, but the upper-case denoting a constant indicates 
that none of its values are to be changed by the programmer.


As far as the function is concerned, the dict and its contents are 
constants.
(but the dict can't be treated as a global ENV[IRONMENT] object, because 
it has to cross into the module's namespace)



Is passing the dict as an argument/parameter considered to be 
incompatible with its designation as a constant?


Perhaps the style should be more enum-like, ie the dict's name in 
lower-case, with the key-named in upper case, eg


workbook_definitions[ "FILE_NAME" ]


Am not particularly concerned by the IDE raising this as a 'problem' - 
will quite happily ignore and carry-on; but am curious as to the logic 
behind the analysis - and why it doesn't come readily to mind.


Advice, comments, critique welcome!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Argument name should be lowercase

2022-11-11 Thread dn

Thanks for the thoughts!


On 11/11/2022 21.54, dn wrote:
PyCharm is warning against using an identifier of all upper-case letters 
as a function's parameter, saying "Argument name should be lowercase". 
(weak, code smell)



...
PEP-008: makes no mention, and is but a guide anyway.
(that said, if one 'breaks a rule', then a good reason should be required!)

YELLING is an email-interpretation. Does it apply to code? Particularly 
as we are talking Python, where an identifier using all upper-case 
letters is a convention (not a language-structure, as stated in 
contributions 'here') that is widely used.


Accordingly, the purpose of the UPPER_CASE is to communicate the 
read-only nature of the data-item to the programmer. Combine this with 
"we're all adults here", and if someone is foolish-enough to modify a 
'constant', then Python will comply - but (s)he can expect push-back 
during a Code Review! So, yes, «weird to see an all-cap parameter» (I 
thought so too) but isn't that effect the purpose of the convention in 
the first place?


There are several aspects of Python where the 'we're all adults' 
thinking must be applied, eg 'private attributes'. Given that 
understanding, it doesn't seem necessary to force constant-behavior on 
the parameter - although when one does, there are a couple of mechanisms 
and more than several projects working on this and other aspects of 
enforcing data-types and their characteristics!


That said, and with @Stefan's observations, there are many reasons why 
this code is piling-up trouble - and thus, should be avoided...




def build_product_prices_dictionary( WORKBOOK_DEFINITIONS:dict )->dict:
...
     price_array = xl.iget_array(
     file_name=WORKBOOK_DEFINITIONS[ "file_name" ],
     ...

(the function def is flagged, as above)


As far as the function is concerned, the dict and its contents are 
constants.
(but the dict can't be treated as a global ENV[IRONMENT] object, because 
it has to cross into the module's namespace)


By way of background, in recent times, have the habit/standardised code 
'template' for config/environment-setting, which instantiates a class 
from (at least) JSON/YAML files. Accordingly, the instance is named in 
lower-case, and particular groups of parameters (as here) can be passed 
as an extract-function/property (as a general style, I avoid long 
parameter/argument lists, preferring a data-collection - which landed me 
in this...).


Which re-raises the question the other way around: how does the object's 
name indicate its constant/read-only nature to the reader?

"Ouch" says idealism!

Back to this case, which part of a tutorial comparing different methods 
to access prices in a product-catalog[ue] (eg hard-coded dict, 
flat-file, workbook, database, etc). Some members of the group are 
either anti-OOP or OOP-untrained. Hence avoiding my personal 'good, old, 
stand-by'.


(plus it was Veterans'/Remembrance/Liberation Day, which we don't 
observe (much) here (ANZAC Day instead) and I was using some 
creative-coding time to [try to] take my mind off it)


The particular @Rob and I both find it peculiar (in the same sense) but 
as-above, that's (ultimately) the point of the upper-casing.


The idea of moving the workbook-definitions into that module appears to 
make sense and could easily be achieved - but in the singular context of 
this example. However, as a matter of style, all of an application's 
environment-setting would best be done in one place - with cmdLN, 
config-file(s), etc, all being combined, and with the output of a single 
'authority' as its objective.


I could try to 'get away with it', but if some Apprentice takes the idea 
and later uses it as a 'template', a general grumpiness will result... 
(no it's not a learning-objective, but sometimes people take-away 
unintended 'side effects', maybe like this).


However, in that spirit, am contemplating use of a DataClass. It will be 
as easy to read as any config file, even to non-OOP-ers; has no learning 
side-effect down-side (that I've spotted, as-yet); and can be 'seen' as 
a instance by the workbook module (instance named using lower-case). 
This, hopefully also measuring-up to @Thomas' observations of risk that 
the current code's intentions be misconstrued later.


I'll admit to (idealists look away now!) not being 'above' the use of 
globals, particularly?if only an ENVIRONMENT class - IIRC this 
irresponsible behavior being when the environment is fairly trivial (cf 
multi-layered or large numbers of 'tunable factors').


Because the ENVIRONMENT is returned to the mainline, which subsequently 
uses those parameters to call the 'action' functions/methods (and know 
which to cal

Re: Persisting functions typed into the shell

2022-11-12 Thread dn

On 13/11/2022 05.05, Stefan Ram wrote:

Wayne Harris  writes:

Wow.  Could the dis module help at all?


   Thank you for this idea! I think this should work, but only
   under CPython and not necessarily across different Python
   versions. Still, I might use dis.


Was constructing a two-part tutorial. When it came to the preparing for 
the second meeting, was surprised to discover that PyCharm retained code 
and values in its Python Console (its REPL tab/window) - I'm presuming, 
within its 'project' structure.


Was more interested in ensuring all-parties would be able to re-create 
the ending/re-starting position, regardless of IDE. Accordingly, never 
looked any further.


Depending upon the full range of criteria, may be worth a look...


Disclaimer: JetBrains sponsor our local PUG with a one-year 'pro' 
license, as a monthly 'door prize'. Apart from using the product, have 
no other connection!


Similarly, have not looked at such within VS-Codium or other editors/IDEs...
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: In code, list.clear doesn't throw error - it's just ignored

2022-11-13 Thread dn

On 14/11/2022 12.12, DFS wrote:

On 11/13/2022 5:20 PM, Jon Ribbens wrote:

On 2022-11-13, DFS  wrote:

In code, list.clear is just ignored.
At the terminal, list.clear shows



in code:
x = [1,2,3]
x.clear
print(len(x))
3

at terminal:
x = [1,2,3]
x.clear

print(len(x))
3


Caused me an hour of frustration before I noticed list.clear() was what
I needed.

x = [1,2,3]
x.clear()
print(len(x))
0


If you want to catch this sort of mistake automatically then you need
a linter such as pylint:

   $ cat test.py
   """Create an array and print its length"""

   array = [1, 2, 3]
   array.clear
   print(len(array))
   $ pylint -s n test.py
   * Module test
   test.py:4:0: W0104: Statement seems to have no effect 
(pointless-statement)



Thanks, I should use linters more often.

But why is it allowed in the first place?

I stared at list.clear and surrounding code a dozen times and said 
"Looks right!  Why isn't it clearing the list?!?!"


2 parens later and I'm golden!

It looks 'right' because it is 'right'!
However, compared with what was intended, it was 'wrong'!

«
I really hate this d***umb machine,
I wish that they would sell it.
It never does quite what I want,
but only what I tell it!
»



Lifting some text from a recent PUG-meeting:

«Distinguishing functions and their names:

Please remind yourself that is_odd is the name of a function, whereas 
is_odd() calls the function and could thus be considered a 'label' for 
the returned-value – either approach could be used in different situations.

»


In this case, the subject is a method, and accordingly has a slightly 
different flavor. Rather than a return-value, the impact is an effect 
within the scope and/or to the state of the object. However, not 
materially-different from the OP's question.



It is assumed that there is no difficulty related to calling the 
function, eg len( x ).



So, why would we use the function/method by name instead of its asking 
for its return-value?

(please remember that a Python function is a "first class" object)

The (above) Challenge to PUG-members was to use code which produces the 
Fibonacci Sequence, and out of the first 16 values, return the number of 
Fibonacci-values which are also odd-numbers.


We started with straight-line code which mixed-up these various steps in 
the process. As the challenge continued, such tangling made it very 
difficult to enable any variations. To illustrate the SRP and DIP 
(Single Responsibility and Dependency Inversion Principles of SOLID 
Architecture), we refactored and refactored, ending-up with:


values_counted = sm.sequence_select_and_project(
  fg.fibonacci_generator,
  is_odd,
  limit,
  )

sequence_select_and_project is a for-loop spanning two if-statements 
which count or break

fibonacci_generator is self-explanatory (hopefully)
is_odd returns boolean advice
limit is 16

Note how the first two arguments are [generator-]function names, cf 
function-calls!



Now for 'the magic' of a dependency-inverted plug-in architecture:-

If the 16 is changed to 32, we'll be comfortable with the idea that 
twice as many values will be generated and considered.


So, think about changing the generator to produce (say) prime numbers.

Alternately, alter the program to count only values divisible by two 
(perhaps using "is_even" as function-name).


By 'plugging-in' a different function-name, the above control-routine 
can be used with any suitably-lengthy sequence as its data-source, 
and/or selection-criteria function!



Accordingly, using the name of a function can be as useful as using the 
result of a function-call - even if the latter is far more common.


--
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Help Merging Of Separate Python Codes

2022-11-19 Thread dn

On 20/11/2022 02.20, maria python wrote:
Hello, I have these two python codes that work well separately and I 
want to combine them, but I am not sure how to do it. Also after that, I 
want to print the result in txt cvs or another file format. Do you have 
a code for that? Thank you.



Have you tried joining them together, one after the other?

Have you looked at the Python docs?
eg https://docs.python.org/3/library/csv.html

Do you need the help of a professional to write code for you?

If you are learning Python, perhaps the Tutor list will be a more 
appropriate for you...


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing information between modules

2022-11-19 Thread dn

On 18/11/2022 23.53, Stefan Ram wrote:

   Can I use "sys.argv" to pass information between modules
   as follows?

   in module A:

import sys
sys.argv.append( "Hi there!" )

   in module B:

import sys
message = sys.argv[ -1 ]

   . "sys.argv" is said to be a list by the standard
   documentation, so it should be guaranteed to be
   appendable as lists are appendable.

   Moreover, in my own program, after its startup, third parties
   do not inspect "sys.argv". So by appending something to it
   (or modifying it) I do not tamper with information that might
   be misinterpreted by any third party outside of my own code.

   Another hack might be:

   in module A

import builtins
builtins.message = "Hi there!"

   in module B

import builtins
message = builtins.message

   But I'm not sure whether modules (such as "builtins" here)
   are guaranteed to be modifyable and visible by the language
   reference in this way though



The re-use of built-in features is risky, if only because of the remote 
possibility that a future version of Python will add something that 
clashes. That's why Python makes such good (and careful) use of namespaces!


In some respects we have the (OP) problem because Python does not have 
"interfaces" as a formal component of the language. So, we often 
get-away with taking an easier course - but in doing-so, may forget that 
they serve specific purposes.



There is a general idea that globals are harmful, a code-smell, etc; and 
therefore something to be avoided. However, the global namespace is a 
(built-in!) feature of Python, so why not use it?


The problem comes when we try to re-use module A or B in some other 
application. It may not be relatively-obvious that some global, eg 
config, must be previously-defined and made-available. If you're 
prepared to accept that risk - and presumably combat the criticism by 
carefully (and prominently) documenting it, just as with any other 
docstring, where's the problem? (caveat emptor!)



Considering the use-case, it is unlikely to be as trivial as the 
example-given (OP). A classic example would be set of credentials to 
access an RDBMS and specific table(s).


A 'standard' solution is to collect all such configuration-data at the 
start of the application, into an object (or other data-structure) - I 
usually call it "env" (an instantiation of "Environment").


Thereafter, when needing such data within a module, calling the 
particular function/class/method by name (moduleNM.function(...) ), and 
passing only that section of the env[ironment] required. Such achieved 
by passing some sub-structure of env, or by passing a retrieval/get method.
(a module handling GUI, for example, has no business looking at 
RDBMS-creds - which it would be able to do if the whole env was passed!)



but...

the module's code will expect its data in a particular form (an 
interface!), which must be documented and understood by both the 
provider and consumer (people and software)


- which sounds like the same 'solution' to the 'globals problem'...

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing information between modules

2022-11-20 Thread dn

On 21/11/2022 01.03, Stefan Ram wrote:

dn  writes:

In some respects we have the (OP) problem because Python does not have
"interfaces" as a formal component of the language.


   What one can do today is,

class my_interface( metaclass=abc.ABCMeta ):
 """This interface ..."""

 @abc.abstractmethod
 def method( __self__, *s, **x ):
 """This abstract method ..."""

# ...

my_interface.register( my_class )

# ...



Ugh!

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing information between modules

2022-11-20 Thread dn

On 21/11/2022 12.07, Dan Kolis wrote:

If you understand its meaning, it achieves my purpose. If you don't I you're 
perhaps not a programmer...


Ouch!

Does the first sentence imply who is the more important person in the 
interaction? Does the second further the idea that anyone/everyone who 
is not at your 'level' has no worth?


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing information between modules

2022-11-20 Thread dn

On 21/11/2022 01.29, Stefan Ram wrote:

dn  writes:

A 'standard' solution is to collect all such configuration-data at the
start of the application, into an object (or other data-structure) - I
usually call it "env" (an instantiation of "Environment").


   Yeah, I had some functions of my library take such an "env",
   which in my library is called "context":

def python_version_check( major=3, minor=9, context=x_default_context ):
 passed = _sys.version_info >=( major, minor )
 if not passed:
  requirements_info = "This program requires Python " + \
  str( major ) + "." + str( minor )+ "+.\n"
  version_info = "Currently running under Python {}.{}.\n". \
 format( *_sys.version_info[ :2 ] )
  context.warning( requirements_info + version_info )
 return passed

   . But so far I am using "context" only for logging, so I am
   now thinking about replacing with Pythons logging facility.

   One possible application of "context", however, would also be
   normal output, which has to be shown to the user, not only
   logging as in:

def show_sum( x, y, context=x_default_context ):
   context.print( f'The sum is {x+y}.' )

   . For example, there could by a "GUI context" by which
   "context.print" would append the output to some GUI text
   field. Using the logging facility to output text that must
   be show to the user, would abuse logging somewhat.

def show_sum( x, y, context=x_default_context ):
   logger.log\
   ( my_custom_level_for_output_to_user, f'The sum is {x+y}.' )

   Or one could "print patch" a module, via (using the class from
   a recent post of mine):

M = prepare_module( 'M' )
M.print = my_gui_print_function
M = M.load()
M.f()

   and "show_sum" would be simply:

def show_sum( x, y, context=x_default_context ):
   print( f'The sum is {x+y}.').

   My original question probably was intended to be something
   like: "Today, we can add attributes to a module from the
   outside. How large is the risk that this will be forbidden
   one day, so that all code using this will stop working?".



Am put-off by the 'smell' of subverting/adapting names like print() = 
surprise/confusion factor - but I think I understand where you're going.


What about an ABC which is inherited by two classes. One class handles 
all the detail of output to GUI. The other, similarly, output to the 
terminal, log, (whatever). The ABC should require an output() method, 
with suitable signature. The two classes will vary on the fine detail of 
the HOW, leaving the calling-routine to produce the WHAT.


Now, at the config stage, take the instructions to define whichever the 
user prefers, and instantiate that class. Then the 'calling-routine' can 
use the instantiated object as an interface to whichever type of output.


If the choices on-offer include not just either/or, but also 'both of 
the above'. The instantiation would need to be a class which called both 
class's output() method serially.



Your use of the word "context" provoked some thought. (you don't know 
just how dangerous that could become!)


In many ways, and as described, an Environment/context class could be 
very easily coded with formal __enter__() and __exit__() methods. The 
mainline might then become:


with Environment() as env:
# processing

There would be no need to explicitly prevent any 'processing' if the 
set-up doesn't work, because that context manager class will handle it all!


NB haven't had time to try this as a refactoring exercise.

Is this how you implement?

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: NEO6 GPS with Py PICO with micropython

2022-11-29 Thread dn

On 30/11/2022 00.53, KK CHN wrote:

List ,
I am following this tutorial to  get latitude and longitude data  using
NEO6 GPS module and Py PICO  to read the GPS data from the device.

I followed the code specified in this tutorial.
https://microcontrollerslab.com/neo-6m-gps-module-raspberry-pi-pico-micropython/

I have installed thony IDE in my Desktop(windows PC) and  run the code
after the devices all connected and using USB cable connected to my PC.

When I ran the program I am able to see the output of  latitude and
longitude in the console of thony IDE.  But  between certain intervals of a
few seconds  I am getting the latitude and longitude data ( its printing
GPS data not found ?? ) in the python console.

The satellite count from the $GGPA output showing 03 ..
and the GPS data not found repeating randomly for intervals of seconds.
Any hints why it is missing the GPS data (randomly) ??

PS:-  The GPS device I placed outside  my window and connected to the PC
with a USB cable from the PICO  module. GPS device NEO6 light (Red LED
) blinking even though the "  GPS data not found" messages in th python
console.

Any hints ?? most welcome


If it works (correctly*) some of the time, and there is only one look-up 
in the code, it doesn't really sound like a problem with the Python.


* is it?

Does the unit also report the number of satellites it can 'see'? Is it 
always more than one?


Other data not-discussed: change of cable, reducing length of cable, ...

--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


AuckPUG's last (virtual) Coding Evening for 2022

2022-11-30 Thread dn

Wednesday 7 December, 1800 for 1830 NZDT/0530 UTC

We will continue the "Crafting Software" series, gradually developing 
Monty's Python Supermarket. The evening's aim is to move the 
product-prices from their hard-coded dict[ionary] into a flat-file 
(introducing Python I/O), and then to do same with the Accountant's 
favorite tool - a Workbook or Spreadsheet (Python's library to interact 
with LibreOffice-Calc and MS-Excel). You can treat it as a 
code-along-at-home exercise or just watch the fun. The Web-conference 
URL and a QuickStart Guide (for those who didn't attend last time) will 
be provided upon RSVP. All welcome!


https://www.meetup.com/nzpug-auckland/events/hgxmwsydcqbkb/



The Smart Iterators Challenge has finished (after five Challenge-weeks). 
Congratulations to all who participated (and if you didn't have time to 
complete, you're welcome to continue at your own pace). Particular pride 
for those who hung-in-there right to the end, making astute discoveries 
and learning ideas which have already been adopted into 
professional-practice. Well done! A "Retrospective, Review, and 
Reflection Wrap-up" document is available to participants/upon request. 
Advice and assistance will continue to be available - please email off-list.


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   >