Re: Friday finking: IDE 'macro expansions'

2023-03-18 Thread Weatherby,Gerard
I send ~99% of Python coding time in PyCharm. Likewise, IntelliJ and Clion for Java and C++, respectively. Mostly use: Tab completion for variable names Letting PyCharm figure out imports for me, and cleaning up old, unused imports. Jumping to definitions of symbols. Tellling me I’ve made a type

Re: Implementing a plug-in mechanism

2023-03-15 Thread Weatherby,Gerard
I do something similar to Thomas. (Also MIT licensed). I like objects. I like type hints. Each plugin needs to have check and purpose functions and accepts either PluginSpec (by default) or AddonSpec if it defines addon = True This requires a single-level plugin directory with no extra files

Re: Implementing a plug-in mechanism

2023-03-15 Thread Weatherby,Gerard
Yes, that works, and I’ve used that on a couple of projects. Another alternative is defining an Abstract Base Class, https://docs.python.org/3/library/abc.html, and having an institution-specific implementation passed into your module. From: Python-list on behalf of Loris Bennett Date:

Re: Debugging reason for python running unreasonably slow when adding numbers

2023-03-15 Thread Weatherby,Gerard
=100)) --- For Loop Sum: 6.984986504539847 Built-in Sum: 0.5175364706665277 From: Weatherby,Gerard Date: Wednesday, March 15, 2023 at 1:09 PM To: python-list@python.org Subject: Re: Debugging reason for python running unreasonably slow when adding numbers Sum is faster than iteration

Re: Debugging reason for python running unreasonably slow when adding numbers

2023-03-15 Thread Weatherby,Gerard
Sum is faster than iteration in the general case. Lifting a test program from Stack Overflow https://stackoverflow.com/questions/24578896/python-built-in-sum-function-vs-for-loop-performance, import timeit def sum1(): s = 0 for i in range(100): s += i return s def

Re: Distributing program for Linux

2023-03-14 Thread Weatherby,Gerard
It’s really going to depend on the distribution and whether you have root access. If you have Ubuntu and root access, you can add the deadsnakes repo, https://launchpad.net/~deadsnakes, and install whatever Python you want. The default ‘python3’ remains but you can called a specific Python,

Re: Tkinter and cv2: "not responding" popup when imshow launched from tk app

2023-03-14 Thread Weatherby,Gerard
Assuming you’re using opencv-python, I’d post query at https://github.com/opencv/opencv-python/issues. From: Python-list on behalf of John O'Hagan Date: Tuesday, March 14, 2023 at 6:56 AM To: Python list Subject: Tkinter and cv2: "not responding" popup when imshow launched from tk app ***

Re: Baffled by readline module

2023-03-10 Thread Weatherby,Gerard
on Date: Friday, March 10, 2023 at 5:15 PM To: python-list@python.org Subject: Re: Baffled by readline module *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 10Mar2023 09:12, Grant Edwards wrote: >On 2023-03-10, Weatherby,G

Re: Baffled by readline module

2023-03-10 Thread Weatherby,Gerard
Edwards Date: Friday, March 10, 2023 at 9:39 AM To: python-list@python.org Subject: Re: Baffled by readline module *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** On 2023-03-10, Weatherby,Gerard wrote: > I would say, “No, readl

Re: Baffled by readline module

2023-03-10 Thread Weatherby,Gerard
I would say, “No, readline is not the right tool.” cmd.Cmd is: https://docs.python.org/3/library/cmd.html. I have a couple of cmd.Cmd modules, one of which I use daily and the other weekly. From: Python-list on behalf of Grant Edwards Date: Thursday, March 9, 2023 at 2:29 PM To:

Re: Lambda returning tuple question, multi-expression

2023-03-09 Thread Weatherby,Gerard
Other than the admittedly subjective viewpoint that using the lambda is confusing, there’s probably nothing wrong with the lambda approach. A couple of alternatives: def e(): for e in (e1,e2,e3): e.config(state="normal") b = tk.Button(master=main, text="Enable",command=e) or b

Re: Bug 3.11.x behavioral, open file buffers not flushed til file closed.

2023-03-06 Thread Weatherby,Gerard
Add f.reconfigure it you want line buffering in your example: f = open("abc", "w") f.reconfigure(line_buffering=True) for i in range(5): f.write(str(i) + "\n") More Pythonic would be: with open("abc", "w") as f: for i in range(5000): print(i,file=f) From: Python-list on

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

2023-03-06 Thread Weatherby,Gerard
“Dino, Sending lots of data to an archived forum is not a great idea. I snipped most of it out below as not to replicate it.” Surely in 2023, storage is affordable enough there’s no need to criticize Dino for posting complete information. If mailing space is a consideration, we could all help

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

2023-03-06 Thread Weatherby,Gerard
Not sure if this is what Thomas meant, but I was also thinking dictionaries. Dino could build a set of dictionaries with keys “a” through “z” that contain data with those letters in them. (I’m assuming case insensitive search) and then just search “v” if that’s what the user starts with.

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

2023-03-04 Thread Weatherby,Gerard
Nope. No consensus. I’d use self.__class__ . Seems more explicit and direct to me. From: Python-list on behalf of Ian Pilcher Date: Thursday, March 2, 2023 at 4:17 PM To: python-list@python.org Subject: Which more Pythonic - self.__class__ or type(self)? *** Attention: This is an external

Re: Python list insert iterators

2023-03-04 Thread Weatherby,Gerard
Python lists are arrays in other languages. You’ll have to roll your own or find something in https://pypi.org, etc. I think this incomplete implementation does the trick. # # MIT licensed # from dataclasses import dataclass from typing import TypeVar, Generic T = TypeVar("T") @dataclass

Re: Packing Problem

2023-03-02 Thread Weatherby,Gerard
Haven’t look at it all in detail, but I’d replace the list comprehensions with a loop: CopyOfWords = list(Words) Words = [(w[1:] if w[0] == ch else w) for w in Words] Words = [w for w in Words if w != ''] nextWords = [] for w in CopyOfWords:

Re: Look free ID genertion (was: Is there a more efficient threading lock?)

2023-03-01 Thread Weatherby,Gerard
So I guess we know what would have happened. Get Outlook for iOS From: Python-list on behalf of Chris Angelico Sent: Wednesday, March 1, 2023 8:45:50 PM To: python-list@python.org Subject: Re: Look free ID genertion (was: Is there a more

Re: How to escape strings for re.finditer?

2023-02-28 Thread Weatherby,Gerard
Regex is fine if it works for you. The critiques – “difficult to read” –are subjective. Unless the code is in a section that has been profiled to be a bottleneck, I don’t sweat performance at this level. For me, using code that has already been written and vetted is the preferred approach to

Python type system

2023-02-27 Thread Weatherby,Gerard
When I first started transitioning to Python as a Perl replacement, with my Java/C++ baggage, I thought Pythnon had some loosey-goosey type system. I thought int() and str() were casts, not constructors. I now realize Python has a great strong type system. Duck typing. If it walks like a duck,

Programming by contract.

2023-02-25 Thread Weatherby,Gerard
The discussion of asserts got me thinking about Programming by Contract. Back in the 90s, I had occasion to learn Eiffel programming language. ( https://en.wikipedia.org/wiki/Eiffel_(programming_language) The concepts are intriguing, although Eiffel itself had barriers to widespread adoption.

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

2023-02-25 Thread Weatherby,Gerard
of Peter J. Holzer Date: Saturday, February 25, 2023 at 5:21 PM To: python-list@python.org Subject: Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ? On 2023-02-25 21:58:18 +, Weatherby,Gerard wrote: > I only use asserts for things I know to be true. Yeah, tha

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

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

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

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

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

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

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

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: 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

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,

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

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:

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: 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: Typing Number, PyCharm

2023-02-06 Thread Weatherby,Gerard
l-type And 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 external emai

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: 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

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

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

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):

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 #

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

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

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: 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

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

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

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

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

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

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: 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:

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

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
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:

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

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: 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

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 =

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

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

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: 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

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

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: 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,

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

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: 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,

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

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

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

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: 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

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' +

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,

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

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,

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: 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:

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: Python-list

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: 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: 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 =

Re: Preprocessing not quite fixed-width file before parsing

2022-11-23 Thread Weatherby,Gerard
data = f"{' '.join(hparts)} | {tail}" return fixed_data return data except: logging.exception("read") logging.basicConfig() with Wrapper('data.txt') as f: df = pandas.read_csv(f, delimiter=r"\s+") print(df) From: Weath

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: 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: 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

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: 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: 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

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: 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

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

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

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: 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

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

  1   2   >