Re: lxml with python-3.12.0a5

2023-02-24 Thread Robin Becker

On 23/02/2023 18:09, Mats Wichmann wrote:


I seem to always have trouble with lxml (which I know doesn't help).

The cause would seem to be this:

 GH-101291: Refactor the `PyLongObject` struct into object header and 
PyLongValue struct. (GH-101292)


So it looks to me like cython was affected, and has patched themselves. It's possible regenerating with a patched cython 
will clear up the build problem (something which the lxml project takes pains to tell you that you don't really want to 
do :)

Thanks Mats,

I build a cython wheel from git latest and after installing into 
python-3.12.0a5 I used latest lxml source and

 python setup.py bdist_wheel --with-cython

which built without error. The installed lxml seems fine (at least for 
reportlab tests).
--
Robin Becker
--
https://mail.python.org/mailman/listinfo/python-list


Re: semi colonic

2023-02-24 Thread Peter J. Holzer
On 2023-02-23 15:56:54 -0500, [email protected] wrote:
> I am not sure it is fair to blame JSON for a design choice.

We can't blame JSON (it has no agency), but as you say, it it was a
choice. And we can absolutely blame Doug for making that choice!

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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


Re: putting JUNK at the end of a [.py] file

2023-02-24 Thread Mats Wichmann

On 2/23/23 22:16, Thomas Passin wrote:

On 2/23/2023 7:21 PM, Hen Hanna wrote:


in a LaTeX file,   after the (1st)   \end{document} line,
   i can put any random Junk i want    (afterwards)   until the 
end of the file.



Is there a similar Method  for a    .py file ?

Since i know of no such trick,  i sometimes put this (below) at the 
end of a .py file.




dummy= ("""  junk and more junk
   words in Dict
 239  words in Dict
 (((  notes or Code fragmetns  )))
  """ )



**    maybe i don't need the dummy= but it looks better.


You can just put it in triple quotes, no need to assign the string to a 
variable.  Or make each line a comment.




Indeed, I work on a project that by convention puts editor instructions 
at the end of each file (which some might consider junk :-) ), like this:



# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


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


Re: putting JUNK at the end of a [.py] file

2023-02-24 Thread Mats Wichmann

On 2/24/23 08:27, Mats Wichmann wrote:



Indeed, I work on a project that by convention puts editor instructions 
at the end of each file (which some might consider junk :-) ), like this:



# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


I should probably have added that I know the above is unnecessary, as 
there is now a standard for defining this stuff once, called 
EditorConfig, which many editors understand natively, and many more via 
plugins.


https://editorconfig.org/


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


Re: putting JUNK at the end of a [.py] file

2023-02-24 Thread Hen Hanna
On Thursday, February 23, 2023 at 9:17:05 PM UTC-8, Thomas Passin wrote:
> On 2/23/2023 7:21 PM, Hen Hanna wrote: 
> > 
> > in a LaTeX file, after the (1st) \end{document} line, 
> > i can put any random Junk i want (afterwards) until the end of the file. 
> > 
> > 
> > Is there a similar Method for a .py file ? 
> > 
> > Since i know of no such trick, i sometimes put this (below) at the end of a 
> > .py file. 
> > 
> > 
> > 
> > dummy= (""" junk and more junk 
> > words in Dict 
> > 239 words in Dict 
> > ((( notes or Code fragmetns ))) 
> >   """) 
> > 
> > 
> > 
> > ** maybe i don't need the  dummy=   but it looks better.


> You can just put it in triple quotes, no need to assign the string to a 
> variable. Or make each line a comment.


thanks for the   rare   concise comment   taht  also seems  devoid of insulting 
 attitude.

  (  i  still can't  tell one person from 
another, but
  i did notice that  one person 
sent me email 
that was  really long, 
insulting, and creepy )


i guess i  use("""   """)   because i wish   it  (this feature)   
came in matching pairs.

and   put dummy=to remind myselfand to  tell the compiler,  
 obivously  this Var is unused to feel free to ignore it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: putting JUNK at the end of a [.py] file

2023-02-24 Thread Loris Bennett
Hen Hanna  writes:

> in a LaTeX file,   after the (1st)   \end{document} line, 
>   i can put any random Junk i want(afterwards)   until the end of the 
> file.
>
>
> Is there a similar Method  for a.py file ?
>
> Since i know of no such trick,  i sometimes put this (below) at the end of a 
> .py file.
>
>
>
> dummy= ("""  junk and more junk
>   words in Dict
> 239  words in Dict
> (((  notes or Code fragmetns  )))
>  """ )
>
>
>
> **maybe i don't need the dummy= but it looks better.

Apropos looking better:

In my newsreader with a fixed-width font, I find your postings rather
hard to read as there is a lot of, for me, inexplicable white space.

Is there a particular reason why your postings are formatted like this?

Cheers,

Loris

-- 
This signature is currently under constuction.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: putting JUNK at the end of a [.py] file

2023-02-24 Thread Thomas Passin

On 2/24/2023 12:37 AM, Hen Hanna wrote:

On Thursday, February 23, 2023 at 9:17:05 PM UTC-8, Thomas Passin wrote:

On 2/23/2023 7:21 PM, Hen Hanna wrote:


in a LaTeX file, after the (1st) \end{document} line,
i can put any random Junk i want (afterwards) until the end of the file.


Is there a similar Method for a .py file ?

Since i know of no such trick, i sometimes put this (below) at the end of a .py 
file.



dummy= (""" junk and more junk
words in Dict
239 words in Dict
((( notes or Code fragmetns )))
   """)



** maybe i don't need the  dummy=   but it looks better.




You can just put it in triple quotes, no need to assign the string to a
variable. Or make each line a comment.



thanks for the   rare   concise comment   taht  also seems  devoid of insulting 
 attitude.

   (  i  still can't  tell one person from 
another, but
   i did notice that  one person 
sent me email
 that was  really long, 
insulting, and creepy )


i guess i  use("""   """)   because i wish   it  (this feature)   
came in matching pairs.

and   put dummy=to remind myselfand to  tell the compiler,  
 obivously  this Var is unused to feel free to ignore it.


The bare string will be evaluated but not assigned to any variable name. 
You don't need to tell the compiler anything.  As an example, here is a 
tiny program that runs:


"""A little test program to verify that a floating string is OK."""

MSG = 'this is a test'
print(MSG)

"""This is a free-floating message
that is just a note to myself.
"

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


terse

2023-02-24 Thread avi.e.gross
Greg,

I do not advocate for writing extremely concise python as mentioned in that
book although I was quite interested and do use some of the methods. 

But I worry about what you focused in on. Everyone says a picture is worth a
thousand words. So when writing about python one-liners, you might shorten
some programs even more with a nice illustration!

But if that is an obstacle, perhaps the edition below is less illustrative.

https://www.amazon.com/gp/product/B07ZY7XMX8

Just a reminder. My point was not about a book or set of techniques. It was
that lots of Python features can be used quite effectively to reduce the
need for more lines of cluttered code or places you may be tempted to use
semicolons. Having said that, guess what some one-liner techniques use?

In my view, terseness is not a goal in and of itself. However, it has often
been said that the number of bugs in code often seems correlated with the
number of lines and code written using higher levels of coordination and
abstraction in a language that supports that, can often be written with
fewer lines and apparently even with fewer bugs.

There is also a well-known set of phenomena about us humans in that many of
us are wired to handle fairly small amounts in memory at a time, such as
perhaps 7.  People who can do substantially better are often using an
assortment of tricks like clumping. I mean most people can remember a
10-digit phone number for a while because they may chunk it into
xxx-yyy-abcd or something like that where xxx is just remembered as one unit
as a complete area code while abcd is remembered as 4 individual digits.

So languages that allow and encourage not so much terseness as variations
like chunking, meaning using lots of smaller well-named functions, objects
that encapsulate what your program logic is, and yes, terse but easy to
understand ways of doing things like loops and functional programming
methods, and that are extended by modules or packages with a well-defined
interface, can let you focus on the program at higher levels that do fit in
your memory and can be reasoned more easily and accurately.

So some one-liners are great. Others not so much. Can you imagine a list
comprehension with a dozen or so nested loops on one long line, including
regions grouped in parentheses and lots of "if" clauses? It may be one line
that wraps on your screen into many or has to be scrolled sideways. Yes, you
can rewrite it split across many lines. But at some point, it may be better
to refactor it using a functional style or writing the loops out explicitly.

In my experience, some one-liners are accompanied by paragraphs of comments
explaining them. And often they use tricks that are less efficient.

Avi


-Original Message-
From: Python-list  On
Behalf Of Greg Ewing via Python-list
Sent: Friday, February 24, 2023 1:31 AM
To: [email protected]
Subject: Re: semi colonic

On 24/02/23 9:26 am, [email protected] wrote:
> Python One-Liners: Write Concise, Eloquent Python Like a Professional 
> Illustrated Edition by Christian Mayer (Author)

I didn't know there were any Professional Illustrated Editions writing
Pythom. You learn something every day! :-)

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

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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-22 15:46:09 -0800, Hen Hanna wrote:
> On Wednesday, February 22, 2023 at 12:05:34 PM UTC-8, Hen Hanna wrote:
> > > py bug.py 
> > Traceback (most recent call last): 
> > File "C:\Usenet\bug.py", line 5, in  
> > print( a + 12 ) 
> > TypeError: can only concatenate str (not "int") to str 
> > 
> > 
> > Why doesn't Python (error msg) do the obvious thing and tell me 
> > WHAT the actual (offending, arg) values are ? 
> > 
> > In many cases, it'd help to know what string the var A had , when the error 
> > occurred. 
> >  i wouldn't have to put print(a) just above, to see. 
> > 
> > ( pypy doesn't do that either, but Python makes programming
> > (debugging) so easy that i hardly feel any inconvenience.)

That seems like a non-sequitur to me. If you hardly feel any
inconvenience, why argue so forcefully?
And why is pypy relevant here?


> i  see that my example   would be clearER  with this one-line  change:
> 
> 
>   >  py   bug.py
> 
>Traceback (most recent call last):
> 
>   File "C:\Usenet\bug.py", line 5, in 
>  map( Func,fooBar(  X,  Y,  X +  
> Y  ))
>  
>TypeError: can only concatenate str (not "int") to str
> 
> 
> i hope that   NOW   a few of you  can  see this as a genuine,  (reasonable)  
> question.

That doesn't seem a better example to me. There is still only one
subexpression (X + Y) where that error can come from, so I know that X
is a str and Y is an int.

A better example would be something like 

x = (a + b) * (c + d)

In this case it could be either (a + b) or (c + d) which caused the
error. But what I really want to know here is the names of the involved
variables, NOT the values. If the error message told me that the values
were 'foo' and 12.3, I still wouldn't be any wiser. The problem here of
course is that the operands aren't necessarily simple variables as in
this example - they may be arbitrarily complex expressions. However, it
might be sufficient to mark the operator which caused the exception:

|   ...
|   File "/home/hjp/tmp/./foo", line 4, in f
| return (a + b) * (c + d)
| ^
| TypeError: can only concatenate str (not "int") to str

would tell me that (c + d) caused the problem and therefore that c must
be a str which it obviously shouldn't be.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-23 20:32:26 -0700, Michael Torrie wrote:
> On 2/23/23 01:08, Hen Hanna wrote:
> >  Python VM  is seeing an "int" object (123)   (and telling me that)
> >  ...   so it should be easy to print that "int" object What does
> >  Python VMknow ?   and when does it know it ?
> It knows there is an object and its name and type.  It knows this from
> the first moment you create the object and bind a name to it.
> > it seems like  it is being playful, teasing (or mean),and
> > hiding  the ball from me
> 
> Sorry you aren't understanding.  Whenever you print() out an object,
> python calls the object's __repr__() method to generate the string to
> display.  For built-in objects this is obviously trivial. But if you
> were dealing an object of some arbitrary class, there may not be a
> __repr__() method

Is this even possible? object has a __repr__ method, so all other
classes would inherit that if they don't define one themselves. I guess
it's possible to explicitely remove it ...

> which would cause an exception, or if the __repr__()
> method itself raised an exception,

Yup. That is possible and has happened to me several times - of course
always in a situation where I really needed that output ...

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
> In some ways, providing this information seems appropriate. Curiously, this
> does not even occur during an assert exception - despite the
> value/relationship being the whole point of using the command!
> 
> x = 1
> assert x == 2
> 
> AssertionError (and that's it)

Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 

platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py F 
  [100%]

= FAILURES 
==
__ test_a 
___

def test_a():
a = [1, 2, 3]
b = {"a": a, "b": 2}

>   assert len(a) == len(b)
E   AssertionError: assert 3 == 2
E+  where 3 = len([1, 2, 3])
E+  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==
FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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


Find 6-letter words that are hidden (embedded) within

2023-02-24 Thread Hen Hanna


  i just wrote a program,  which...
within[FunFunPython]  
   finds: (funny,futon,python)

 ( 5- and 6- letter words )


(my program uses a Trie, but is pretty simple)



Maybe someone would show me
how it's done usingitertools,   Permutations, etc.

 Wouldn't it get too slow for Letter-Seeds longer than 11 letters or so?


__
 
 Find   6-letter words that are hidden (embedded)  within each row of letters.
  The letters are in the correct order.
 
 1.JSOYOMFUBELR
 2.SCDUARWDRLYE
 3.DASNAGEFERTY
 4.CLULOOTSCEHN
 5.USENEARSEYNE
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Find 6-letter words that are hidden (embedded) within

2023-02-24 Thread Pancho via Python-list

On 24/02/2023 18:34, Hen Hanna wrote:


   i just wrote a program,  which...
 within[FunFunPython]
finds: (funny,futon,python)

  ( 5- and 6- letter words )


(my program uses a Trie, but is pretty simple)



Maybe someone would show me
 how it's done usingitertools,   Permutations, etc.

  Wouldn't it get too slow for Letter-Seeds longer than 11 letters or so?



For performance, generally you sort the characters in a word to create a 
new word (character list) and compare the sorted character lists (which 
you can use a string for). Two anagrams will produce the same sorted 
character list.


The problem with going through all permutations is that the number of 
permutations tends to grow exponentially, so that is why you sort first.


So first take an English dictionary and build a python dictionary with 
the key being the character sorted list and the value being a list of

the English words that produce the sorted list, aka anagrams.

You then sort your specific word and test each subset of this sorted 
word (each combination of characters) against your python anagram 
dictionary.


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread dn via Python-list

On 25/02/2023 08.12, Peter J. Holzer wrote:

On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:

In some ways, providing this information seems appropriate. Curiously, this
does not even occur during an assert exception - despite the
value/relationship being the whole point of using the command!

 x = 1
 assert x == 2

AssertionError (and that's it)


Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 

platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py F 
  [100%]

= FAILURES 
==
__ test_a 
___

 def test_a():
 a = [1, 2, 3]
 b = {"a": a, "b": 2}


   assert len(a) == len(b)

E   AssertionError: assert 3 == 2
E+  where 3 = len([1, 2, 3])
E+  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==
FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=


+1
and hence the tone of slight surprise in the observation - because only 
ever use assert within pytests, and as observed, pytest amplifies the 
report-back to provide actionable-intelligence. See also: earlier 
contribution about using a debugger.



That said, have observed coders 'graduating' from other languages, 
making wider use of assert - assumed to be more data (value) 
sanity-checks than typing, but ...


Do you use assert frequently?


The OP seems wedded to his?her ways, complaining that Python does not 
work the way it 'should'. In turn, gives rise to the impression that 
expounding the advantages of TDD, and thus anticipating such unit and 
integration error-possibilities, might be considered an insult or unhelpful.

(sigh!)

Personally, I struggled a bit to adapt from the more-strictured (if not 
more-structured) languages of my past, to Python - particularly the 
different philosophies or emphases of what happens at 'compile-time' cf 
'execution-time'; and how such required marked changes in attitudes to 
design, time-allocation, work-flow, and tool-set. Two related-activities 
which made the language-change more workable and unleashed greater than 
step-change advantage, were: increased use of TDD, and actively learning 
the facilities within Python-oriented IDEs.


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-25 08:47:00 +1300, dn via Python-list wrote:
> That said, have observed coders 'graduating' from other languages, making
> wider use of assert - assumed to be more data (value) sanity-checks than
> typing, but ...
> 
> Do you use assert frequently?

Not very often, but I do use it. Sometimes for its intended purpose
(i.e. to guard against bugs or wrong assumptions), sometimes just to
guard incomplete or sloppy code (e.g. browsing through some projects I
find
assert len(data["structure"]["dimensions"]["observation"]) == 1
(incomplete code - I didn't bother to implement multiple observations)
and
assert(header[0] == "Monat (MM)")
(the code below is sloppy. Instead of fixing it I just made the original
programmer's assumptions explicit)
and of course
assert False
(this point should never be reached)).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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


Re: Find 6-letter words that are hidden (embedded) within

2023-02-24 Thread Hen Hanna
On Friday, February 24, 2023 at 10:34:31 AM UTC-8, Hen Hanna wrote:
> i just wrote a program, which... 
>within [FunFunPython] 
>finds: (funny, futon, python) 
> 
>( 5- and 6- letter words ) 
> 
> 
> (my program uses a Trie, but is pretty simple) 
> 
> 
> 
> Maybe someone would show me 
>   how it's done using itertools, Permutations, etc. 
> 
> Wouldn't it get too slow for Letter-Seeds longer than 11 letters or so? 
> 
> 
> __ 
> 
> Find 6-letter words that are hidden (embedded) within each row of letters. 
> The letters are in the correct order. 
> 
> 1. JSOYOMFUBELR 
> 2. SCDUARWDRLYE 
> 3. DASNAGEFERTY 
> 4. CLULOOTSCEHN 
> 5. USENEARSEYNE



> The letters are in the correct order.  So this problem is not about 
> Anagraming.



it seems that 
https://docs.python.org/3/library/itertools.html
doesn't offer waht i want, so i wrote this (below) and it works.

   Is there a better or faster way to do the same thing?


def subs( x ): 
if x=='':   return  ['']
x1= subs( x[1:] )
return x1 + mapAdd(x[0] , x1)

def mapAdd( x, Ylis ):return [ x+y for y in Ylis ]

print( subs('ab' ))
print( subs('abc' ))
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: Find 6-letter words that are hidden (embedded) within

2023-02-24 Thread David Raymond
> Find 6-letter words that are hidden (embedded) within each row of letters. 
> The letters are in the correct order. 
> 
> 1. JSOYOMFUBELR 
> 2. SCDUARWDRLYE 
> 3. DASNAGEFERTY 
> 4. CLULOOTSCEHN 
> 5. USENEARSEYNE

> The letters are in the correct order.  So this problem is not about 
> Anagraming.


You can get every combination of 6 letters out of it with 
itertools.combinations like below.
Just implement the isWord function to return whether a string actually counts 
as a legit word or not.
12 choose 6 is only 924 combinations to check, so shouldn't be too bad to check 
them all.


def isWord(word):
return True #Best left as an exercise to the reader

startWord = "JSOYOMFUBELR"
subLetterCount = 6

foundWords = set()

for letters in itertools.combinations(startWord, subLetterCount):
word = "".join(letters)
if word not in foundWords and isWord(word):
print(word)
foundWords.add(word)
-- 
https://mail.python.org/mailman/listinfo/python-list


TypeError: can only concatenate str (not "int") to str

2023-02-24 Thread Hen Hanna
 TypeError: can only concatenate str (not "int") to str

thanks for the comments,  ---   esp. 2 or 3 (?) ppl  who  directly addressed it 
or commented on it.


py   and pypy  don't tell me what the (offending)  int   is  

   (even tho'  it'd be easy to show me the int, or 
number)

because  a Tuple, List... may produce  a long output and they don't want to 
deal with ways of abbreviating  it   (with ... )

and because  User-defined  Class object may cause another error while printing 
it.



_
  TypeError: can only join an iterable

Here too it'd help me   if  pypy (Jeannie)  could tell me what the offending 
data object is.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Line continuation and comments

2023-02-24 Thread Mark Bourne
Personally, I don't particularly like the way you have to put multiline 
strings on the far left (rather than aligned with the rest of the scope) 
to avoid getting spaces at the beginning of each line.  I find it makes 
it more difficult to see where the scope of the class/method/etc. 
actually ends, especially if there are multiple such strings.  It's not 
too bad for strings defined at the module level (outer scope) though, 
and of course for docstrings the extra spaces at the beginning of each 
line don't matter.


However, rather than using "+" to join strings as in your examples 
(which, as you suggest, is probably less efficient), I tend to use 
string literal concatenation which I gather is more efficient (treated 
as a single string at compile-time rather than joining separate strings 
at run-time).  See 
.


For example:
  HelpText = ("Left click: Open spam\n"
  "Shift + Left click: Cook spam\n"
  "Right click:Crack egg\n"
  "Shift + Right click:Fry egg\n")

The downside is having to put an explicit "\n" at the end of each line, 
but to me that's not as bad as having to align the content to the far left.


Getting a bit more on topic, use of backslashes in strings is a bit 
different to backslashes for line continuation anyway.  You could almost 
think of "\
(newline)" in a multiline string as being like an escape sequence 
meaning "don't actually put a newline character in the string here", in 
a similar way to "\n" meaning "put a newline character here" and "\t" 
meaning "put a tab character here".


Mark.


[email protected] wrote:

Good example, Rob, of how some people make what I consider RELIGIOUS edicts 
that one can easily violate if one wishes and it makes lots of sense in your 
example.

Let me extend that. The goal was to store a character string consisting of 
multiple lines when printed that are all left-aligned. Had you written:

  HelpText = """
Left click: Open spam
...
Shift + Right click:Fry egg
"""
Then it would begin with an extra carriage return you did not want. Your 
example also ends with a carriage return because you closed the quotes on 
another line, so a \ on the last line of text (or moving the quotes to the end 
of the line) would be a way of avoiding that.

Consider some alternatives I have seen that are in a sense ugly and may involve 
extra work for the interpreter unless it is byte compiled once.

def someFunc():
  HelpText =
  "Left click: Open spam" + "\n" +
  "Shift + Left click: Cook spam" + "\n" +
  ...

Or the variant of:
HelpText =  "Left click: Open spam\n"
HelpText +=  " Shift + Left click: Cook spam\n"
...

Or perhaps just dumping the multi-line text into a file beforehand and reading 
that into a string!

def someFunc():

The backslash is not looking like such a bad idea! LOL!

-Original Message-
From: Python-list  On 
Behalf Of Rob Cliffe via Python-list
Sent: Wednesday, February 22, 2023 2:08 PM
To: [email protected]
Subject: Re: Line continuation and comments



On 22/02/2023 15:23, Paul Bryan wrote:

Adding to this, there should be no reason now in recent versions of
Python to ever use line continuation. Black goes so far as to state
"backslashes are bad and should never be used":

https://black.readthedocs.io/en/stable/the_black_code_style/future_sty
le.html#using-backslashes-for-with-statements


def someFunc():
  HelpText = """\
Left click: Open spam
Shift + Left click: Cook spam
Right click:Crack egg
Shift + Right click:Fry egg
"""

The initial backslash aligns the first line with the others (in a fixed font of 
course).
Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list


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


Re: Line continuation and comments

2023-02-24 Thread Roel Schroeven

Mark Bourne schreef op 24/02/2023 om 22:04:

Personally, I don't particularly like the way you have to put multiline
strings on the far left (rather than aligned with the rest of the scope)
to avoid getting spaces at the beginning of each line.  I find it makes
it more difficult to see where the scope of the class/method/etc.
actually ends, especially if there are multiple such strings.  It's not
too bad for strings defined at the module level (outer scope) though,
and of course for docstrings the extra spaces at the beginning of each
line don't matter.
A way around this is using textwrap.dedent() 
(https://docs.python.org/3.10/library/textwrap.html?highlight=dedent#textwrap.dedent). 
Example from the documentation:


    def test():
    # end first line with \ to avoid the empty line!
    s = '''\
    hello
  world
    '''
    print(repr(s))  # prints '    hello\n world\n    '
    print(repr(dedent(s)))  # prints 'hello\n  world\n'


--
"Met een spitsvondig citaat bewijs je niets."
-- Voltaire

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


Evaluate once or every time

2023-02-24 Thread avi.e.gross
Mark,

I was very interested in the point you made and have never thought much about 
string concatenation this way but adjacency is an operator worth using.

This message has a new subject line as it is not about line continuation or 
comments.

From what you say, concatenation between visibly adjacent strings is done once 
when generating bytecode. Using a plus is supposed to be about the same but may 
indeed result in either an error if you use anything other than a string literal

bad = "hello " str(12)

or you must use something like a "+" to do the concatenation at each run time. 
Or, weirder, do it manually as : 

good = "hello ".__add__(str(12))

This may be no big deal in terms of efficiency but something to consider.

I have often stared in amazement at code like:

>>> mylist = "The quick brown fox jumps over the lazy dog".split()

>>> mylist
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

Or perhaps to make a list of vowels:

import string

vowels = list("aeiouAEIOU")
consonants = sorted(list(set(string.ascii_letters) - set(vowels)))

I mean couldn't you do this work in advance and do something like:

vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 
'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']

I assume this latter version would be set once no matter how often you run the 
unchanged program. YES, I am aware this may be bad practice for code you want 
to adapt for international use. 

But why be wasteful? I am currently reading a book on refactoring and will not 
share if it is illustrated, or if the above is a decent example as the book 
uses examples in JavaScript. 😉



-Original Message-
From: Python-list  On 
Behalf Of Mark Bourne
Sent: Friday, February 24, 2023 4:04 PM
To: [email protected]
Subject: Re: Line continuation and comments

Personally, I don't particularly like the way you have to put multiline strings 
on the far left (rather than aligned with the rest of the scope) to avoid 
getting spaces at the beginning of each line.  I find it makes it more 
difficult to see where the scope of the class/method/etc. 
actually ends, especially if there are multiple such strings.  It's not too bad 
for strings defined at the module level (outer scope) though, and of course for 
docstrings the extra spaces at the beginning of each line don't matter.

However, rather than using "+" to join strings as in your examples (which, as 
you suggest, is probably less efficient), I tend to use string literal 
concatenation which I gather is more efficient (treated as a single string at 
compile-time rather than joining separate strings at run-time).  See 
.

For example:
   HelpText = ("Left click: Open spam\n"
   "Shift + Left click: Cook spam\n"
   "Right click:Crack egg\n"
   "Shift + Right click:Fry egg\n")

The downside is having to put an explicit "\n" at the end of each line, but to 
me that's not as bad as having to align the content to the far left.

Getting a bit more on topic, use of backslashes in strings is a bit different 
to backslashes for line continuation anyway.  You could almost think of "\ 
(newline)" in a multiline string as being like an escape sequence meaning 
"don't actually put a newline character in the string here", in a similar way 
to "\n" meaning "put a newline character here" and "\t" 
meaning "put a tab character here".

Mark.


[email protected] wrote:
> Good example, Rob, of how some people make what I consider RELIGIOUS edicts 
> that one can easily violate if one wishes and it makes lots of sense in your 
> example.
> 
> Let me extend that. The goal was to store a character string consisting of 
> multiple lines when printed that are all left-aligned. Had you written:
> 
>   HelpText = """
> Left click: Open spam
> ...
> Shift + Right click:Fry egg
> """
> Then it would begin with an extra carriage return you did not want. Your 
> example also ends with a carriage return because you closed the quotes on 
> another line, so a \ on the last line of text (or moving the quotes to the 
> end of the line) would be a way of avoiding that.
> 
> Consider some alternatives I have seen that are in a sense ugly and may 
> involve extra work for the interpreter unless it is byte compiled once.
> 
> def someFunc():
>   HelpText =
>   "Left click: Open spam" + "\n" +
>   "Shift + Left click: Cook spam" + "\n" +
>   ...
> 
> Or the variant of:
> HelpText =  "Left click: Open spam\n"
> HelpText +=  " Shift + Left click: Cook spam\n"
> ...
> 
> Or perhaps just dumping the multi-line text into a file beforehand and 
> read

Re: Evaluate once or every time

2023-02-24 Thread Chris Angelico
On Sat, 25 Feb 2023 at 09:36,  wrote:
> From what you say, concatenation between visibly adjacent strings is done 
> once when generating bytecode. Using a plus is supposed to be about the same 
> but may indeed result in either an error if you use anything other than a 
> string literal
>
> bad = "hello " str(12)
>
> or you must use something like a "+" to do the concatenation at each run 
> time. Or, weirder, do it manually as :
>

Abuttal is a syntactic feature. It's completely different from string
concatenation. The only similarity is that some forms of addition may
be constant-folded.

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


Re: Not receiving posts

2023-02-24 Thread Mats Wichmann

On 2/23/23 13:56, Grant Edwards wrote:

On 2023-02-23, Jim Byrnes  wrote:


I have been reading the python-list for some time now. At first via
gemane and since it's demise via a subscription.


FWIW, gmane is still there, and still working fine. I read this list
by pointing slrn at news.gmane.io


Well gmane did die, and caused changes and the story is weird even by 
internet standards.  And the founder eventually spilled


https://lars.ingebrigtsen.no/2020/01/06/whatever-happened-to-news-gmane-org/

Not everything came back the same.

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


Re: Line continuation and comments

2023-02-24 Thread dn via Python-list

On 25/02/2023 10.04, Mark Bourne wrote:
Personally, I don't particularly like the way you have to put multiline 
strings on the far left (rather than aligned with the rest of the scope) 
to avoid getting spaces at the beginning of each line.  I find it makes 
it more difficult to see where the scope of the class/method/etc. 
actually ends, especially if there are multiple such strings.  It's not 
too bad for strings defined at the module level (outer scope) though, 
and of course for docstrings the extra spaces at the beginning of each 
line don't matter.


However, rather than using "+" to join strings as in your examples 
(which, as you suggest, is probably less efficient), I tend to use 
string literal concatenation which I gather is more efficient (treated 
as a single string at compile-time rather than joining separate strings 
at run-time).  See 
.


For example:
   HelpText = ("Left click: Open spam\n"
   "Shift + Left click: Cook spam\n"
   "Right click:    Crack egg\n"
   "Shift + Right click:    Fry egg\n")

The downside is having to put an explicit "\n" at the end of each line, 
but to me that's not as bad as having to align the content to the far left.


S\Possible solution to that:

HelpText = "\n".join( ["Left click: Open spam",
...   "Shift + Left click: Cook spam",
...   "Right click:Crack egg",
...   "Shift + Right click:Fry egg"
...   ]
...   )

To PEP-008 Police:
Apologies for formatting - was working from original example

In this manner, the sub-strings may be placed wherever you see fit, and 
those pesky line-endings no-longer contribute to visual clutter (but 
maybe the brackets do...)


Another philosophy is to move awkward strings, such as the examples in 
this thread, 'out' of the mainline code and into a config-file (of sorts).


The PEP-008 Police are more likely to ignore transgressions in a 
'data-file' during code-review. So, you can format the code in whatever 
fashion you like...



Text for GUIs, report print-outs, etc, tends to be at the (tender) mercy 
of (opinionated) users. By putting such into a separate file, such 
changes can be made without (as much) risk of 'breaking' the code 
itself. Ultimately, if you ever have to expand the application to 
multi-tenancy, such will become necessary.


Using a separate file, you can consider if should write such as Python 
(import module) or use something else like JSON, YAML, ...

(and may God bless all who sail in her...).

YMMV!


Getting a bit more on topic, use of backslashes in strings is a bit 
different to backslashes for line continuation anyway.  You could almost 
think of "\
(newline)" in a multiline string as being like an escape sequence 
meaning "don't actually put a newline character in the string here", in 
a similar way to "\n" meaning "put a newline character here" and "\t" 
meaning "put a tab character here".


Book title: "Don't Make Me Think"
(thoroughly recommended. Author: Steve Krug)

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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Thomas Passin

On 2/24/2023 2:47 PM, dn via Python-list wrote:

On 25/02/2023 08.12, Peter J. Holzer wrote:

On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
In some ways, providing this information seems appropriate. 
Curiously, this

does not even occur during an assert exception - despite the
value/relationship being the whole point of using the command!

 x = 1
 assert x == 2

AssertionError (and that's it)


Sometimes you can use a second parameter to assert if you know what kind 
of error to expect:


>>> a = [1,2,3]
>>> b = [4,5]
>>> assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: len(a): 3 != len(b): 2

With type errors, assert may actually give you the information needed:

>>> c = {"a": a, "b": 2}
>>> assert a > c
Traceback (most recent call last):
  File "", line 1, in 
TypeError: '>' not supported between instances of 'list' and 'dict'

So now we know that a is a list and c is a dictionary.


Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 


platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py 
F   [100%]


= FAILURES 
==
__ test_a 
___


 def test_a():
 a = [1, 2, 3]
 b = {"a": a, "b": 2}


   assert len(a) == len(b)

E   AssertionError: assert 3 == 2
E    +  where 3 = len([1, 2, 3])
E    +  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==

FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=


+1
and hence the tone of slight surprise in the observation - because only 
ever use assert within pytests, and as observed, pytest amplifies the 
report-back to provide actionable-intelligence. See also: earlier 
contribution about using a debugger.



That said, have observed coders 'graduating' from other languages, 
making wider use of assert - assumed to be more data (value) 
sanity-checks than typing, but ...


Do you use assert frequently?


The OP seems wedded to his?her ways, complaining that Python does not 
work the way it 'should'. In turn, gives rise to the impression that 
expounding the advantages of TDD, and thus anticipating such unit and 
integration error-possibilities, might be considered an insult or 
unhelpful.

(sigh!)

Personally, I struggled a bit to adapt from the more-strictured (if not 
more-structured) languages of my past, to Python - particularly the 
different philosophies or emphases of what happens at 'compile-time' cf 
'execution-time'; and how such required marked changes in attitudes to 
design, time-allocation, work-flow, and tool-set. Two related-activities 
which made the language-change more workable and unleashed greater than 
step-change advantage, were: increased use of TDD, and actively learning 
the facilities within Python-oriented IDEs.




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


Re: Evaluate once or every time

2023-02-24 Thread Thomas Passin

On 2/24/2023 5:35 PM, [email protected] wrote:

Mark,

I was very interested in the point you made and have never thought much about 
string concatenation this way but adjacency is an operator worth using.

This message has a new subject line as it is not about line continuation or 
comments.

 From what you say, concatenation between visibly adjacent strings is done once 
when generating bytecode. Using a plus is supposed to be about the same but may 
indeed result in either an error if you use anything other than a string literal

bad = "hello " str(12)

or you must use something like a "+" to do the concatenation at each run time. 
Or, weirder, do it manually as :

good = "hello ".__add__(str(12))

This may be no big deal in terms of efficiency but something to consider.

I have often stared in amazement at code like:


mylist = "The quick brown fox jumps over the lazy dog".split()



mylist

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']


Why be amazed? The .split() version is way easier to type.  I do it all 
the time.  Usually these evaluations will be done only once, at compile 
time, so the cost in computing time is usually not important.  And, if 
you get right down to it, the first form is actually what you mean.  The 
second form is an implementation detail (you need to feed a list of 
words into a function).



Or perhaps to make a list of vowels:

import string

vowels = list("aeiouAEIOU")
consonants = sorted(list(set(string.ascii_letters) - set(vowels)))

I mean couldn't you do this work in advance and do something like:

vowels = ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']
consonants = ['B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 
'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 
'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']


I don't want to have to type these monsters, and in this form I'd be 
prone to making an error.  And they are hard to proofread.  Anyway, a 
list like this is typically used to assess whether a character is in one 
or the other group, and you can do it without turning the string into a 
list of characters:


VOWELS = 'aeiouAEIOU'
is_vowel = 'y' in VOWELS

If I really needed them to be in a list, I'd probably do a list 
comprehension:


VOWEL_LIST = [ch for ch in VOWELS]

Again, much easier to type and to read, closer to what is really meant, 
and less error-prone.


In the case of the consonants, even in string form it would be hard to 
proofread, so I'd be inclined to insert spaces for readability:


CONSONANTS = 'BCDFGH JKLMNP QRSTVWX YZ bcdfgh jklmnp qrstvwx yz'

If for some reason spaces wouldn't work, I'd delete them:
CONSONANTS  = CONSONANTS.replace(' ', '')

In concept this isn't much different from using the C pre-processor to 
pre-compute some things for you.




I assume this latter version would be set once no matter how often you run the 
unchanged program. YES, I am aware this may be bad practice for code you want 
to adapt for international use.

But why be wasteful? I am currently reading a book on refactoring and will not 
share if it is illustrated, or if the above is a decent example as the book 
uses examples in JavaScript. 😉


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


Re: Not receiving posts

2023-02-24 Thread Grant Edwards
On 2023-02-24, Mats Wichmann  wrote:
> On 2/23/23 13:56, Grant Edwards wrote:
>> On 2023-02-23, Jim Byrnes  wrote:
>> 
>>> I have been reading the python-list for some time now. At first via
>>> gemane and since it's demise via a subscription.
>> 
>> FWIW, gmane is still there, and still working fine. I read this list
>> by pointing slrn at news.gmane.io
>
> Well gmane did die, and caused changes and the story is weird even by 
> internet standards.  And the founder eventually spilled
>
> https://lars.ingebrigtsen.no/2020/01/06/whatever-happened-to-news-gmane-org/

Interesting! I had seen less detailed versions of that story
elsewhere, but never saw that.

> Not everything came back the same.

I do sometimes miss the old webUI. The search function was useful, and
it was a handy place to point people to when you wanted to reference
an old mailing list posting. But, I certainly don't have the time and
skills to re-create it, so I've got absolutely no right to complain.

After setting up and maintaining gmane.org for all those years,
there's no way Mr. Ingebrigtsen's positive karma balance has been
noticably reduced by the bumpy transition that resulted in gmane.io.



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


Re: Find 6-letter words that are hidden (embedded) within

2023-02-24 Thread Hen Hanna
On Friday, February 24, 2023 at 1:18:28 PM UTC-8, David Raymond wrote:
> > Find 6-letter words that are hidden (embedded) within each row of letters. 
> > The letters are in the correct order. 
> > 
> > 1. JSOYOMFUBELR 
> > 2. SCDUARWDRLYE 
> > 3. DASNAGEFERTY 
> > 4. CLULOOTSCEHN 
> > 5. USENEARSEYNE 
> 
> > The letters are in the correct order.  So this problem is not about 
> > Anagraming.
> You can get every combination of 6 letters out of it with 
> itertools.combinations like below. 
> Just implement the isWord function to return whether a string actually counts 
> as a legit word or not. 
> 12 choose 6 is only 924 combinations to check, so shouldn't be too bad to 
> check them all. 
> 
> 
> def isWord(word): 
> return True #Best left as an exercise to the reader 
> 
> startWord = "JSOYOMFUBELR" 
> subLetterCount = 6 
> 
> foundWords = set() 
> 
> for letters in itertools.combinations(startWord, subLetterCount): 
> word = "".join(letters) 
> if word not in foundWords and isWord(word): 
> print(word) 
> foundWords.add(word)



   thank you...  i could use the Pset below, too.


# Factorial Python One-Liner
def fac(n):   return   reduce(lambda x, y: x * y, range(1, n+1))

for i in range(1,11):print ( '\t', fac(i) )


# Power set Python One-Liner
def Pset(L):  returnreduce(lambda z, x: z + [y + [x] for y in z], 
L, [[]])

print( '\n',   Pset( [1,] ))
print( '\n',   Pset( [1,2,] ))
print( '\n',   Pset( [1,2,3] ))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Evaluate once or every time

2023-02-24 Thread 2QdxY4RzWzUUiLuE
On 2023-02-24 at 18:42:39 -0500,
Thomas Passin  wrote:

> VOWELS = 'aeiouAEIOU'
> is_vowel = 'y' in VOWELS
> 
> If I really needed them to be in a list, I'd probably do a list
> comprehension:
> 
> VOWEL_LIST = [ch for ch in VOWELS]

Why use a comprehension when a simple loop will do?  ;-)

No.  Wait.  That's not what I meant.

Why use a comprehension when the constructor will do?

VOWEL_LIST = list(VOWELS)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Evaluate once or every time

2023-02-24 Thread Thomas Passin

On 2/24/2023 7:00 PM, [email protected] wrote:

On 2023-02-24 at 18:42:39 -0500,
Thomas Passin  wrote:


VOWELS = 'aeiouAEIOU'
is_vowel = 'y' in VOWELS

If I really needed them to be in a list, I'd probably do a list
comprehension:

VOWEL_LIST = [ch for ch in VOWELS]


Why use a comprehension when a simple loop will do?  ;-)

No.  Wait.  That's not what I meant.

Why use a comprehension when the constructor will do?

VOWEL_LIST = list(VOWELS)


It just didn't occur to me, I think, that this would create a list of 
the string's characters.  Very nice!


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


Re: TypeError: can only concatenate str (not "int") to str

2023-02-24 Thread dn via Python-list

On 25/02/2023 09.36, Hen Hanna wrote:

  TypeError: can only concatenate str (not "int") to str

thanks for the comments,  ---   esp. 2 or 3 (?) ppl  who  directly addressed it 
or commented on it.


If you haven't already, please review the Python Software Foundation's 
Code of Conduct https://www.python.org/psf/conduct/




py   and pypy  don't tell me what the (offending)  int   is

(even tho'  it'd be easy to show me the int, or 
number)

because  a Tuple, List... may produce  a long output and they don't want to 
deal with ways of abbreviating  it   (with ... )

and because  User-defined  Class object may cause another error while printing 
it.



_
   TypeError: can only join an iterable

Here too it'd help me   if  pypy (Jeannie)  could tell me what the offending 
data object is.


Observation:
- python doesn't tell you what you want
- correspondents are not telling you what you want and/or how you want
There's a common theme developing...

Suggestion: if you want help, and at the frequency with which you've 
been posting recently, would it be better not to sound like a 'troll'?



Please understand everyone here is volunteering time, in a bid to 
provide you (and each-other) with benefit.


Does the FACT that you have failed to answer several questions from 
colleagues really entitle you to demand others only directly-address you 
(and only your questions)?


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:
> On 2/24/2023 2:47 PM, dn via Python-list wrote:
> > On 25/02/2023 08.12, Peter J. Holzer wrote:
> > > On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
> > > > In some ways, providing this information seems appropriate.
> > > > Curiously, this does not even occur during an assert exception -
> > > > despite the value/relationship being the whole point of using
> > > > the command!
> > > > 
> > > >  x = 1
> > > >  assert x == 2
> > > > 
> > > > AssertionError (and that's it)
> 
> Sometimes you can use a second parameter to assert if you know what kind of
> error to expect:
> 
> >>> a = [1,2,3]
> >>> b = [4,5]
> >>> assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'
> Traceback (most recent call last):
>   File "", line 1, in 
> AssertionError: len(a): 3 != len(b): 2

Yup. That's very useful (but I tend to forget that).


> With type errors, assert may actually give you the information needed:
> 
> >>> c = {"a": a, "b": 2}
> >>> assert a > c
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: '>' not supported between instances of 'list' and 'dict'

Actually in this case it isn't assert which gives you the information,
it's evaluating the expression itself. You get the same error with just
a > c
on a line by its own.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | [email protected] |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


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