Re: Trouble with defaults and timeout decorator

2023-06-24 Thread Piergiorgio Sartor via Python-list

On 24/06/2023 18.18, Jason Friedman wrote:

I'm writing a database connectivity module to be used by other modules and
leveraging the jaydebeapi module.

From what I can tell jaydebeapi contains no built-in timeout capability, so

then I turned to https://pypi.org/project/timeout-decorator/.
My goal is to have a default timeout of, say, 10 seconds, which can be
overridden by the caller.


import jaydebeapi
from timeout_decorator import timeout

class Database:
 database_connection = None
 database_name, user_name, password, host, port = stuff
 timeout = None

 def __init__(self, timeout=10):
 self.timeout = timeout

 @timeout(self.timeout)
 def get_connection(self):
 if not self.database_connection:
 self.database_connection = jaydebeapi.connect(some_args)
 return self.database_connection


The trouble occurs on line 12 with:
NameError: name 'self' is not defined


A quick search would return that "self"
is not available in the class body, only
in the class methods.

There are workarounds, but I guess not
simple ones, expecially for "timeout".

bye,

--

piergiorgio

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


Re: []=[]

2023-09-25 Thread Piergiorgio Sartor via Python-list

On 23/09/2023 09.41, Stefan Ram wrote:

[email protected] (Stefan Ram) writes:

[]=[]


   I was watching a video of a David Beazley talk "Python
   Concurrency From the Ground Up" , where he wrote

can_recv, can_send, [] = select(recv_wait, send_wait, [])

   . Later, he clarified that he actually wanted to write

can_recv, can_send, _ = select(recv_wait, send_wait, [])

   and that he was surprised how the "[]" gave no error.
   ("I wonder why that works.")


If you try:

[] = [1]

and check the error, it will be clear how it works.
Maybe not why... :-)

bye,

--

piergiorgio

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


Context without manager

2023-11-26 Thread Piergiorgio Sartor via Python-list

Hi all,

I apologize in advance for the "foggy"
question, but I've myself unclear ideas.

Anyway...

Python has "context manager".
For example, the "open()" class can be
simply used as follow:

with open(...) as fp:
  fp.do_something()

On the other hand, it is also possible to do:

fp = open()
fp.do_something()
fp.close()

Now, if we want to use "open()" in a class,
it would be possible to apply the second
variant, with "self.fp = open()" in "__init__(...)",
"self.fp.close()" maybe in "__del__(...)" and having
few methods doing this and that with the "self.fp".

Apparently, the "with" context manager is not usable
in classes, at least not with __init__() & co.

It seems there are classes ("gradio.Blocks()", for
example) which are *only* usable with context manager.

I found more...

One way to do the same as in "open()" is:

def __init__(...):
  fp = open(...)
  fp.__enter__()
...
def __del__(...):
  fp.__exit__()
  fp.close()

This works, but it seems quite ugly.
I could not find any other way, in case the
class do only support context manager.

Question: is there any other way to use a
context manager only object within a class,
with methods accessing the object?

Or any other solution to the same situation?

Thanks a lot in advance.

P.S.: currently gmail posts are deleted, due
to excessive spam, so I'll not see any reply
coming from this family of addresses.

bye,

--

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


Re: Context without manager

2023-11-27 Thread Piergiorgio Sartor via Python-list

On 26/11/2023 18.50, Dieter Maurer wrote:

Piergiorgio Sartor wrote at 2023-11-25 22:15 +0100:

...
Apparently, the "with" context manager is not usable
in classes, at least not with __init__() & co.


You can use `with` in classes -- with any context manager.
However, you would usually not use `with` with a file you have opened
in `__init__`.

If a class defines `__enter__` and `__exit__` (i.e.
the "cntext manager protocol"), then its instances
can be used with the `with` statement.

The important use case for a context manager is the
situation:
set up a context (--> method `__enter__`)
perform some operations in this context (--> body of `with` statement)
tear down the context (--> method `__exit__`).
If you do not have this case (e.g. usually if you open the file
in a class's `__init__`), you do not use a context manager.


Very clear, but what if the class is *not* "open()",
but something else _requiring_ using "with"?
How to do this in a "__init__()" of a class?

In other words, what if "open()" could *only* be used
with "with" and not just by assigning "fp = open()"?

The problem is I've some SDK of some device which
provides context manager *only* classes.

I *cannot* do:

device = device_open(...)
device.do_something()
device.close()

I *must* do:

with device_open() as device:
  device.do_something()

Nevertheless, I _need_ to have a class
where the device is opened in the __init__()
and used in some methods.

Any ideas?

bye,

--

piergiorgio

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


Re: How to enter multiple, similar, dictionaries?

2023-12-11 Thread Piergiorgio Sartor via Python-list

On 11/12/2023 16.16, Chris Green wrote:

Is there a way to abbreviate the following code somehow?

 lv = {'dev':'bbb', 'input':'1', 'name':'Leisure volts'}
 sv = {'dev':'bbb', 'input':'0', 'name':'Starter volts'}
 la = {'dev':'bbb', 'input':'2', 'name':'Leisure Amps'}
 sa = {'dev':'bbb', 'input':'3', 'name':'Starter Amps'}
 bv = {'dev':'adc2', 'input':0, 'name':'BowProp Volts'}

It's effectively a 'table' with columns named 'dev', 'input' and
'name' and I want to access the values of the table using the variable
name.

I could, obviously, store the data in a database (sqlite), I have some
similar data in a database already but the above sort of format in
Python source is more human readable and accessible.  I'm just looking
for a less laborious way of entering it really.



Maybe a dict of dicts:

tx = {lv: {'dev':'bbb', 'input':'1', 'name':'Leisure volts'},
  sv: {'dev':'bbb', 'input':'0', 'name':'Starter volts'},
  ...}

Might have one or two advantages.

bye,

--

piergiorgio

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


Re: Extract lines from file, add to new files

2024-01-11 Thread Piergiorgio Sartor via Python-list

On 11/01/2024 19.08, Rich Shepard wrote:

It's been several years since I've needed to write a python script so I'm
asking for advice to get me started with a brief script to separate names
and email addresses in one file into two separate files: salutation.txt and
emails.txt.

An example of the input file:

Calvin
[email protected]

Hobbs
[email protected]

Nancy
[email protected]

Sluggo
[email protected]

Having extracted salutations and addresses I'll write a bash script using
sed and mailx to associate a message file with each name and email address.


Why not to use bash script for all?

bye,

--

piergiorgio

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


Re: Can one output something other than 'nan' for not a number values?

2024-02-18 Thread Piergiorgio Sartor via Python-list

On 16/02/2024 23.12, Chris Green wrote:

I'm looking for a simple way to make NaN values output as something
like '-' or even just a space instead of the string 'nan'.  This would
then make it much easier to handle outputting values from sensors when
not all sensors are present.

So, for example, my battery monitoring program outputs:-

 Battery Voltages and Currents
 Leisure Battery - 12.42 volts  -0.52 Amps
 Starter Battery - 12.34 volts  -0.01 Amps

If the starter battery sensor has failed, or is disconnected, I see:-

 Battery Voltages and Currents
 Leisure Battery - 12.42 volts  -0.52 Amps
 Starter Battery -   nan voltsnan Amps


What I would like is for those 'nan' strings to be just a '-' or
something similar.

Obviously I can write conditional code to check for float('nan')
values but is there a neater way with any sort of formatting string or
other sort of cleverness?


Uhm, I cannot see how to avoid conditional code.

Somewhere, function, class, method, there should be
an "if isnan(x)".

You can hide that, but you cannot avoid, I suspect.

bye,

--

piergiorgio

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


Re: Multiplication

2024-04-01 Thread Piergiorgio Sartor via Python-list

On 01/04/2024 10.40, Stefan Ram wrote:

 Q: How can I multiply two variables in Python? I tried:
 
a = 2

b = 3
print( ab )

 but it did not work.

 A: No, this cannot work. To multiply, you need the multiplication
 operator. You can import the multiplication operator from "math":

 Code example:

from math import *

a = 2
b = 3
print( a * b )


I guess the operator "*" can be imported from any module... :-)

bye,

--

piergiorgio

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


Re: A technique from a chatbot

2024-04-02 Thread Piergiorgio Sartor via Python-list

On 02/04/2024 19.18, Stefan Ram wrote:

   Some people can't believe it when I say that chatbots improve
   my programming productivity. So, here's a technique I learned
   from a chatbot!
   
   It is a structured "break". "Break" still is a kind of jump,

   you know?
   
   So, what's a function to return the first word beginning with

   an "e" in a given list, like for example
   
[ 'delta', 'epsilon', 'zeta', 'eta', 'theta' ]


   ? Well it's
   
def first_word_beginning_with_e( list_ ):

 for word in list_:
 if word[ 0 ]== 'e': return word

   . "return" still can be considered a kind of "goto" statement.
   It can lead to errors:

def first_word_beginning_with_e( list_ ):
 for word in list_:
 if word[ 0 ]== 'e': return word
 something_to_be_done_at_the_end_of_this_function()
 
   The call sometimes will not be executed here!

   So, "return" is similar to "break" in that regard.
   
   But in Python we can write:
   
def first_word_beginning_with_e( list_ ):

 return next( ( word for word in list_ if word[ 0 ]== 'e' ), None )


Doesn't look a smart advice.


   . No jumps anymore, yet the loop is aborted on the first hit


First of all, I fail to understand why there
should be no jumps any more.
It depends on how "return" and "if" are handled,
I guess, in different context.
Maybe they're just "masked".
In any case, the "compiler" should have just
done the same.


   (if I guess correctly how its working).


Second, it is difficult to read, which is bad.
The "guess" above is just evidence of that.

My personal opinion about these "chatbots", is
that, while they might deliver clever solutions,
they are not explaining *why* these solutions
should be considered "clever".
Which is the most important thing (the solution
itself is _not_).

bye,

--

piergiorgio

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


Re: Terminal Emulator

2024-05-18 Thread Piergiorgio Sartor via Python-list

On 14/05/2024 19.44, Gordinator wrote:
I wish to write a terminal emulator in Python. I am a fairly competent 
Python user, and I wish to try a new project idea. What references can I 
use when writing my terminal emulator? I wish for it to be a true 
terminal emulator as well, not just a Tk text widget or something like 
that.


If you have any advice, please do let me know!


I would start writing down what this
"terminal emulator" should do.

Then, collect information about what
module / library can support the features.

bye,

--

piergiorgio

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


Re: Terminal Emulator (Posting On Python-List Prohibited)

2024-05-18 Thread Piergiorgio Sartor via Python-list

On 18/05/2024 20.04, Mats Wichmann wrote:
[...]
So venvs make managing all that pretty convenient. Dunno why everybody's 
so down on venvs...


Only people which are *not* using python... :-)

In my experience, venvs is the only possible
way to use python properly.

The dependency nightmare created by python, pip
and all the rest cannot be resolved otherwise.

It seems backward compatibility is a taboo...

bye,

--

piergiorgio

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


Re: venvs vs. package management

2024-05-19 Thread Piergiorgio Sartor via Python-list

On 19/05/2024 08.49, Peter J. Holzer wrote:
[...]

That's what package management on Linux is for. Sure, it means that you
won't have the newest version of anything and some packages not at all,
but you don't have to care about dependencies. Or updates.


Well, that doesn't work as well.
Distributions do not pack everything, this
also depending on licenses.

Sometimes, or often, you need to use the
*latest* version of something, due to some
bugfix or similar.

The distribution does not always keep up
to date everything, so you're stuck.

The only solution is a venv, with all
needed packages for the given task.

Typical problem with PyTorch / TensorFlow.

In case of trouble, the first answer is:
"Check with the latest (nightly) release".

Which means installing something *outside*
the Linux distribution support.
And this impossible, because this will pull
in dependencies like crazy, which are not
(yet) in the Linux distribution path.

Saying it differently, the latest greatest
update is not a wish, it's a must...

So, long story short, the only solution I
know are venvs...

Of course, other solutions are welcome!

bye,

--

piergiorgio

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


Re: Best (simplest) way to share data between processes

2024-07-07 Thread Piergiorgio Sartor via Python-list

On 06/07/2024 09.28, Chris Green wrote:

I have a Raspberry Pi in my boat that uses I2C to read a number of
voltages and currents (using ADS1115 A2D) so I can monitor the battery
condition etc.

At present various different scripts (i.e. processes) just read the
values using the I2C bus whenever they need to but I'm pretty sure
this (quite rarely) results in false readings because two processes
try to read at the same time.

Thus I'm looking for ways to prevent simultaneous access.


Why using "different scripts"?
Is it there any particular reason?

Maybe it would be better, if possible, to have
a single script, which, sequentially, reads
whatever needs to be read (or written).
In a loop.

This is even simpler than using a file.

bye,

pg


One fairly obvious way is to have single process/script which reads
the A2D values continuously and writes them to a file.  All other
scripts then read from the file as needed, a simple file lock can then
be used to prevent simultaneous access (well, simultaneous access when
the writing process is writing).

Is this the simplest approach?  Are there better ways using
multiprocess?  (They look more complicated though).

The I2C bus itself has a mutex but I don't think this guarantees that
(for example) an A2D reading is atomic because one reading takes more
than one I2C bus access.

Would a mutex of some sort around each I2C transaction (i.e. complete
A2D reading) be a better way to go?



--

piergiorgio

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


Re: Triggered By Mediocre Code (Posting On Python-List Prohibited)

2024-08-27 Thread Piergiorgio Sartor via Python-list

On 25/08/2024 23.53, Lawrence D'Oliveiro wrote:

Looking at this article about the top three languages for getting
programming jobs
,
naturally I couldn’t help noticing the code in the screenshot at the
top (my transcription):

 bufferedNumber = str(doc.GetTime().GetFrame(docFps))
 if len(bufferedNumber)<4:
 for x in range(len(bufferedNumber),4):
 bufferedNumber = "0" + bufferedNumber

I mean, really? Four lines to do what could be done in a single
expression?

Was that written by a PHP programmer, do you think?


That the more correct question would be:
What is easier to read? And to debug?
The four line version or the one liner?

To paraphrase someone:
"If the length of a program would be
measured by the time needed to understand
it, some program would be too short to
be short."

Because the world is plenty of one liner
nobody (almost) doesn't understand.

There is even a category in the OCC
(https://www.ioccc.org/).

Don't get me wrong, I like and dislike
one liner.
Namely, I like mine and dislike the others :-)

bye,

--

piergiorgio

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


Re: Two python issues

2024-11-06 Thread Piergiorgio Sartor via Python-list

On 05/11/2024 15.48, Raymond Boute wrote:

L.S.,

Python seem to suffer from a few poor design decisions regarding strings 
and lists that affect the elegance of the language.


(a) An error-prone "feature" is returning -1 if a substring is not found 
by "find", since -1 currently refers to the last item. An example:


 >>> s = 'qwertyuiop'
 >>> s[s.find('r')]
'r'
 >>> s[s.find('p')]
'p'
 >>> s[s.find('a')]
'p'
 >>>

If "find" is unsuccessful, an error message is the only clean option.
Moreover, using index -1 for the last item is a bad choice: it should be 
len(s) - 1 (no laziness!).
Negative indices should be reserved for elements preceding the element 
with index 0 (currently not implemented, but a must for orthogonal 
design supporting general sequences).


(b) When using assignment for slices, only lists with the same length as 
the slice should be acceptable, otherwise an error should be given. 
Anything that re-indexes items not covered by the slice is against the 
essential idea of assignment. For changes that imply re-indexing (e.g., 
inserting a list longer than the slice), Python offers cleaner solutions.


Comments are welcome.


To write the nested expression, s[s.find(...)] it
means you're 200% sure of what happens in case of
not found.
It could be -1 or None or [] or anything.

So, the really correct thing to do, since you know
what will happen in case of not found, is *not* to
write the nested form, but explicitly state what it
will happen.

r = s.find(...)
if r is good:
s[r]
else:
print('not found')

Which is much easier to read, to debug, etc.

To paraphrase someone: "If the length of a
program would be measured by the time needed
to understand it, some programs are too short
to be short."

bye,

--

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