Python 3.9 pidfd_open

2022-07-07 Thread Weatherby,Gerard
python introduced os.pidfd_open(), which works as documented. My development environment, PyCharm, complains about it being undefined. Should it be in https://raw.githubusercontent.com/python/cpython/3.9/Lib/os.py ? -- Gerard Weatherby | Application Architect NMRbox | NAN | Department of Molecul

Re: Object in List : how?

2022-07-25 Thread Weatherby,Gerard
“Private” properties are more simply / commonly designated by sticking an _ in front of the name. class Node: def __init__(self,a) self._a = a I recommend you read https://docs.python.org/3/tutorial/classes.html. That’s not to say properties don’t have their uses, but making things “priva

Re: random.SystemRandom().randint() inefficient

2022-07-26 Thread Weatherby,Gerard
Absolutely. The task (“generate a random number”) is ill-defined. Want a fast random number? Use 552015933 (I just retrieved it from random.org). Want a true random number, use random.org API. (https://api.random.org/pricing). Something in between, follow approaches Stefan suggests. — Gerard

Re: PEP about recommended project folder layout

2022-07-31 Thread Weatherby,Gerard
I’m not aware of any standard convention for laying out packages. PEP 8 (https://peps.python.org/pep-0008/) specifies conventions for how to write Python, so a standard layout PEP would not be inconsistent. — Gerard Weatherby | Application Architect NMRbox | NAN | Department of Molecular Biolog

Re: Dictionary order?

2022-08-01 Thread Weatherby,Gerard
I don’t see what is surprising. The interface for a dictionary never specified the ordering of the keys, so I would not be surprised to see it vary based on release, platform, values of keys inserted, number of items in the dictionary, etc. — Gerard Weatherby | Application Architect NMRbox

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

2022-08-04 Thread Weatherby,Gerard
Just be aware https://docs.python.org/3/ defaults to the latest Python version (3.10). When looking up a module, it’s best to explicitly set the documentation to the version you are using. It won’t matter the vast majority of the time but I have been burned by trying to use a function or paramet

Re: Exclude 'None' from list comprehension of dicts

2022-08-04 Thread Weatherby,Gerard
Or: data = [d for d in [get_job_efficiency_dict(job_id) for job_id in job_ids] if d is not None] or for job_id in job_ids: if (d := get_job_efficiency_dict(job_id)) is not None: data.append(d) Personally, I’d got with the latter in my own code. — Gerard Weatherby | Application Arch

Re: Trying to understand nested loops

2022-08-05 Thread Weatherby,Gerard
It’s also a poor code example. Doing a pointless double loop is not good instructional practice, especially when simpler alternatives exist. e.g. for i in range(3): for j in range(-2.-7,-2): print(i +j ) — Gerard Weatherby | Application Architect NMRbox | NAN | Department of Molecular Biol

Re: How to replace an instance method?

2022-09-19 Thread Weatherby,Gerard
Just subclass and override whatever method you wish to modify “Private” is conceptual. Mostly it means when the next version of a module comes out, code that you wrote that accesses *._ parts of the module might break. ___ import pandas class MyClass(pandas.ExcelFile.OpenpyxlReader): de

Re: Ref-strings in logging messages (was: Performance issue with CPython 3.10 + Cython)

2022-10-07 Thread Weatherby,Gerard
The obvious way to avoid log generation is: if logger.isEnableFor(logging.DEBUG): logger.debug( expensive processing ) Of course, having logging alter program flow could lead to hard to debug bugs. From: Python-list on behalf of Barry Date: Friday, October 7, 2022 at 1:30 PM

Re: Ref-strings in logging messages (was: Performance issue with CPython 3.10 + Cython)

2022-10-08 Thread Weatherby,Gerard
Logging does support passing a callable, if indirectly. It only calls __str__ on the object passed if debugging is enabled. class Defer: def __init__(self,fn): self.fn = fn def __str__(self): return self.fn() def some_expensive_function(): return "hello" logging.ba

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

2022-10-09 Thread Weatherby,Gerard
PyCharm. Does a good job of separating these are really errors from do you really mean that warnings from this word is spelled right. https://www.jetbrains.com/pycharm/ From: Python-list on behalf of Antoon Pardon Date: Sunday, October 9, 2022 at 6:11 AM To: python-list@python.org Subject:

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

2022-10-10 Thread Weatherby,Gerard
try: open(disk) except: error(“Can’t open disk”) lots of things From: Python-list on behalf of Karsten Hilbert Date: Monday, October 10, 2022 at 5:46 AM To: python-list@python.org Subject: Re: for -- else: what was the motivation? *** Attention: This is an exter

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

2022-10-10 Thread Weatherby,Gerard
Core developer Raymond Hettinger explains the history starting at 15:40 https://www.youtube.com/watch?v=OSGv2VnC0go (which I found on stackoverflow https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops ) TL:DR The “else” is a historical artificial from

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

2022-10-10 Thread Weatherby,Gerard
October 10, 2022 at 1:10 PM To: python-list@python.org Subject: Re: for -- else: what was the motivation? *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** > On 10/10/2022 15:52, Weatherby,Gerard wrote: >> I wonder if for/else c

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

2022-10-11 Thread Weatherby,Gerard
Sure it does. They’re optional and not enforced at runtime, but I find them useful when writing code in PyCharm: import os from os import DirEntry de : DirEntry for de in os.scandir('/tmp'): print(de.name) de = 7 print(de) Predeclaring de allows me to do the tab completion thing with DirEn

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

2022-10-12 Thread Weatherby,Gerard
As did I. tree = ET.parse(lfile) for child in tree.getroot(): if child.tag == 'server': break else: raise ValueError(f"server tag not found in {lfile}") I think there are other places I could be using it, but honestly I t

Re: Find the path of a shell command

2022-10-12 Thread Weatherby,Gerard
Some thoughts / notes: 1. On our Ubuntu-Server 20.04.3 based systems, /bin/rm and /usr/bin/rm are hard links to the same file. 2. Put the following in a bash script and run it from cron. Then you can see what your environment is. Mine has PATH=/usr/bin:/bin in it. #!/bin/bash env > /tmp/env$$

Re: Find the path of a shell command (shutil.which)

2022-10-12 Thread Weatherby,Gerard
Not going to do any good if it’s not on the PATH in the first place: https://docs.python.org/3/library/shutil.html shutil.which(cmd, mode=os.F_OK | os.X_OK, path=None) Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None. mode is

systemd Re: Find the path of a shell command

2022-10-14 Thread Weatherby,Gerard
Only the first one or two require more work. The rest are your copy-pastes from the last time you did one. Typically I only have to changed descriptions, the executable in the *service and the timing in the *timer. They’re lot more readable and flexible than the cronjobs. From: Python-list on

Re: Operator: inappropriate wording?

2022-10-26 Thread Weatherby,Gerard
No. If the docs say in one place a comma is not an operator, they shouldn’t call it an operator in another place. I’ve submitted a pull request https://github.com/python/cpython/pull/98736 -- we’ll have to see what The Powers That Be think. From: Python-list on behalf of elas tica Date: Wedn

Re: an oop question

2022-10-30 Thread Weatherby,Gerard
I don’t understand your implementation enough to comment specifically. What’s the definition of Pair? (i.e. what methods and public attributes does it have?) (I manage to escape Lisp as an undergrad) To answer your question generally, Union’s are not OO. If you want Pair and Stack to have the s

Re: an oop question

2022-11-01 Thread Weatherby,Gerard
I think: class Stack: def __init__( self, *args ): self.data = args def __str__( self ): return f"Stack({','.join(str(x) for x in self.data)})" gives equivalent output for the if len(args) is 0 or 2, if it’s okay for self.data to be a tuple. class Stack: def __init_

Re: an oop question

2022-11-03 Thread Weatherby,Gerard
C++/Java class variables can be public, protected (accessible to class and subclasses) or private (accessible only to class). Of course the language protections can be hacked around. Python does conceptual private variables by using the single underscore: object._myvar is considered private Fr

Re: an oop question

2022-11-03 Thread Weatherby,Gerard
https://www.oreilly.com/library/view/beginning-c-30/9780470261293/9780470261293_a_short_history_of_object-oriented_progr.html -- https://mail.python.org/mailman/listinfo/python-list

Re: How to manage python shebang on mixed systems?

2022-11-06 Thread Weatherby,Gerard
A possible solution is here. https://superuser.com/questions/815323/can-i-have-a-conditional-shebang From: Python-list on behalf of jak Sent: Sunday, November 6, 2022 2:51:10 PM To: python-list@python.org Subject: Re: How to manage python shebang on mixed sy

Re: How to manage python shebang on mixed systems?

2022-11-07 Thread Weatherby,Gerard
Write the wrapper script. #!/bin/bash if [ $(hostname) == "oldystem" ]; then exec /usr/bin/python $* else exec /usr/bin/python2 $* fi From: Python-list on behalf of Chris Green Date: Sunday, November 6, 2022 at 3:22 PM To: python-list@python.org Subject: Re: How to manage python sheba

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 para

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

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

2022-11-12 Thread Weatherby,Gerard
Types are available if you want to use them. https://www.pythontutorial.net/python-basics/python-type-hints/ From: Python-list on behalf of Pancho via Python-list Date: Friday, November 11, 2022 at 6:28 PM To: python-list@python.org Subject: Re: Need max values in list of tuples, based on pos

Re: Argument name should be lowercase

2022-11-12 Thread Weatherby,Gerard
-list on behalf of Stefan Ram Date: Friday, November 11, 2022 at 2:42 PM To: python-list@python.org Subject: Re: Argument name should be lowercase *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** "Weatherby,Gerard" wr

Re: Dealing with non-callable classmethod objects

2022-11-12 Thread Weatherby,Gerard
Use the inspect module as Cameron suggested. import inspect def analyze_class(clzz): """Analyze a class proof of concept""" assert inspect.isclass(clzz) for k, v in inspect.getmembers(clzz, lambda v: inspect.isfunction(v) or inspect.ismethod(v)): if inspect.ismethod(v):

Re: Persisting functions typed into the shell

2022-11-12 Thread Weatherby,Gerard
Sounds like Jupyter Notebooks: https://jupyter.org From: Python-list on behalf of Stefan Ram Date: Saturday, November 12, 2022 at 1:48 PM To: python-list@python.org Subject: Persisting functions typed into the shell *** Attention: This is an external email. Use caution responding, opening at

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

2022-11-14 Thread Weatherby,Gerard
The terminal told you what x.clear was. The Python documentation tells you how to call it: https://docs.python.org/3/tutorial/datastructures.html list.clear() Remove all items from the list. Equivalent to del a[:]. An IDE (e.g. PyCharm) will try to autocomplete the parentheses and warn you if

Re: Are these good ideas?

2022-11-14 Thread Weatherby,Gerard
Issue 1. Depends very much on your operating system and application environment. Issue 2. I usually make myself a data class to pass around. Then when I figure out I forgot something, I just update the dataclass and the creator and consumer of it. @dataclass class CallParameter:

Re: Preprocessing not quite fixed-width file before parsing

2022-11-23 Thread Weatherby,Gerard
.replace(' ', '_') fixed_data = f"{' '.join(hparts)} | {tail}" return fixed_data return data except: logging.exception("read") logging.basicConfig() with Wrapper('data.txt') as f

Re: Preprocessing not quite fixed-width file before parsing

2022-11-23 Thread Weatherby,Gerard
This seems to work. I’m inferring the | is present in each line that needs to be fixed. import pandas import logging class Wrapper: """Wrap file to fix up data""" def __init__(self, filename): self.filename = filename def __enter__(self): self.fh = open(self.filena

Re: is mypy failing here

2022-11-24 Thread Weatherby,Gerard
https://github.com/python/mypy/issues/12971 From: Python-list on behalf of Thomas Passin Date: Thursday, November 24, 2022 at 7:36 AM To: python-list@python.org Subject: Re: is mypy failing here *** Attention: This is an external email. Use caution responding, opening attachments or clicking

Re: argparse — adding a --version flag in the face of positional args

2022-11-27 Thread Weatherby,Gerard
Use two parsers: import argparse import sys vparser = argparse.ArgumentParser(add_help=False) vparser.add_argument('--version',action="store_true",help="show version") # look for version, ignore remaining arguments vargs, _ = vparser.parse_known_args() if vargs.version: print("Version 2.0")

Re: argparse — adding a --version flag in the face of positional args

2022-11-28 Thread Weatherby,Gerard
More better: import argparse parser = argparse.ArgumentParser() parser.add_argument("positional",type=int) parser.add_argument('--version',action="version",version="2.0") args = parser.parse_args() # double argument print(args.positional * 2) From: Pyt

Re: Python script not letting go of files

2022-11-29 Thread Weatherby,Gerard
Does the script exit when complete? If you’re running on a Linux based system and have root access you can use lsof to see what processes have with files open. (Or use the psutil Python package). From: Python-list on behalf of Mike Dewhirst Date: Tuesday, November 29, 2022 at 2:20 AM To: pyth

Re: Python script not letting go of files

2022-11-29 Thread Weatherby,Gerard
"Weatherby,Gerard" writes: >Do any of you Python folks see any blunders in the above code along the >lines of not letting go of py files or static assets? Er, no, I just replied to the original poster. -- https://mail.python.org/mailman/listinfo/python-list

Re: Vb6 type to python

2022-11-30 Thread Weatherby,Gerard
Look at struct package: https://docs.python.org/3/library/struct.html From: Python-list on behalf of luca72.b...@gmail.com Date: Wednesday, November 30, 2022 at 11:48 AM To: python-list@python.org Subject: Vb6 type to python *** Attention: This is an external email. Use caution responding, op

Re: Calling pselect/ppoll/epoll_pwait

2022-12-03 Thread Weatherby,Gerard
Signalfd and select could probably be made to work if one codes around the race conditions pselect is provided to avoid. I’m not sure if using the GIL (for CPython) is sufficient or if a dedicated concurrency control (e.g. lock, mutex, semaphore) is necessary. An alternative is to call the C l

Re: on the python paradox

2022-12-07 Thread Weatherby,Gerard
I use asyncio in a couple of places. Haven’t quite grokked it yet, though. From: Python-list on behalf of Stefan Ram Date: Wednesday, December 7, 2022 at 12:28 PM To: python-list@python.org Subject: Re: on the python paradox *** Attention: This is an external email. Use caution responding, ope

Re: How to convert a raw string r'\xdd' to '\xdd' more gracefully?

2022-12-08 Thread Weatherby,Gerard
I’m not understanding the task. The sample code given is converting the input r’\x0a’ to a newline, it appears. import re def exam(z): print(f"examine {type(z)} {z}") for c in z: print(f"{ord(c)} {c}") s0 = r'\x0a' def to1byte(matchobj): return chr(int('0x' + matchobj.gro

Re: How to convert a raw string r'\xdd' to '\xdd' more gracefully?

2022-12-09 Thread Weatherby,Gerard
That’s actually more of a shell question than a Python question. How you pass certain control characters is going to depend on the shell, operating system, and possibly the keyboard you’re using. (e.g. https://www.alt-codes.net). Here’s a sample program. The dashes are to help show the boundarie

Re: New computer, new Python

2022-12-09 Thread Weatherby,Gerard
Python in an IDE is much easier in the long run. We use PyCharm – there’s a free version: https://www.jetbrains.com/pycharm/download/#section=windows From: Python-list on behalf of DFS Date: Friday, December 9, 2022 at 4:36 PM To: python-list@python.org Subject: Re: New computer, new Python *

Re: Subtracting dates to get hours and minutes

2022-12-12 Thread Weatherby,Gerard
The difference between two datetime objects is a timedelta object. https://docs.python.org/3/library/datetime.html#timedelta-objects . It has a total_seconds() method. This is a simple task, unless one of the datetimes has a time zone specified and the other doesn’t. From: Python-list on beh

Re: Keeping a list of records with named fields that can be updated

2022-12-15 Thread Weatherby,Gerard
I have a lot of NamedTuples in my codebase, and I now add new ones never. They were a good option prior to Python 3.7 but dataclasses are much easier to work with and are almost a drop-in substitute. A combination of a default dictionary and a dataclass might meet your needs: import collectio

Re: Single line if statement with a continue

2022-12-15 Thread Weatherby,Gerard
I once saw a C function full of GOTOs which jumped to the return state at the bottom of the functions because the programmer had learned that “multiple returns are a bad idea.” I totally agree multiple returns causing confusion is a symptom of poor design, not a cause. Required cleanup is easi

Re: Subtracting dates to get hours and minutes

2022-12-15 Thread Weatherby,Gerard
Not sure what you mean: x = datetime.datetime(year=2018,month=12,day=4,hour=10) y = datetime.datetime(year=2022,month=12,day=13,hour=5) print(x -y) -1470 days, 5:00:00 If you want to display years, (x-y).days /365 From: Python-list on behalf of Gronicus@SGA.Ninja Date: Thursday, December

Re: String to Float, without introducing errors

2022-12-17 Thread Weatherby,Gerard
https://docs.python.org/3/library/decimal.html Get Outlook for iOS From: Python-list on behalf of Paul St George Sent: Saturday, December 17, 2022 6:51:17 AM To: python-list@python.org Subject: String to Float, without introducing errors

Re: pip/setuptools: Entry points not visible from pkexec-root-environment

2022-12-18 Thread Weatherby,Gerard
"sudo python3 -m pip install -e ." You’ve already started down a problematic road. I recommend installing root level Python packages through your system package manager. (apt for debian, or whatever RedHat is using now). If a package you need isn’t available from the system level virtual envir

Re: Installation hell

2022-12-19 Thread Weatherby,Gerard
Personally, I don’t use Windows and avoid it like the plague. Python is easy to install on Linux and Mac. I’d start here: https://learn.microsoft.com/en-us/visualstudio/python/overview-of-python-tools-for-visual-studio?view=vs-2022 From: Python-list on behalf of Jim Lewis Date: Sunday, Dece

Re: Installation hell

2022-12-19 Thread Weatherby,Gerard
: Python-list on behalf of Thomas Passin Date: Monday, December 19, 2022 at 11:05 AM To: python-list@python.org Subject: Re: Installation hell *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 12/19/2022 9:59 AM, Weatherby,Gerard

Re: pygame.midi input/output not working

2022-12-22 Thread Weatherby,Gerard
https://github.com/pygame/pygame/issues/3522 From: Python-list on behalf of Peter J. Holzer Date: Thursday, December 22, 2022 at 5:06 AM To: python-list@python.org Subject: Re: pygame.midi input/output not working On 2022-12-21 17:23:47 -0500, Thomas Passin wrote: > The pygame web site says th

Re: NoneType List

2022-12-31 Thread Weatherby,Gerard
Just use the addition operator: a = [1,2] a = a + [3,4] a is now [1, 2, 3, 4] From: Python-list on behalf of Goran Ikac Date: Saturday, December 31, 2022 at 1:53 AM To: python-list@python.org Subject: NoneType List *** Attention: This is an external email. Use caution responding, opening a

Re: What should go to stdout/stderr and why Python logging write everything to stderr?

2023-01-03 Thread Weatherby,Gerard
Really doesn’t have much to do with Python and very much with standard streams, which go back as far as the 1950s. https://en.wikipedia.org/wiki/Standard_streams When a user types -h / --help to a Python argparse script, the output of the script is the help message. The standard behavior is to

Re: What should go to stdout/stderr and why Python logging write everything to stderr?

2023-01-03 Thread Weatherby,Gerard
If sys.stdout is a tty, it typically flushes on newline. e. g. !/usr/bin/env python3 import time import sys print("No flush",end='',file=sys.stdout) time.sleep(2) print("flushed",file=sys.stdout) time.sleep(5) will print the “flushed” 5 seconds before the script ends From: Python-list on behal

Re: What should go to stdout/stderr and why Python logging write everything to stderr?

2023-01-04 Thread Weatherby,Gerard
Dealing with stdout / stderr is bash is just syntax. I don’t always remember it off the top of my head but … stackoverflow.com. On Linux at least it’s possible to pipe to arbitrary streams, it seems. The following uses bash to write “Hi” to the file “third” opened by Python. I determined the fi

Re: No solution for "--verbose" (on stdout) output in Pythonds standard library?

2023-01-04 Thread Weatherby,Gerard
A couple options. The -vvv is more of Linux thing rather than Pythonic, to my way of thinking. import argparse parser = argparse.ArgumentParser() parser.add_argument('-v',action='store_true') parser.add_argument('-vv',action='store_true') parser.add_argument('-vvv',action='store_true') args = p

Re: What should go to stdout/stderr and why Python logging write everything to stderr?

2023-01-05 Thread Weatherby,Gerard
logging.basicConfig() logging.info(“Nice to know”) logging.debug(“Details for when things are funky”) logging.warn(“Trouble is brewing”) From: Python-list on behalf of Grant Edwards Date: Thursday, January 5, 2023 at 3:31 PM To: python-list@python.org Subject: Re: What should go to stdout/stde

Python logging (was Re: What should go to stdout/stderr and why Python logging write everything to stderr?)

2023-01-06 Thread Weatherby,Gerard
FWIW, it wasn’t too difficult to build a logging handler to send messages to Slack. https://pypi.org/project/slack-webclient-logger/ -- https://mail.python.org/mailman/listinfo/python-list

Re: To clarify how Python handles two equal objects

2023-01-10 Thread Weatherby,Gerard
For clarification, equality is not identity in Python. e.g. x = 7 y = 7.0 print(x == y) print(x is y) Will return True False Full explanation at https://docs.python.org/3/reference/expressions.html#comparisons From: Python-list on behalf of Chris Angelico Date: Tuesday, January 10, 2023 at

Re: Fast lookup of bulky "table"

2023-01-15 Thread Weatherby,Gerard
That’s about what I got using a Python dictionary on random data on a high memory machine. https://github.com/Gerardwx/database_testing.git It’s not obvious to me how to get it much faster than that. From: Python-list on behalf of Dino Date: Sunday, January 15, 2023 at 1:29 PM To: python-lis

Re: Fast lookup of bulky "table"

2023-01-15 Thread Weatherby,Gerard
I think any peformance improvements would have to come from a language change or better indexing of the data. From: Python-list on behalf of Weatherby,Gerard Date: Sunday, January 15, 2023 at 2:25 PM To: Dino , python-list@python.org Subject: Re: Fast lookup of bulky "table" Th

Re: Fast lookup of bulky "table"

2023-01-15 Thread Weatherby,Gerard
With Postgresql, one can also do pre-processing in Python. https://www.postgresql.org/docs/15/plpython.html While it’s not as convenient to develop as client-side Python, it can be used to implement complicated constraints or implement filtering on the server side, which reduces the amount of d

Re: Improvement to imports, what is a better way ?

2023-01-18 Thread Weatherby,Gerard
In the body of the code, if every time an external identifier is used it must be prefixed by a full 'path', the cognitive "burden" shifts from the aspect highlighted (above), to a reading-burden. As the fictional Jack McCoy ( https://en.wikipedia.org/wiki/Jack_McCoy) would say -- Objection: Assu

Re: A natural magnet for the craziest TKinter lovers out there

2023-01-19 Thread Weatherby,Gerard
Works fine on my work machine. (Ubuntu 20.04 / 32 G / 32 CPUS). Scalene (https://github.com/plasma-umass/scalene) shows it using 9 MB of memory. From: Python-list on behalf of Michael Torrie Date: Wednesday, January 18, 2023 at 8:58 PM To: python-list@python.org Subject: Re: A natural magnet

Re: tree representation of Python data

2023-01-21 Thread Weatherby,Gerard
https://docs.python.org/3/library/pprint.html From: Python-list on behalf of Dino Date: Saturday, January 21, 2023 at 11:42 AM To: python-list@python.org Subject: tree representation of Python data *** Attention: This is an external email. Use caution responding, opening attachments or clicki

Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

2023-01-22 Thread Weatherby,Gerard
Argparse is for parsing command line arguments and options. If you just want to evaluate an Python expression, use eval( ) Your string isn’t valid Python due to order of operations, but -(4^2)+5.3*abs(-2-1)/2 is. From: Python-list on behalf of Jach Feng Date: Sunday, January 22, 2023 at 11:2

Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument? WRONG TOOL

2023-01-24 Thread Weatherby,Gerard
I understand we all want to be helpful and friendly, but it seems to me that helping someone use the wrong tool for the job isn’t really helpful in the long run. argparse is for parsing command line arguments. It’s the wrong tool for this job. As Chris Angelico already said: This entire threa

Re: bool and int

2023-01-24 Thread Weatherby,Gerard
Booleans work exactly the way the language documentation says they work: Booleans (bool) These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is

Re: bool and int

2023-01-24 Thread Weatherby,Gerard
https://peps.python.org/pep-0285/ From: Python-list on behalf of rbowman Date: Tuesday, January 24, 2023 at 3:01 PM To: python-list@python.org Subject: Re: bool and int bool is a subtype of integer. I never dug that deep into Python's guts but I assume it goes back to boolean being an aftert

Re: How to make argparse accept "-4^2+5.3*abs(-2-1)/2" string argument?

2023-01-25 Thread Weatherby,Gerard
Use a different prefix character parser = argparse.ArgumentParser(prefix_chars='%') parser.add_argument('expression') args = parser.parse_args() print(args.expression) argparser is for allowing multiple command line options to be passed, providing default, controlling the number

Re: bool and int

2023-01-26 Thread Weatherby,Gerard
I can’t help but wonder if there exists some Java forum /mailing list going on about how horrible Python is. From: Python-list on behalf of rbowman Date: Wednesday, January 25, 2023 at 12:25 PM To: python-list@python.org Subject: Re: bool and int *** Attention: This is an external email. Use

Re: Custom help format for a choice argparse argument

2023-01-27 Thread Weatherby,Gerard
Why not something like: parser.add_argument("-z", "--zone") args = parser.parse_args() if args.zone and args.zone not in ptyz.all_timezones: print(“Invalid timezone”,file=sys.stderr) … From: Python-list on behalf of Ivan "Rambius" Ivanov

Unix / linux programs

2023-01-28 Thread Weatherby,Gerard
The Unix convention is 0 means everything went well, and non-zero means something else happened. Here’s a contrived example of a bash wrapper around GNU tar. By contrived I mean it works but I would not use it in practice … I’d just use tar directly or use the Python tarfile module if I wanted f

Non int Boolean

2023-01-28 Thread Weatherby,Gerard
If someone really really wants a non-int Boolean, it is easy to implement. 5 or 6 lines, depending on whether you count the import statement: from enum import Enum class MyBool(Enum): TRUE = 42 FALSE = 54 def __bool__(self): return self == MyBool.TRUE # # testing # mytru

Re: evaluation question

2023-01-31 Thread Weatherby,Gerard
import io def countprint(*args, **kwargs): capturekw = {k:v for k,v in kwargs.items() if k != 'file'} buffer = io.StringIO() capturekw['file'] = buffer print(*args,**kwargs) print(*args,**capturekw) return len(buffer.getvalue()) def boolprint(*args,active:bool, **kwargs):

Re: Organizing modules and their code

2023-02-04 Thread Weatherby,Gerard
You’re overthinking it. It doesn’t really matter. Having small chunks of codes in separate files can be hassle when trying to find out what the program does. Having one file with 2,000 lines in it can be a hassle. This is art / opinion, not science. From: Python-list on behalf of transreduct

Re: Typing Number, PyCharm

2023-02-05 Thread Weatherby,Gerard
dn, I’m missing something here. Method 5 seems to work fine in PyCharm. I’m interpreting your statement as: from fractions import Fraction from numbers import Number def double(value: Number): if isinstance(value, Number): # noinspection PyTypeChecker return 2 * value r

Re: Organizing modules and their code

2023-02-05 Thread Weatherby,Gerard
Well, first of all, while there is no doubt as to Dijkstra’s contribution to computer science, I don’t think his description of scientific thought is correct. The acceptance of Einstein’s theory of relativity has nothing to do with internal consistency or how easy or difficult to explain but rat

Re: Typing Number, PyCharm

2023-02-06 Thread Weatherby,Gerard
uble(value: Numeric): if isinstance(value, Numeric): return 2 * value raise ValueError(f"{value} of {type(value)} is not Numeric") works (>= 3.10) From: dn Date: Sunday, February 5, 2023 at 2:54 PM To: Weatherby,Gerard , 'Python' Subject: Re: Typing Number,

Re: Typing Number, PyCharm

2023-02-06 Thread Weatherby,Gerard
nd the Decimal definition I’m finding says: class Decimal(object): yet print(issubclass(Decimal,Number)) returns True. From: Paul Bryan Date: Monday, February 6, 2023 at 9:25 AM To: Weatherby,Gerard , dn , 'Python' Subject: Re: Typing Number, PyCharm *** Attention: This is an ext

Re: Tool that can document private inner class?

2023-02-07 Thread Weatherby,Gerard
Yes. Inspect module import inspect class Mine: def __init__(self): self.__value = 7 def __getvalue(self): """Gets seven""" return self.__value mine = Mine() data = inspect.getdoc(mine) for m in inspect.getmembers(mine): if '__getvalue' in m[0]: d

Re: Tool that can document private inner class?

2023-02-08 Thread Weatherby,Gerard
No. I interpreted your query as “is there something that can read docstrings of dunder methods?” Have you tried the Sphinx specific support forums? https://www.sphinx-doc.org/en/master/support.html From: Ian Pilcher Date: Tuesday, February 7, 2023 at 4:01 PM To: Weatherby,Gerard , python

Re: evaluation question

2023-02-13 Thread Weatherby,Gerard
“Why are we even still talking about this?” Because humans are social creatures and some contributors to the list like to discuss things in depth. From: Python-list on behalf of avi.e.gr...@gmail.com Date: Friday, February 10, 2023 at 6:19 PM To: python-list@python.org Subject: RE: evaluati

Re: Precision Tail-off?

2023-02-14 Thread Weatherby,Gerard
Use Python3 Use the decimal module: https://docs.python.org/3/library/decimal.html From: Python-list on behalf of Stephen Tucker Date: Tuesday, February 14, 2023 at 2:11 AM To: Python Subject: Precision Tail-off? *** Attention: This is an external email. Use caution responding, opening att

Re: Precision Tail-off?

2023-02-15 Thread Weatherby,Gerard
All languages that use IEEE floating point will indeed have the same limitations, but it is not true that Python3 only uses IEEE floating point. Using the Decimal class and cribbing a method from StackOverflow, https://stackoverflow.com/questions/47191533/how-to-efficiently-calculate-cube-roots-

Re: Python: How to use the 'trace' module programmatically?

2023-02-15 Thread Weatherby,Gerard
Have you tried the filter options? “These options may be repeated multiple times. --ignore-module= Ignore each of the given module names and its submodules (if it is a package). The argument can be a list of names separated by a comma. --ignore-dir= Ignore all modules and packages in the named di

Re: LRU cache

2023-02-16 Thread Weatherby,Gerard
I think this does the trick: https://gist.github.com/Gerardwx/c60d200b4db8e7864cb3342dd19d41c9 #!/usr/bin/env python3 import collections import random from typing import Hashable, Any, Optional, Dict, Tuple class LruCache: """Dictionary like storage of most recently inserted values"""

Re: Precision Tail-off?

2023-02-17 Thread Weatherby,Gerard
IEEE did not define a standard for floating point arithmetics. They designed multiple standards, including a decimal float point one. Although decimal floating point (DFP) hardware used to be manufactured, I couldn’t find any current manufacturers. There was a company that seemed to be active u

Re: Python + Vim editor

2023-02-21 Thread Weatherby,Gerard
Vim 2% of the time, PyCharm (with VI plugin) 98% of the time. From: Python-list on behalf of Hen Hanna Date: Tuesday, February 21, 2023 at 9:38 PM To: python-list@python.org Subject: Python + Vim editor *** Attention: This is an external email. Use caution responding, opening attachments or c

Re: Creating logs with Python

2023-02-22 Thread Weatherby,Gerard
https://docs.python.org/3/howto/logging.html From: Python-list on behalf of Bibi Date: Wednesday, February 22, 2023 at 9:44 AM To: python-list@python.org Subject: Creating logs with Python *** Attention: This is an external email. Use caution responding, opening attachments or clicking on lin

Re: Line continuation and comments

2023-02-22 Thread Weatherby,Gerard
That’s a neat tip. End of line comments work, too x = (3 > 4 #never and 7 == 7 # hopefully or datetime.datetime.now().day > 15 # sometimes ) print(x) From: Python-list on behalf of Edmondo Giovannozzi Date: Wednesday, February 22, 2023 at 9:40 AM To: python-list@python.org Su

Re: Line continuation and comments

2023-02-23 Thread Weatherby,Gerard
“ NB my PyCharm-settings grumble whenever I create an identifier which is only used once (and perhaps, soon after it was established). I understand the (space) optimisation, but prefer to trade that for 'readability'. “ I haven’t seen that one. What I get is warnings about: def is_adult( self )->b

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

2023-02-25 Thread Weatherby,Gerard
I only use asserts for things I know to be true. Nothing is harder to debug than when something you know to be true turns out to be… not True. Because I’ll check everything else instead of the cause of the bug. In other words, a failing assert means I have a hole in my program logic. For that u

Re: Is there a more efficient threading lock?

2023-02-25 Thread Weatherby,Gerard
“I'm no expert on locks, but you don't usually want to keep a lock while some long-running computation goes on. You want the computation to be done by a separate thread, put its results somewhere, and then notify the choreographing thread that the result is ready.” Maybe. There are so many poss

  1   2   >