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 Weatherby,Gerard
PEP 8 doesn’t explicitly list a naming convention for function parameters, but 
every example shows them as lowercase, even though the function doesn’t modify 
them.

See also the Python tutorial ( 
https://docs.python.org/3/tutorial/controlflow.html#defining-functions ), which 
also shows all parameters as lowercase.

I’d personally find it weird to see an all-cap parameter (Why are you 
yelling?). I expect ALL_CAPS to be hardcoded values.



From: Python-list  on 
behalf of dn 
Date: Friday, November 11, 2022 at 3:56 AM
To: 'Python' 
Subject: Argument name should be lowercase
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

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://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!h56Cia7ERYDmxaCnEo0k9hfXz-mTJrz43UqHjbfhwLjutjhQE1QU975lUXTBf38la5kXAkBHdzyzOY4XAObbAPOa-ebC-HNY$
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Argument name should be lowercase

2022-11-11 Thread Thomas Passin
This is a matter of convention.  Historically, many language 
practitioners got used to using all-caps for key constants.  This makes 
it easier to tell when you are using (or misusing) one, for one thing.


For myself, I also will use all-caps for quasi-constants, ones that are 
set only once, for example from command-line parameters.


In your example,I would not use all-caps for the formal parameter in the 
function  definition.  I would have written


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

There is no value in making a formal parameter's name be all-caps, since 
even if it were the same string as an actual global parameter, it would 
not mean that actual parameter: it is only a placeholder.  There could 
even be a negative consequence, because later you might forget and think 
that the formal parameter's name meant that the global parameter would 
be used automatically in the function call, as if it were a default 
parameter.  At a minimum, this could lead to confusion about your 
intent, at a maximum it could end up being a bug.


Perhaps you wrote it that way as a reminder which dict to use.  If so, 
that kind of information would better go into the docstring:


def build_product_prices_dictionary(workbook_definitions:dict) -> dict:
"""Return a dictionary of product prices given their definitions.

ARGUMENT
workbook_definitions -- a dict of product definitions, typically
the global WORKBOOK_DEFINITIONS.
"""
# ...

Alternatively, you could make the global be the default for the argument:

def build_product_prices_dictionary(workbook_definitions:dict =
WORKBOOK_DEFINITIONS)->dict:

This might or might not make sense depending on how you plan to use the 
function.


So basically, PyCharm is suggesting that you use a clearer, less 
problem-prone style of naming.  I'd heed the advice.  It would also be 
in line with what many other programmers are used to reading, and that's 
a positive advantage.


On 11/11/2022 3:54 AM, 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)



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!



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


Re: Argument name should be lowercase

2022-11-11 Thread MRAB

On 2022-11-11 08:54, dn wrote:
[snip]


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)


[snip]
I think the problem is that the dict _is_ mutable, so it's not a 
constant; it's read-only, which is not the same thing.

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


Superclass static method name from subclass

2022-11-11 Thread Ian Pilcher

Is it possible to access the name of a superclass static method, when
defining a subclass attribute, without specifically naming the super-
class?

Contrived example:

  class SuperClass(object):
  @staticmethod
  def foo():
  pass

  class SubClass(SuperClass):
  bar = SuperClass.foo
^^

Is there a way to do this without specifically naming 'SuperClass'?

--

Google  Where SkyNet meets Idiocracy

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


Re: Argument name should be lowercase

2022-11-11 Thread Weatherby,Gerard
If you wanted to document/enforce the input argument is immutable, you could do 
one of the following. You’d get a type warning in PyCharm with bad_func or 
equivalent, and bad_func2 will fail at runtime.

def bad_func(x: typing.Mapping):
"""Get type warning if x modified"""
x[3] = 7


def bad_func2(x: types.MappingProxyType):
"""Get runtime error if x modified"""
if not isinstance(x, types.MappingProxyType):
x = types.MappingProxyType(x)
x[3] = 8


From: Python-list  on 
behalf of dn 
Date: Friday, November 11, 2022 at 3:56 AM
To: 'Python' 
Subject: Argument name should be lowercase
*** Attention: This is an external email. Use caution responding, opening 
attachments or clicking on links. ***

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://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!h56Cia7ERYDmxaCnEo0k9hfXz-mTJrz43UqHjbfhwLjutjhQE1QU975lUXTBf38la5kXAkBHdzyzOY4XAObbAPOa-ebC-HNY$
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Superclass static method name from subclass

2022-11-11 Thread Lars Liedtke

yes,

just use SubClass.foo

at least this works for me:

class SuperClass:
   @staticmethod
   def test():
   print("yay")

class SubClass(SuperClass):

   def __init__(self):
   super().__init__()
   SubClass.test()

subclass = SubClass()

Output:

python3.11 test.py
yay


Cheers

Lars


Lars Liedtke
Software Entwickler

[Tel.]  +49 721 98993-
[Fax]   +49 721 98993-
[E-Mail]l...@solute.de


solute GmbH
Zeppelinstraße 15
76185 Karlsruhe
Germany


[Logo Solute]


Marken der solute GmbH | brands of solute GmbH
[Marken]
[Advertising Partner]

Geschäftsführer | Managing Director: Dr. Thilo Gans, Bernd Vermaaten
Webseite | www.solute.de 
Sitz | Registered Office: Karlsruhe
Registergericht | Register Court: Amtsgericht Mannheim
Registernummer | Register No.: HRB 110579
USt-ID | VAT ID: DE234663798



Informationen zum Datenschutz | Information about privacy policy
https://www.solute.de/ger/datenschutz/grundsaetze-der-datenverarbeitung.php




Am 11.11.22 um 17:21 schrieb Ian Pilcher:
Is it possible to access the name of a superclass static method, when
defining a subclass attribute, without specifically naming the super-
class?

Contrived example:

 class SuperClass(object):
 @staticmethod
 def foo():
 pass

 class SubClass(SuperClass):
 bar = SuperClass.foo
   ^^

Is there a way to do this without specifically naming 'SuperClass'?

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


Re: Superclass static method name from subclass

2022-11-11 Thread Thomas Passin

You can define a classmethod in SubClass that seems to do the job:

class SuperClass(object):
  @staticmethod
  def spam():  # "spam" and "eggs" are a Python tradition
  print('spam from SuperClass')

class SubClass(SuperClass):
@classmethod
def eggs(self):
super().spam()

SubClass.eggs()  # Prints "spam from SuperClass"

If you try to make it a @staticmethod, though, you would need to provide 
a class argument to super(), but a staticmethod does not pass one in.


On 11/11/2022 11:21 AM, Ian Pilcher wrote:

Is it possible to access the name of a superclass static method, when
defining a subclass attribute, without specifically naming the super-
class?

Contrived example:

   class SuperClass(object):
   @staticmethod
   def foo():
   pass

   class SubClass(SuperClass):
   bar = SuperClass.foo
     ^^

Is there a way to do this without specifically naming 'SuperClass'?



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


Re: Superclass static method name from subclass

2022-11-11 Thread Dieter Maurer
Ian Pilcher wrote at 2022-11-11 10:21 -0600:
>Is it possible to access the name of a superclass static method, when
>defining a subclass attribute, without specifically naming the super-
>class?
>
>Contrived example:
>
>   class SuperClass(object):
>   @staticmethod
>   def foo():
>   pass
>
>   class SubClass(SuperClass):
>   bar = SuperClass.foo
> ^^
>
>Is there a way to do this without specifically naming 'SuperClass'?

Unless you overrode it, you can use `self.foo` or `SubClass.foo`;
if you overrode it (and you are using either Python 3 or
Python 2 and a so called "new style class"), you can use `super`.
When you use `super` outside a method definition, you must
call it with parameters.
-- 
https://mail.python.org/mailman/listinfo/python-list


Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread Jessica Smith
Hello,

Weird issue I've found on Windows images in Azure Devops Pipelines and
Github actions. Printing Unicode characters fails on these images because,
for some reason, the encoding is mapped to cp1252. What is particularly
weird about the code page being set to 1252 is that if you execute "chcp"
it shows that the code page is 65001.

At the end of this email are the cleaned up logs from GH actions. The
actions are very simple - print out unicode characters using echo to prove
the characters can be printed to the console. The rest of the commands are
in Python, and they include printing out the "encoding" variable of
sys.stdout, as well as printing sys.flags and sys.getfilesystemencoding.
Then print the same unicode character using print, which causes a
UnicodEncodeError because the character isn't in the cp1252 charmap.

I've also uploaded the logs to pastebin here: https://pastebin.com/ExzGRHav
I also uploaded a screenshot to imgur, since the logs are not the easiest
to read. https://imgur.com/a/dhvLWOJ

I'm trying to determine why this issue only happens on these images - I can
replicate it on multiple versions of Python (from 3.9 to 3.7 at least,
haven't tried more), but I can't replicate this on my own machines.

There are a few issues on GH regarding this issue but they seem to stay
open since they are hard to replicate. Here are the ones I have stumbled
upon while researching this.

https://github.com/databrickslabs/dbx/issues/455
https://github.com/PrefectHQ/prefect/issues/5754
https://github.com/pallets/click/issues/2121

Any insight or ideas on how to test and validate the cause would be great.
I'm pulling my hair out trying to find the root cause of this - not because
it really matters to any of my processes but because it is weird and broken.

Thanks for any help,

Jessica

Begin Logs:

2022-11-10T23:54:51.7272453Z Requested labels: windows-latest
2022-11-10T23:54:51.7272494Z Job defined at:
NodeJSmith/wsl_home/.github/workflows/blank.yml@refs/heads/main
2022-11-10T23:54:51.7272514Z Waiting for a runner to pick up this job...
2022-11-10T23:54:52.3387510Z Job is waiting for a hosted runner to come
online.
2022-11-10T23:55:04.8574435Z Job is about to start running on the hosted
runner: Hosted Agent (hosted)
2022-11-10T23:55:15.8332600Z Current runner version: '2.298.2'

2022-11-10T23:55:15.8366947Z ##[group]Operating System
2022-11-10T23:55:15.8367650Z Microsoft Windows Server 2022
2022-11-10T23:55:15.8367954Z 10.0.20348
2022-11-10T23:55:15.8368389Z Datacenter
2022-11-10T23:55:15.8368696Z ##[endgroup]

2022-11-10T23:55:15.8369023Z ##[group]Runner Image
2022-11-10T23:55:15.8369654Z Image: windows-2022
2022-11-10T23:55:15.8369931Z Version: 20221027.1
2022-11-10T23:55:15.8370539Z Included Software:
https://github.com/actions/runner-images/blob/win22/20221027.1/images/win/Windows2022-Readme.md
2022-11-10T23:55:15.8371174Z Image Release:
https://github.com/actions/runner-images/releases/tag/win22%2F20221027.1
2022-11-10T23:55:15.8371622Z ##[endgroup]

2022-11-10T23:55:15.8371955Z ##[group]Runner Image Provisioner
2022-11-10T23:55:15.8372277Z 2.0.91.1
2022-11-10T23:55:15.8372514Z ##[endgroup]

2022-11-10T23:55:16.3619998Z ##[group]Run echo  " └── ID:"
2022-11-10T23:55:16.3620626Z echo  " └── ID:"
2022-11-10T23:55:16.3927292Z shell: C:\Program Files\PowerShell\7\pwsh.EXE
-command ". '{0}'"
2022-11-10T23:55:16.3927894Z ##[endgroup]
2022-11-10T23:55:32.9958751Z  └── ID:

2022-11-10T23:55:34.0835652Z ##[group]Run chcp
2022-11-10T23:55:34.0836104Z chcp
2022-11-10T23:55:34.0878901Z shell: C:\Program Files\PowerShell\7\pwsh.EXE
-command ". '{0}'"
2022-11-10T23:55:34.0879350Z ##[endgroup]
2022-11-10T23:55:34.4878247Z Active code page: 65001

2022-11-10T23:55:34.7917219Z ##[group]Run python -c "import sys;
print('sys.stdout.encoding', sys.stdout.encoding);
print('sys.flags',sys.flags);print('sys.getfilesystemencoding',sys.getfilesystemencoding())"
2022-11-10T23:55:34.7918148Z python -c "import sys;
print('sys.stdout.encoding', sys.stdout.encoding);
print('sys.flags',sys.flags);print('sys.getfilesystemencoding',sys.getfilesystemencoding())"
2022-11-10T23:55:34.7960873Z shell: C:\Program Files\PowerShell\7\pwsh.EXE
-command ". '{0}'"
2022-11-10T23:55:34.7961202Z ##[endgroup]
2022-11-10T23:55:36.2324642Z sys.stdout.encoding cp1252
2022-11-10T23:55:36.2325910Z sys.flags sys.flags(debug=0, inspect=0,
interactive=0, optimize=0, dont_write_bytecode=0, no_user_site=0,
no_site=0, ignore_environment=0, verbose=0, bytes_warning=0, quiet=0,
hash_randomization=1, isolated=0, dev_mode=False, utf8_mode=0)
2022-11-10T23:55:36.2327055Z sys.getfilesystemencoding utf-8

2022-11-10T23:55:36.4553957Z ##[group]Run python -c "print('└── ID:')"
2022-11-10T23:55:36.4554395Z python -c "print('└── ID:')"
2022-11-10T23:55:36.4595413Z shell: C:\Program Files\PowerShell\7\pwsh.EXE
-command ". '{0}'"
2022-11-10T23:55:36.4595740Z ##[endgroup]
2022-11-10T23:55:36.8739309Z Traceback (most recent call last):
2022-11-10T23:55:37.1316425Z   File

Re: What is the reason from different output generate using logical 'and' and 'or' operator in Python 3.10.8

2022-11-11 Thread Exam Guide Publishers
On Tuesday, 8 November 2022 at 05:36:49 UTC+5:30, David wrote:
> On Tue, 8 Nov 2022 at 03:08, ICT Ezy  wrote: 
> 
> > Please explain how to generate different output in following logical 
> > operations 
> 
> > >>> 0 and True 
> > 0 
> > >>> 0 or True 
> > True 
> > >>> 1 and True 
> > True 
> > >>> 1 or True 
> > 1
> Hi, 
> 
> The exact explanation of how 'and' and 'or' behave can be read here: 
> https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not 
> The "Notes" there explain what you see.
Thank you very much, I understood Cleary.
Before I have doubt, but now clear.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need max values in list of tuples, based on position

2022-11-11 Thread DFS

On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:



[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12} 


Do they have to be IN THAT ORDER?


Yes.


data = [(0,11), (1,1),  (2,1), (0,1) , (1,41), (2,2), (0,9) , (1,3),  (2,12)]
reshape = list(zip(*data))
result = sorted(reshape[1])[-3:]
result

[11, 12, 41]





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


Need max values in list of tuples, based on position

2022-11-11 Thread DFS



[(0,11), (1,1),  (2,1),
 (0,1) , (1,41), (2,2),
 (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12} 



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


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Pancho via Python-list

On 11/11/2022 18:53, DFS wrote:

On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:



[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}


Do they have to be IN THAT ORDER?


Yes.

Sets aren't ordered, which is why I gave my answer as a list. A wrongly 
ordered list, but I thought it rude to point out my own error, as no one 
else had. :-)


Assuming you want numeric order of element[0], rather than first 
occurrence order of the element[0] in the original tuple list. In this 
example, they are both the same.


Here is a corrected version

from collections import OrderedDict
def build_max_dict( tups):
dict =  OrderedDict()
for (a,b) in tups:
if (a in dict):
if (b>dict[a]):
dict[a]=b
else:
dict[a]=b
return(dict.values())

This solution giving the answer as type odict_values. I'm not quite sure 
what this type is, but it seems to be a sequence/iterable/enumerable 
type, whatever the word is in Python.


Caveat: I know very little about Python.




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


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Pancho via Python-list

On 11/11/2022 07:22, DFS wrote:


[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}




def build_max_dict( tups):
dict = {}
for (a,b) in tups:
if (a in dict):
if (b>dict[a]):
dict[a]=b
else:
dict[a]=b
return(sorted(dict.values()))


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


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Dennis Lee Bieber
On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:

>
>[(0,11), (1,1),  (2,1),
>  (0,1) , (1,41), (2,2),
>  (0,9) , (1,3),  (2,12)]
>
>The set of values in elements[0] is {0,1,2}
>
>I want the set of max values in elements[1]: {11,41,12}

Do they have to be IN THAT ORDER?

>>> data = [(0,11), (1,1),  (2,1), (0,1) , (1,41), (2,2), (0,9) , (1,3),  
>>> (2,12)]
>>> reshape = list(zip(*data))
>>> result = sorted(reshape[1])[-3:]
>>> result
[11, 12, 41]



-- 
Wulfraed Dennis Lee Bieber AF6VN
wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need max values in list of tuples, based on position

2022-11-11 Thread DFS

On 11/11/2022 7:50 AM, Stefan Ram wrote:

Pancho  writes:

def build_max_dict( tups):
 dict = {}
 for (a,b) in tups:
 if (a in dict):
 if (b>dict[a]):
 dict[a]=b
 else:
 dict[a]=b
 return(sorted(dict.values()))


   Or,

import itertools
import operator

def build_max_dict( tups ):
 key = operator.itemgetter( 0 )
 groups = itertools.groupby( sorted( tups, key=key ), key )
 return set( map( lambda x: max( x[ 1 ])[ 1 ], groups ))


FYI, neither of those solutions work:

Pancho: 11, 12, 41
You   : 41, 11, 12

The answer I'm looking for is 11,41,12


Maybe a tuple with the same info presented differently would be easier 
to tackle:


orig:
[(0, 11), (1, 1),  (2, 1),
 (0, 1),  (1, 41), (2, 2),
 (0, 9),  (1, 3),  (2, 12)]

new: [(11,1,1),
  (1,41,2),
  (9,3,12)]

I'm still looking for the max value in each position across all elements 
of the tuple, so the answer is still 11,41,12.



Edit: found a solution online:
-
x = [(11,1,1),(1,41,2),(9,3,12)]
maxvals = [0]*len(x[0])
for e in x:
maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)]
print(maxvals)
[11,41,12]
-

So now the challenge is making it a one-liner!


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


Re: Argument name should be lowercase

2022-11-11 Thread Chris Angelico
On Sat, 12 Nov 2022 at 06:42, Stefan Ram  wrote:
>
> "Weatherby,Gerard"  writes:
> >I'd personally find it weird to see an all-cap parameter
>
>   In the source code of the standard library, all-caps
>   notation is used for a parameter name sometimes
>   if that parameter name is "URL" or sometimes
>   when it is being initialized from an all-caps name as in:
>
> |def __del__(self, _warn=warnings.warn, RUN=RUN):
> |if self._state == RUN:
> ...
> from "pool.py".
>
>   ("RUN=RUN" makes RUN have the value "RUN" had
>   at the time of the definition of the function.)
>

There are a few reasons to do that "snapshot" trick. The most common
is performance, but in this case, my guess is that (since it's a
__del__ method) it's to ensure that the objects are still referenced
when this function is called - to stop them getting disposed of
prematurely. Very rare, but important occasionally.

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


Dealing with non-callable classmethod objects

2022-11-11 Thread Ian Pilcher

I am trying to figure out a way to gracefully deal with uncallable
classmethod objects.  The class hierarchy below illustrates the issue.
(Unfortunately, I haven't been able to come up with a shorter example.)


import datetime


class DUID(object):

_subclasses = {}

def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls._subclasses[cls.duid_type] = cls

def __init__(self, d):
for attr, factory in self._attrs.items():
setattr(self, attr, factory(d[attr]))

@classmethod
def from_dict(cls, d):
subcls = cls._subclasses[d['duid_type']]
return subcls(d)


class DuidLL(DUID):

@staticmethod
def _parse_l2addr(addr):
return bytes.fromhex(addr.replace(':', ''))

duid_type = 'DUID-LL'
_attrs = { 'layer2_addr': _parse_l2addr }


class DuidLLT(DuidLL):

@classmethod
def _parse_l2addr(cls, addr):
return super()._parse_l2addr(addr)

duid_type = 'DUID-LLT'
_attrs = {
'layer2_addr': _parse_l2addr,
'time': datetime.datetime.fromisoformat
}


A bit of context on why I want to do this ...

This is a simplified subset of a larger body of code that parses a
somewhat complex configuration.  The configuration is a YAML document,
that pyyaml parses into a dictionary (which contains other dictionaries,
lists, etc., etc.).  My code then parses that dictionary into an object
graph that represents the configuration.

Rather than embedding parsing logic into each of my object classes, I
have "lifted" it into the parent class (DUID in the example).  A
subclasses need only provide a few attributes that identifies its
required and optional attributes, default values, etc. (simplified to
DuidLL._attrs and DuidLLT._attrs in the example).

The parent class factory function (DUID.from_dict) uses the information
in the subclass's _attrs attribute to control how it parses the
configuration dictionary.  Importantly, a subclass's _attrs attribute
maps attribute names to "factories" that are used to parse the values
into various types of objects.

Thus, DuidLL's 'layer2_addr' attribute is parsed with its
_parse_l2addr() static method, and DuidLLT's 'time' attribute is parsed
with datetime.datetime.fromisoformat().  A factory can be any callable
object that takes a dictionary as its only argument.

This works with static methods (as well as normal functions and object
types that have an appropriate constructor):


duid_ll = DUID.from_dict({ 'duid_type': 'DUID-LL', 'layer2_addr': 
'de:ad:be:ef:00:00' })
type(duid_ll)



duid_ll.duid_type

'DUID-LL'

duid_ll.layer2_addr

b'\xde\xad\xbe\xef\x00\x00'

It doesn't work with a class method, such as DuidLLT._parse_l2addr():


duid_llt = DUID.from_dict({ 'duid_type': 'DUID-LLT', 'layer2_addr': 
'de:ad:be:ef:00:00', 'time': '2015-09-04T07:53:04-05:00' })

Traceback (most recent call last):
  File "", line 1, in 
  File "/home/pilcher/subservient/wtf/wtf.py", line 19, in from_dict
return subcls(d)
  File "/home/pilcher/subservient/wtf/wtf.py", line 14, in __init__
setattr(self, attr, factory(d[attr]))
TypeError: 'classmethod' object is not callable

In searching, I've found a few articles that discuss the fact that
classmethod objects aren't callable, but the situation actually seems to
be more complicated.

>>> type(DuidLLT._parse_l2addr)

>>> callable(DuidLLT._parse_l2addr)
True

The method itself is callable, which makes sense.  The factory function
doesn't access it directly, however, it gets it out of the _attrs
dictionary.

>>> type(DuidLLT._attrs['layer2_addr'])

>>> callable(DuidLLT._attrs['layer2_addr'])
False

I'm not 100% sure, but I believe that this is happening because the
class (DuidLLT) doesn't exist at the time that its _attrs dictionary is
defined.  Thus, there is no class to which the method can be bound at
that time and the dictionary ends up containing the "unbound version."

Fortunately, I do know the class in the context from which I actually
need to call the method, so I am able to call it with its __func__
attribute.  A modified version of DUID.__init__() appears to work:

def __init__(self, d):
for attr, factory in self._attrs.items():
if callable(factory):  # <= ???!
value = factory(d[attr])
else:
value = factory.__func__(type(self), d[attr])
setattr(self, attr, value)

A couple of questions (finally!):

* Is my analysis of why this is happening correct?

* Can I improve the 'if callable(factory):' test above?  This treats
  all non-callable objects as classmethods, which is obviously not
  correct.  Ideally, I would check specifically for a classmethod, but
  there doesn't seem to be any literal against which I could check the
  factory's type.

Note:  I am aware that there are any number of workarounds for this
issue.  I just want to make sure that I understand what is going on, and
determine if there's a be

Re: Need max values in list of tuples, based on position

2022-11-11 Thread Thomas Passin

On 11/11/2022 2:22 PM, Pancho via Python-list wrote:

On 11/11/2022 18:53, DFS wrote:

On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:



[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}


Do they have to be IN THAT ORDER?


Yes.

Sets aren't ordered, which is why I gave my answer as a list. A wrongly 
ordered list, but I thought it rude to point out my own error, as no one 
else had. :-)


Assuming you want numeric order of element[0], rather than first 
occurrence order of the element[0] in the original tuple list. In this 
example, they are both the same.


Here is a corrected version

from collections import OrderedDict
def build_max_dict( tups):
     dict =  OrderedDict()
     for (a,b) in tups:
     if (a in dict):
     if (b>dict[a]):
     dict[a]=b
     else:
     dict[a]=b
     return(dict.values())

This solution giving the answer as type odict_values. I'm not quite sure 
what this type is, but it seems to be a sequence/iterable/enumerable 
type, whatever the word is in Python.


Caveat: I know very little about Python.


Kindly do not use "dict" as a variable name, since that shadows the 
system's built-in name for a dictionary type.


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


Re: Superclass static method name from subclass

2022-11-11 Thread Ian Pilcher

On 11/11/22 11:29, Dieter Maurer wrote:

Ian Pilcher wrote at 2022-11-11 10:21 -0600:


   class SuperClass(object):
   @staticmethod
   def foo():
   pass

   class SubClass(SuperClass):
   bar = SuperClass.foo
 ^^

Is there a way to do this without specifically naming 'SuperClass'?


Unless you overrode it, you can use `self.foo` or `SubClass.foo`;
if you overrode it (and you are using either Python 3 or
Python 2 and a so called "new style class"), you can use `super`.
When you use `super` outside a method definition, you must
call it with parameters.


SubClass.foo doesn't work, because 'SubClass' doesn't actually exist
until the class is defined.

>>> class SubClass(SuperClass):
...   bar = SubClass.foo
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in SubClass
NameError: name 'SubClass' is not defined. Did you mean: 'SuperClass'?

Similarly, self.foo doesn't work, because self isn't defined:

>>> class SubClass(SuperClass):
...   bar = self.foo
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in SubClass
NameError: name 'self' is not defined

--

Google  Where SkyNet meets Idiocracy


--
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 call), it is not available within the import-ed module's 
namespace. Hence the fall-back to passing it/the Workbook sub-set of 
parameters, as an argument. (see above for normal/traditional 'solution' 
to traversing namespaces)



Is passing the dict as an argument/parameter considered 

Re: Superclass static method name from subclass

2022-11-11 Thread Ian Pilcher

On 11/11/22 11:02, Thomas Passin wrote:

You can define a classmethod in SubClass that seems to do the job:

class SuperClass(object):
   @staticmethod
   def spam():  # "spam" and "eggs" are a Python tradition
   print('spam from SuperClass')

class SubClass(SuperClass):
     @classmethod
     def eggs(self):
     super().spam()

SubClass.eggs()  # Prints "spam from SuperClass"



That did it!  Thanks!

--

Google  Where SkyNet meets Idiocracy


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


Re: Superclass static method name from subclass

2022-11-11 Thread Cameron Simpson

On 11Nov2022 10:21, Ian Pilcher  wrote:

Is it possible to access the name of a superclass static method, when
defining a subclass attribute, without specifically naming the super-
class?

Contrived example:

 class SuperClass(object):
 @staticmethod
 def foo():
 pass

 class SubClass(SuperClass):
 bar = SuperClass.foo
   ^^

Is there a way to do this without specifically naming 'SuperClass'?


I think not.

All the posts so far run from inside methods, which execute after you've 
got an instance of `SubClass`.


However, during the class definition the code under `class SubClass` is 
running in a standalone namespace - not even inside a completed class.  
When that code finished, that namespace is used to create the class 
definition.


So you have no access to the `SuperClass` part of `class 
SubClass(SuperClass):` in the class definition execution.


Generally it is better to name where something like this comes from 
anyway, most of the time.


However, if you really want to plain "inherit" the class attribute 
(which I can imagine valid use cases for), maybe write a property?


@property
def bar(self):
return super().foo

That would still require an instance to make use of it, so you can't 
write explicitly `SubClass.bar`.


Possibly a metaclass would let you write a "class property", or to 
define `bar` as a class attribute directly.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Problems with IDLE in Windows 8.1 and installer x86 Version 3.10.8

2022-11-11 Thread Eryk Sun
On 11/11/22, darkst...@o2online.de  wrote:
>
> What can I do for the next step to find, why IDLE isn’t working?

The question is why tkinter isn't working. IDLE not working is just a
symptom of the underlying problem. In the command prompt, run 32-bit
Python 3.10 via `py -3.10-32`. In Python's interactive shell, run
`import _tkinter`. Please paste any resulting traceback and error
message in your reply to this message.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Superclass static method name from subclass

2022-11-11 Thread Cameron Simpson

On 12Nov2022 09:17, Cameron Simpson  wrote:

On 11Nov2022 10:21, Ian Pilcher  wrote:

class SubClass(SuperClass):
bar = SuperClass.foo
  ^^

Is there a way to do this without specifically naming 'SuperClass'?


I think not.


Then I saw your "Dealing with non-callable classmethod objects" post 
which mentions `__init_subclass__`. Which feels like I've read about 
that before, but had entirely slipped my mind.


Maybe:

class SubClass(SuperClass):
@classmethod
def __init__subclass__(cls):
cls.bar = super().foo

would do the trick. Looks clean, but I haven't tried it yet.

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Dealing with non-callable classmethod objects

2022-11-11 Thread Cameron Simpson

On 11Nov2022 15:29, Ian Pilcher  wrote:

I am trying to figure out a way to gracefully deal with uncallable
classmethod objects.


I'm just going to trim your example below a bit for reference purposes:


class DUID(object):
   def __init__(self, d):
   for attr, factory in self._attrs.items():
   setattr(self, attr, factory(d[attr]))
   @classmethod
   def from_dict(cls, d):
   subcls = cls._subclasses[d['duid_type']]
   return subcls(d)

class DuidLL(DUID):
   @staticmethod
   def _parse_l2addr(addr):
   return bytes.fromhex(addr.replace(':', ''))
   _attrs = { 'layer2_addr': _parse_l2addr }

class DuidLLT(DuidLL):
   @classmethod
   def _parse_l2addr(cls, addr):
   return super()._parse_l2addr(addr)
   _attrs = {
   'layer2_addr': _parse_l2addr,
   }


So what you've got is that `for attr, factory in self._attrs.items():` 
loop, where the factory comes from the subclass `_attrs` mapping. For 
`DuidLL` you get the static method `_parse_l2addr` object and for 
`DuidLLT` you get the class method object.


[...]

This works with static methods (as well as normal functions and object
types that have an appropriate constructor): [...]

[...]


It doesn't work with a class method, such as DuidLLT._parse_l2addr():


duid_llt = DUID.from_dict({ 'duid_type': 'DUID-LLT', 'layer2_addr': 
'de:ad:be:ef:00:00', 'time': '2015-09-04T07:53:04-05:00' })

Traceback (most recent call last):
 File "", line 1, in 
 File "/home/pilcher/subservient/wtf/wtf.py", line 19, in from_dict
   return subcls(d)
 File "/home/pilcher/subservient/wtf/wtf.py", line 14, in __init__
   setattr(self, attr, factory(d[attr]))
TypeError: 'classmethod' object is not callable

In searching, I've found a few articles that discuss the fact that
classmethod objects aren't callable, but the situation actually seems to
be more complicated.


type(DuidLLT._parse_l2addr)



callable(DuidLLT._parse_l2addr)

True

The method itself is callable, which makes sense.  The factory function
doesn't access it directly, however, it gets it out of the _attrs
dictionary.


type(DuidLLT._attrs['layer2_addr'])



callable(DuidLLT._attrs['layer2_addr'])

False

I'm not 100% sure, but I believe that this is happening because the
class (DuidLLT) doesn't exist at the time that its _attrs dictionary is
defined.  Thus, there is no class to which the method can be bound at
that time and the dictionary ends up containing the "unbound version."


Yes. When you define the dictionary `_parse_l2addr` is an unbound class 
method object. That doesn't change.



Fortunately, I do know the class in the context from which I actually
need to call the method, so I am able to call it with its __func__
attribute.  A modified version of DUID.__init__() appears to work:

   def __init__(self, d):
   for attr, factory in self._attrs.items():
   if callable(factory):  # <= ???!
   value = factory(d[attr])
   else:
   value = factory.__func__(type(self), d[attr])
   setattr(self, attr, value)


Neat!


A couple of questions (finally!):
* Is my analysis of why this is happening correct?


It seems so to me. Although I only learned some of these nuances 
recently.



* Can I improve the 'if callable(factory):' test above?  This treats
 all non-callable objects as classmethods, which is obviously not
 correct.  Ideally, I would check specifically for a classmethod, but
 there doesn't seem to be any literal against which I could check the
 factory's type.


Yeah, it does feel a bit touchy feely.

You could see if the `inspect` module tells you more precise things 
about the `factory`.


The other suggestion I have is to put the method name in `_attrs`; if 
that's a `str` you could special case it as a well known type for the 
factory and look it up with `getattr(cls,factory)`.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Thomas Passin

On 11/11/2022 2:22 AM, DFS wrote:


[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}


This request is ambiguous.  Do you want to get the maximum value for 
each row, and present it in the order of those rows?  Your data list 
does not distinguish the rows from the tuples, so that information must 
come from somewhere else.  Could it sometimes be different from 3?  How 
are we supposed to know?


Also, as has already been noted in this thread, the result cannot 
literally be a set because sets are not ordered but you insisted that 
the order is important.


This code  allows for different length of rows, and tries to be as clear 
as possible:


data = [(0,11), (1,1),  (2,1),
 (0,1), (1,41), (2,2),
 (0,9), (1,3),  (2,12)]

span = 3  # Change for other row lengths

d1 = [y for x, y in data]  # pick out the 2nd member of each tuple
# d1: [11, 1, 1, 1, 41, 2, 9, 3, 12]

groups = []
for i in range(0, len(d1), span):
group = []
for s in range(span):
group.append(d1[i + s])
groups.append(group)
# groups: [[11, 1, 1], [1, 41, 2], [9, 3, 12]]

maxes = [max(t) for t in groups]
# maxes: [11, 41, 12]

This could be condensed, but I recommend keeping it as clear as 
possible.  Tricky, condensed code becomes harder to understand as time 
goes by.

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


Create a Python Launcher on Desktop

2022-11-11 Thread ohinseok
Hello,

 

I am real a beginner of Python.  Not able to create a Python launcher
(shortcut) on Desktop after the installation. 

Would you kindly instruct how to do it? 

 

Windows 11-Home, 64 bits, HP desktop

 

Thanks,

Dan

 

 

 

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


Re: Need max values in list of tuples, based on position

2022-11-11 Thread DFS

On 11/11/2022 2:22 PM, Pancho wrote:

On 11/11/2022 18:53, DFS wrote:

On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:



[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}


Do they have to be IN THAT ORDER?


Yes.

Sets aren't ordered, which is why I gave my answer as a list. A wrongly 
ordered list, but I thought it rude to point out my own error, as no one 
else had. :-)


Assuming you want numeric order of element[0], rather than first 
occurrence order of the element[0] in the original tuple list. In this 
example, they are both the same.


Here is a corrected version

from collections import OrderedDict
def build_max_dict( tups):
     dict =  OrderedDict()
     for (a,b) in tups:
     if (a in dict):
     if (b>dict[a]):
     dict[a]=b
     else:
     dict[a]=b
     return(dict.values())

This solution giving the answer as type odict_values. I'm not quite sure 
what this type is, but it seems to be a sequence/iterable/enumerable 
type, whatever the word is in Python.


Caveat: I know very little about Python.



Thanks for looking at it.  I'm trying to determine the maximum length of 
each column result in a SQL query.  Normally you can use the 3rd value 
of the cursor.description object (see the DB-API spec), but apparently 
not with my dbms (SQLite).  The 'display_size' column is None with 
SQLite.  So I had to resort to another way.




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


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Pancho via Python-list

On 11/11/2022 20:58, Thomas Passin wrote:

On 11/11/2022 2:22 PM, Pancho via Python-list wrote:

On 11/11/2022 18:53, DFS wrote:

On 11/11/2022 12:49 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 02:22:34 -0500, DFS  declaimed the
following:



[(0,11), (1,1),  (2,1),
  (0,1) , (1,41), (2,2),
  (0,9) , (1,3),  (2,12)]

The set of values in elements[0] is {0,1,2}

I want the set of max values in elements[1]: {11,41,12}


Do they have to be IN THAT ORDER?


Yes.

Sets aren't ordered, which is why I gave my answer as a list. A 
wrongly ordered list, but I thought it rude to point out my own error, 
as no one else had. :-)


Assuming you want numeric order of element[0], rather than first 
occurrence order of the element[0] in the original tuple list. In this 
example, they are both the same.


Here is a corrected version

from collections import OrderedDict
def build_max_dict( tups):
 dict =  OrderedDict()
 for (a,b) in tups:
 if (a in dict):
 if (b>dict[a]):
 dict[a]=b
 else:
 dict[a]=b
 return(dict.values())

This solution giving the answer as type odict_values. I'm not quite 
sure what this type is, but it seems to be a 
sequence/iterable/enumerable type, whatever the word is in Python.


Caveat: I know very little about Python.


Kindly do not use "dict" as a variable name, since that shadows the 
system's built-in name for a dictionary type.




Yes, I half suspected it might cause subtle problems, I changed it to d, 
and then I changed it back, senility I guess :-).


That was one of the things I didn't like about Python. Lack of types and 
subsequent loss of intellisense is the thing I find hardest to deal with.


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


Re: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread Eryk Sun
On 11/10/22, Jessica Smith <12jessicasmit...@gmail.com> wrote:
>
> Weird issue I've found on Windows images in Azure Devops Pipelines and
> Github actions. Printing Unicode characters fails on these images because,
> for some reason, the encoding is mapped to cp1252. What is particularly
> weird about the code page being set to 1252 is that if you execute "chcp"
> it shows that the code page is 65001.

If stdout isn't a console (e.g. a pipe), it defaults to using the
process code page (i.e. CP_ACP), such as legacy code page 1252
(extended Latin-1). You can override just sys.std* to UTF-8 by setting
the environment variable `PYTHONIOENCODING=UTF-8`. You can override
all I/O to use UTF-8 by setting `PYTHONUTF8=1`, or by passing the
command-line option `-X utf8`.

Background

The locale system in Windows supports a common system locale, plus a
separate locale for each user. By default the process code page is
based on the system locale, and the thread code page (i.e.
CP_THREAD_ACP) is based on the user locale. The default locale of the
Universal C runtime combines the user locale with the process code
page. (This combination may be inconsistent.)

In Windows 10 and later, the default process and thread code pages can
be configured to use CP_UTF8 (65001). Applications can also override
them to UTF-8 in their manifest via the "ActiveCodePage" setting. In
either case, if the process code page is UTF-8, the C runtime will use
UTF-8 for its default locale encoding (e.g. "en_uk.utf8").

Unlike some frameworks, Python has never used the console input code
page or output code page as a locale encoding. Personally, I wouldn't
want Python to default to that old MS-DOS behavior. However, I'd be in
favor of supporting a "console" encoding that's based on the console
input code page that's returned by GetConsoleCP(). If the process
doesn't have a console session, the "console" encoding would fall back
on the process code page from GetACP().
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need max values in list of tuples, based on position

2022-11-11 Thread Dennis Lee Bieber
On Fri, 11 Nov 2022 15:03:49 -0500, DFS  declaimed the
following:


>Thanks for looking at it.  I'm trying to determine the maximum length of 
>each column result in a SQL query.  Normally you can use the 3rd value 
>of the cursor.description object (see the DB-API spec), but apparently 
>not with my dbms (SQLite).  The 'display_size' column is None with 
>SQLite.  So I had to resort to another way.

Not really a surprise. SQLite doesn't really have column widths --
since any column can store data of any type; affinities just drive it into
what may be the optimal storage for the column... That is, if a column is
"INT", SQLite will attempt to convert whatever the data is into an integer
-- but if the data is not representable as an integer, it will be stored as
the next best form.

123 => stored as integer
"123"   => converted and stored as integer
123.0   => probably converted to integer
123.5   => likely stored as numeric/double
"one two three" => can't convert, store it as a string

We've not seen the SQL query in question, but it might suffice to use a
second (first?) SQL query with aggregate (untested)

max(length(colname))

for each column in the main SQL query.

"""
length(X)

For a string value X, the length(X) function returns the number of
characters (not bytes) in X prior to the first NUL character. Since SQLite
strings do not normally contain NUL characters, the length(X) function will
usually return the total number of characters in the string X. For a blob
value X, length(X) returns the number of bytes in the blob. If X is NULL
then length(X) is NULL. If X is numeric then length(X) returns the length
of a string representation of X. 
"""

Note the last sentence for numerics. 


-- 
Wulfraed Dennis Lee Bieber AF6VN
wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Create a Python Launcher on Desktop

2022-11-11 Thread Thomas Passin

On 11/11/2022 4:44 PM, ohins...@gmail.com wrote:

Hello,

  


I am real a beginner of Python.  Not able to create a Python launcher
(shortcut) on Desktop after the installation.

Would you kindly instruct how to do it?

  


Windows 11-Home, 64 bits, HP desktop



If you get an offer of Python when you open the start menu and type 
"Python" (no quotes, please) then it's easy. I'm working with Windows 
10, but it's probably much the same in Windows 11.


When the Start menu offers "Python", choose the version of Python you 
want (if there are more than one), right click on it, and choose "Open 
File Location".  This will open a Windows Explorer window with some 
Python-related shortcuts.  Make sure the Explorer window does not cover 
the whole screen - you need to have some of the desktop visible around 
it. Choose the shortcut for Python, and drag it to the desktop **while 
holding down both the  and  keys**.  Presto, a Python 
launcher on your desktop.


If you don't see your version of Python when you tap the Windows key and 
type "Python", then you will need to find where the Python directory is, 
find the file called "python.exe", and then do the dragging operation on it.


If you do not know how to find where Python is located, then please see 
my message on this list titled "Re: Problems with IDLE in Windows 8.1 
and installer x86 Version 3.10.8", dated 11/9/2022.



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


Re: Superclass static method name from subclass

2022-11-11 Thread Thomas Passin

On 11/11/2022 5:07 PM, Ian Pilcher wrote:

On 11/11/22 11:02, Thomas Passin wrote:

You can define a classmethod in SubClass that seems to do the job:

class SuperClass(object):
   @staticmethod
   def spam():  # "spam" and "eggs" are a Python tradition
   print('spam from SuperClass')

class SubClass(SuperClass):
 @classmethod
 def eggs(self):
 super().spam()

SubClass.eggs()  # Prints "spam from SuperClass"



That did it!  Thanks!


Glad I could help.  I probably should have written

 def eggs(clas):  # instead of "self"

but it's not actually used anyway.

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


Re: Create a Python Launcher on Desktop

2022-11-11 Thread Eryk Sun
On 11/11/22, ohins...@gmail.com  wrote:
>
> I am real a beginner of Python.  Not able to create a Python launcher
> (shortcut) on Desktop after the installation.

Did you already install Python? If not, open the Store, and install
the Python 3.11 app that's published by the Python Software
Foundation. After Python is installed, you'll have shortcuts in the
start menu that run Python in a terminal or that run the IDLE
development environment.

On the context menu of a shortcut, there's an action to pin it to the
top-level start menu, which is more convenient than having to click on
"all apps" to find it. Also, the context menu of a pinned shortcut has
an action to pin it to the taskbar, for even more convenient access.
The running application icon on the taskbar also lets you pin the app.

If you really want a shortcut on your desktop, it depends on which
distribution you installed. If you installed the app version of 3.11,
then you have "python3.11.exe" to run Python in a terminal and
"idle3.11.exe" to IDLE. To create a shortcut, right click the desktop;
select the action to create a new shortcut; and enter one of the
latter executable names. After creating the shortcut, on its context
menu select the "properties" action, and then modify the "start in"
folder to your preferred working directory.

If you installed the standard distribution from python.org, then you
already have normal file shortcuts (as opposed to app shortcuts) in
the start menu, which you can copy to the desktop. The context menu of
the start-menu shortcut has an action to open the file location. This
opens an Explorer window. Right click the shortcut in that window and
drag it to the desktop. Release the mouse button and select the action
"copy here".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread 12Jessicasmith34
  >  If stdout isn't a console (e.g. a pipe), it defaults to using the 
process code page (i.e. CP_ACP), such as legacy code page 1252
 
(extended Latin-1).
 

 
First off, really helpful information, thank you. That was the exact background 
I was missing.
 

 
Two questions: any idea why this would be happening in this situation? AFAIK, 
stdout *is* a console when these images are running the python process. Second 
- is there a way I can check the locale and code page values that you 
mentioned? I assume I could call GetACP using ctypes, but maybe there is a 
simpler way?
 
 

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


Re: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread Eryk Sun
On 11/11/22, 12Jessicasmith34 <12jessicasmit...@gmail.com> wrote:
>
> any idea why this would be happening in this situation? AFAIK, stdout
> *is* a console when these images are running the python process.

If sys.std* are console files, then in Python 3.6+,
sys.std*.buffer.raw will be _io._WindowsConsoleIO. The latter presents
itself to Python code as a UTF-8 file stream, but internally it uses
UTF-16LE with the wide-character API functions ReadConsoleW() and
WriteConsoleW().

> is there a way I can check the locale and code page values that you
> mentioned? I assume I could call GetACP using ctypes, but maybe
> there is a simpler way?

io.TextIOWrapper uses locale.getpreferredencoding(False) as the
default encoding. Actually, in 3.11+ it uses locale.getencoding()
unless UTF-8 mode is enabled, which is effectively the same as
locale.getpreferredencoding(False). On Windows this calls GetACP() and
formats the result as "cp%u" (e.g. "cp1252").
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Need max values in list of tuples, based on position

2022-11-11 Thread DFS

On 11/11/2022 7:04 PM, Dennis Lee Bieber wrote:

On Fri, 11 Nov 2022 15:03:49 -0500, DFS  declaimed the
following:



Thanks for looking at it.  I'm trying to determine the maximum length of
each column result in a SQL query.  Normally you can use the 3rd value
of the cursor.description object (see the DB-API spec), but apparently
not with my dbms (SQLite).  The 'display_size' column is None with
SQLite.  So I had to resort to another way.


Not really a surprise. SQLite doesn't really have column widths --


As I understand it, the cursor.description doesn't look at the column 
type - it goes by the data in the cursor.




since any column can store data of any type; affinities just drive it into
what may be the optimal storage for the column... That is, if a column is
"INT", SQLite will attempt to convert whatever the data is into an integer
-- but if the data is not representable as an integer, it will be stored as
the next best form.


Yeah, I don't know why cursor.description doesn't work with SQLite; all 
their columns are basically varchars.




123 => stored as integer
"123" => converted and stored as integer
123.0   => probably converted to integer
123.5   => likely stored as numeric/double
"one two three"   => can't convert, store it as a string

	We've not seen the SQL query in question, 



The query is literally any SELECT, any type of data, including SELECT *. 
 The reason it works with SELECT * is the cursor.description against 
SQLite DOES give the column names:


select * from timezone;
print(cur.description)
(
('TIMEZONE', None, None, None, None, None, None),
('TIMEZONEDESC', None, None, None, None, None, None),
('UTC_OFFSET',   None, None, None, None, None, None)
)

(I lined up the data)


Anyway, I got it working nicely, with the help of the solution I found 
online and posted here earlier:


-
x = [(11,1,1),(1,41,2),(9,3,12)]
maxvals = [0]*len(x[0])
for e in x:

#clp example using only ints
maxvals = [max(w,int(c)) for w,c in zip(maxvals,e)]  #clp example

#real world - get the length of the data string, even if all numeric
maxvals = [max(w,len(str(c))) for w,c in zip(maxvals,e)]

print(maxvals)
[11,41,12]
-

Applied to real data, the iterations might look like this:

[4, 40, 9]
[4, 40, 9]
[4, 40, 9]
[4, 40, 18]
[4, 40, 18]
[4, 40, 18]
[5, 40, 18]
[5, 40, 18]
[5, 40, 18]
[5, 69, 18]
[5, 69, 18]
[5, 69, 18]

The last row contains the max width of the data in each column.

Then I compare those datawidths to the column name widths, and take the 
wider of the two, so [5,69,18] might change to [8,69,18] if the column 
label is wider than the widest bit of data in the column


convert those final widths into a print format string, and everything 
fits well: Each column is perfectly sized and it all looks pleasing to 
the eye (and no external libs like tabulate used either).


https://imgur.com/UzO3Yhp


The 'downside' is you have to fully iterate the data twice: once to get 
the widths, then again to print it.


If I get a wild hair I might create a PostgreSQL clone of my db and see 
if the cursor.description works with it.  It would also have to iterate 
the data to determine that 'display_size' value.


https://peps.python.org/pep-0249/#cursor-attributes




> but it might suffice to use a
> second (first?) SQL query with aggregate (untested)
>
>max(length(colname))
>
> for each column in the main SQL query.


Might be a pain to code dynamically.





"""
length(X)

 For a string value X, the length(X) function returns the number of
characters (not bytes) in X prior to the first NUL character. Since SQLite
strings do not normally contain NUL characters, the length(X) function will
usually return the total number of characters in the string X. For a blob
value X, length(X) returns the number of bytes in the blob. If X is NULL
then length(X) is NULL. If X is numeric then length(X) returns the length
of a string representation of X.
"""

Note the last sentence for numerics.




Thanks for looking at it.

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


Re: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread Inada Naoki
On Sat, Nov 12, 2022 at 10:21 AM 12Jessicasmith34
<12jessicasmit...@gmail.com> wrote:
>
>
> Two questions: any idea why this would be happening in this situation? AFAIK, 
> stdout *is* a console when these images are running the python process. 
> Second - is there a way I can check the locale and code page values that you 
> mentioned? I assume I could call GetACP using ctypes, but maybe there is a 
> simpler way?
>

Maybe, python doesn't write to console in this case.

  python -(pipe)-> PowerShell -> Console

In this case, python uses ACP for writing to pipe.
And PowerShell uses OutputEncoding for reading from pipe.

If you want to use UTF-8 on PowerShell in Windows,

 * Set PYTHONUTF8=1 (Python uses UTF-8 for writing into pipe).
 * Set `$OutputEncoding =
[System.Text.Encoding]::GetEncoding('utf-8')` in PowerShell profile.

Regards,

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


Re: Strange UnicodeEncodeError in Windows image on Azure DevOps and Github

2022-11-11 Thread Inada Naoki
On Sat, Nov 12, 2022 at 11:53 AM Inada Naoki  wrote:
>
> On Sat, Nov 12, 2022 at 10:21 AM 12Jessicasmith34
> <12jessicasmit...@gmail.com> wrote:
> >
> >
> > Two questions: any idea why this would be happening in this situation? 
> > AFAIK, stdout *is* a console when these images are running the python 
> > process. Second - is there a way I can check the locale and code page 
> > values that you mentioned? I assume I could call GetACP using ctypes, but 
> > maybe there is a simpler way?
> >
>
> Maybe, python doesn't write to console in this case.
>
>   python -(pipe)-> PowerShell -> Console
>
> In this case, python uses ACP for writing to pipe.
> And PowerShell uses OutputEncoding for reading from pipe.
>
> If you want to use UTF-8 on PowerShell in Windows,
>
>  * Set PYTHONUTF8=1 (Python uses UTF-8 for writing into pipe).
>  * Set `$OutputEncoding =
> [System.Text.Encoding]::GetEncoding('utf-8')` in PowerShell profile.
>

I forgot [Console]::OutputEncoding. This is what PowerShell uses when
reading from pipe. So PowerShell profile should be:

  $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

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


Re: Dealing with non-callable classmethod objects

2022-11-11 Thread Dieter Maurer
Ian Pilcher wrote at 2022-11-11 15:29 -0600:
> ...
>In searching, I've found a few articles that discuss the fact that
>classmethod objects aren't callable, but the situation actually seems to
>be more complicated.
>
> >>> type(DuidLLT._parse_l2addr)
>
> >>> callable(DuidLLT._parse_l2addr)
>True
>
>The method itself is callable, which makes sense.  The factory function
>doesn't access it directly, however, it gets it out of the _attrs
>dictionary.
>
> >>> type(DuidLLT._attrs['layer2_addr'])
>
> >>> callable(DuidLLT._attrs['layer2_addr'])
>False

Accessing an object via a `dict` does not change its type,
nor does putting it into a `dict`.
Thus, you did not put `DuidLLT._parse_l2addr` (of type `method`)
into your `_attrs` `dict` but something else (of type `classmethod`).

This narrows down the space for your investigation: why was
the object you have put into `_attr` was not what you have expected.
-- 
https://mail.python.org/mailman/listinfo/python-list