Re: Canonical list of Python security vulnerabilities

2023-07-15 Thread Dieter Maurer via Python-list
Bob Kline wrote at 2023-7-14 13:35 -0400:
>Can someone point me to the official catalog of security vulnerabilities in
>Python (by which I mean cpython and the standard libraries)? I found
>https://www.cvedetails.com/vulnerability-list/vendor_id-10210/product_id-18230/Python-Python.html
>but that isn't maintained by python.org.

I am active in the `Zope` community (a web application server
based on Python). This community has a security mailing list
for security related reports
and issues public CVE (= "Commun Vulnerabilities and Exposures") reports
(via a "GitHUB" service) as soon as a security risk has been resolved.

I expect that security risks for Python itself are handled in
a similar way (as, Python too, maintains its code on "GitHUB").
This means that the CVE dictionary should contain **ALL**
publicly announced security risk reports whether found by
the Pyhton community or packagers.

For details about CVE, read
"https://en.wikipedia.org/wiki/Common_Vulnerabilities_and_Exposures";.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Meta Class Maybe?

2023-07-23 Thread Dieter Maurer via Python-list
Chris Nyland wrote at 2023-7-22 19:12 -0400:
>So I am stuck on a problem. I have a class which I want to use to create
>another class without having to go through the boiler plate of subclassing.

Do you know about `__init_subclass__`?
It is called whenever a class is subclassed and can be used to
check/update the newly created class.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fallback for operator and other dunder methods

2023-07-26 Thread Dieter Maurer via Python-list
Dom Grigonis wrote at 2023-7-26 05:22 +0300:
> ...
>Is there a way to achieve it without actually implementing operators?
>I have looked at Proxy objects, but they do not seem suited to achieve this.

Proxying is a good approach:
you might have a look at `dm.reuse.proxy.OverridingProxy` (--> `dm.reuse`
on PyPI).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to find the full class name for a frame

2023-08-04 Thread Dieter Maurer via Python-list
Jason Friedman wrote at 2023-8-3 21:34 -0600:
> ...
>my_frame = inspect.currentframe()
> ...
>My question is: let's say I wanted to add a type hint for my_frame.

`my_frame` will be an instance of `Types.FrameType`.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Dieter Maurer via Python-list
[email protected] wrote at 2023-8-17 07:10 +:
>I want to display one string in its original source (untranslated)
>version and in its translated version site by site without duplicating
>the string in the python source code?

Is it an option for you to replace the `gettext` binding
by `zope.i18nmessageid`? Its `Message` instances provide
access to all interesting attributes (id, default, mapping, domain).
Together with other packages (--> `zope.i18n` and `i18ndude`)
it is compatible with `GNU gettext` translation catalogs.

If this is not an option, use Python's inspection functionality
to learn which attributes are made available by the binding's
message class.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GNU gettext: Print string translated and untranslated at the same time

2023-08-17 Thread Dieter Maurer via Python-list
[email protected] wrote at 2023-8-17 07:10 +:
>I want to display one string in its original source (untranslated)
>version and in its translated version site by site without duplicating
>the string in the python source code?

You could try to translate into an unknown language: this
should give you the default translation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Passing info to function used in re.sub

2023-09-04 Thread Dieter Maurer via Python-list
Jan Erik Moström wrote at 2023-9-3 18:10 +0200:
>I'm looking for some advice for how to write this in a clean way
> ...
>The "problem" is that I've currently written some code that works but it uses 
>global variables ... and I don't like global variables. I assume there is a 
>better way to write this, but how?

You could define a class with a `__call__` method
and use an instance of the class as replacement.
The class and/or instance can provide all relevant information via
attributes.

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


Re: How to write list of integers to file with struct.pack_into?

2023-10-02 Thread Dieter Maurer via Python-list
Jen Kris wrote at 2023-10-2 00:04 +0200:
>Iwant to write a list of 64-bit integers to a binary file.  Everyexample I 
>have seen in my research convertsit to .txt, but I want it in binary.  I wrote 
>this code,based on some earlier work I have done:
>
>buf= bytes((len(qs_array)) * 8)
>
>for offset in range(len(qs_array)):
>  item_to_write= bytes(qs_array[offset])
>  struct.pack_into(buf,"
>But I get the error "struct.error: embedded null character."

You made a lot of errors:

 * the signature of `struct.pack_into` is
   `(format, buffer, offset, v1, v2, ...)`.
   Especially: `format` is the first, `buffer` the second argument

 * In your code, `offset` is `0`, `1`, `2`, ...
   but it should be `0 *8`, `1 * 8`, `2 * 8`, ...

 * The `vi` should be something which fits with the format:
   integers in your case. But you pass bytes.

Try `struct.pack_into("https://mail.python.org/mailman/listinfo/python-list


Re: Simple webserver

2023-10-22 Thread Dieter Maurer via Python-list
Janis Papanagnou wrote at 2023-10-21 04:03 +0200:
> ...
>I'd like to ask; where do you see the specific risks with Python
>(as language per se) and it's (web-socket-)libraries here?

The web server in Python's runtime library is fairly simple,
focusing only on the HTTP requirements.

You might want additional things for an HTTP server
exposed on the internet which should potentially handle high trafic:
e.g.

 * detection of and (partial) protection against denial of service attacks,
 * load balancing,
 * virtual hosting
 * proxing
 * URL rewriting
 * high throughput, low latency

Depending on your requirements, other web servers might be preferable.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question(s)

2023-10-25 Thread Dieter Maurer via Python-list
o1bigtenor wrote at 2023-10-24 07:22 -0500:
> ...
>Is there a way to verify that a program is going to do what it is
>supposed to do even
>before all the hardware has been assembled and installed and tested?

Others have already noted that "verify" is a very strong aim.

There are different kinds of errors.

Some can be avoided by using an integrated development environment
(e.g. misspellings, type mismatches, ...).

Some can be found via tests.
Look at Python's "unittest" package for learn how to write tests.
"unittest.mock" can help you to mockup hardware you do not yet have.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Simple webserver

2023-10-25 Thread Dieter Maurer via Python-list
Frank Millman wrote at 2023-10-25 09:57 +0200:
> ...
>Based on this, I am considering the following -
>
>1. Replace my HTTP handler with Uvicorn. Functionality should be the
>same, but performance should be improved.
>
>2. Instead of running as a stand-alone server, run my app as a
>reverse-proxy using Nginx. I tested this a few years ago using Apache,
>and it 'just worked', so I am fairly sure that it will work with Nginx
>as well. Nginx can then provide the additional functionality that Dieter
>has mentioned.

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


Re: Question(s)

2023-10-25 Thread Dieter Maurer via Python-list
o1bigtenor wrote at 2023-10-25 06:44 -0500:
>On Wed, Oct 25, 2023 at 6:24?AM Dieter Maurer  wrote:
> ...
>> There are different kinds of errors.
>>
>> Some can be avoided by using an integrated development environment
>> (e.g. misspellings, type mismatches, ...).
>
>Haven't heard of a python IDE - - - doesn't mean that there isn't such - -
>just that I haven't heard of such. Is there a python IDE?

There are several.

Python comes with "IDLE".

There are several others,
e.g. "ECLIPSE" can be used for Python development.
Search for other alternatices.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question(s)

2023-10-25 Thread Dieter Maurer via Python-list
o1bigtenor wrote at 2023-10-25 07:50 -0500:
>> There are several others,
>> e.g. "ECLIPSE" can be used for Python development.
>
>Is 'Eclipse' a Windows oriented IDE?

No.
==> "https://en.wikipedia.org/wiki/Eclipse_(software)"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question(s)

2023-10-25 Thread Dieter Maurer via Python-list
o1bigtenor wrote at 2023-10-25 08:29 -0500:
> ...
>It would appear that something has changed.
>
>Went to the Eclipse download page, downloaded and verified (using sha-512).
>Expanded software to # opt .
>There is absolutely NO mention of anything python - - - java, c and
>its permutations,
>'scientific computing', and some others but nothing python.
>
>I may be missing something due to an extreme lack of knowledge.
>
>Please advise as to where I might find the 'python' environment in eclipse.

I entered "eclipse python download" in my favorite search engine
(=> "ecosia.org") and the second hit gave:
"https://marketplace.eclipse.org/content/pydev-python-ide-eclipse";.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: NameError: name '__version__' is not defined

2023-10-27 Thread Dieter Maurer via Python-list
Loris Bennett wrote at 2023-10-27 09:29 +0200:
> ...
>For the application with the system Python this mechanism works, but for
>the non-system Python I get the error:
>
>  NameError: name '__version__' is not defined

If you get exceptions (they usually end in `Error` (such as `NameError`)),
look at the traceback. The traceback informs you about
the calling context that led to the exception, espeically where
in the code the exception occurred.

If you cannot resolve the problem at your own,
include the traceback in your call for assistence.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to find any documentation for smbus?

2023-10-30 Thread Dieter Maurer via Python-list
Chris Green wrote at 2023-10-28 17:08 +0100:
>I am using the python3 smbus module, but it's hard work because of the
>lack of documentation.  Web searches confirm that the documentation is
>somewhat thin!
>
>If you do the obvious this is what you get:-
>
>>>> import smbus
>>>> dir (smbus)
>['SMBus', '__doc__', '__file__', '__loader__', '__name__', '__package__', 
> '__spec__']
>>>> help(smbus)
> ...

What does `help(smbus.SMBus`) tell you?

Almost surely, `SMBus` is a class providing the main access methods.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pip/pip3 confusion and keeping up to date

2023-11-02 Thread Dieter Maurer via Python-list
Chris Green wrote at 2023-11-2 10:58 +:
> ...
>So, going on from this, how do I do the equivalent of "apt update; apt
>upgrade" for my globally installed pip packages?

`pip list -o` will tell you for which packages there are upgrades
available.
`pip install -U ...` will upgrade packages.

Be careful, though.
With `apt`, you usually have (`apt`) sources representing a consistent
package universe. Someone tests that package upgrades in this
universe do not break other packages (in this universe).
Because of this, upgrading poses low risk.

`PyPI` does not guarantes consistency. A new package version
may be incompatible to a previous one -- and with other
package you have installed.

I do not think that you would want to auto-upgrade all installed
packages.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pip/pip3 confusion and keeping up to date

2023-11-03 Thread Dieter Maurer via Python-list
Karsten Hilbert wrote at 2023-11-3 14:47 +0100:
> ...
>> Are they not available in your system's package manager?
>
>... this clearly often answers to "no" for applications of
>any complexity.
>
>Is there a suggested proper path to deal with that (Debian is
>of interest to me here) ?

Complex applications may maintain a set of "known workable versions"
associated with the application's releases.
They may describe those "known workable versions" in a `pip` constraint file.
In this case, you can upgrade to a new application release
by using this constraint file.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pip/pip3 confusion and keeping up to date

2023-11-06 Thread Dieter Maurer via Python-list
Karsten Hilbert wrote at 2023-11-5 23:19 +0100:
> ...
>do you happen to know where to read up on how to fit a pip
>constraint file into a Debian package creation workflow ?

I have only rudimentary `apt` knowledge.

I know it is quite flexible, e.g. it used to handle `flash`
in a special way. I expect it flexible enough to load from `PyPI`.

`apt` is essentially controlled by a set of `sources`.
Each "source" describes a list of package distributions.
A description contains metadata about the distribution
including name, version, description, dependencies, incompatibilities, etc.

Any integration would require you to define one or more
"source"s, listing the distributions which should come from `PyPI`.
This would allow you to specify potential upgrades at a central
place, the "source"s, you control.
It would not solve the more fundamental problem: to determine
which versions are compatible with the universe of (all the
"sources" described) package versions.


I know that debian packagers create debian packages
from Python distributions not using the approach sketched above
and likely they have their reasons.

You might want to discuss this on an `apt` related mailing list.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Detect naming typos (AttributeError) in function names

2023-11-06 Thread Dieter Maurer via Python-list
[email protected] wrote at 2023-11-6 12:47 +:
>I would like to know how to detect (e.g. via a linter) typos in function
>names imported from another module.

One option is a test suite (--> Python's "unittest" package)
with a sufficiently high coverage (near 100 %).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __set_name__ equivalent for instance

2023-11-16 Thread Dieter Maurer via Python-list
Dom Grigonis wrote at 2023-11-15 18:44 +0200:
>So there is a method __set_name__ which is called on class creation.
>
>The functionality that I am interested in is not retrieving name, but the fact 
>that it also receives `owner` argument.
>
>Thus, allowing simulation of bound class method.
>
>I was wandering if there is an equivalent functionality of attribute to 
>receive `instance` argument on instance creation.

As PEP 487 describes, `__set_name__` essentially targets descriptors.
It is there to inform a descriptor about the name it is used for
in a class (and the class itself). There is no other (easy) way to allow
a descriptor to learn about this name.

If a descriptor is accessed via an instance, the descriptor (protocol)
methods get the instance as parameter.
Note that descriptors are stored in the class: they must not store
instance specific information in their attributes.
Therefore, a method informing an descriptor about instance creation
would not help: it cannot do anything with it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __set_name__ equivalent for instance

2023-11-16 Thread Dieter Maurer via Python-list
Dom Grigonis wrote at 2023-11-16 20:12 +0200:
>What I am interested in is a callback.
>Preferably just after methods get bound. So in `object.__new__`.

>I have done it via metaclass, but it is not ideal as there would be too much 
>overhead.
>
>I think what I am looking for is custom method binding.

Methods are not bound during instance creation, they are bound during
access.

You can use descriptors to implement "custom method binding".

Descriptors are defined on the class (and do not behave as
descriptors when defined on instances).
Thus, you would need a metaclass or `__inist_subclass__` is you
want your "custom method binding" globally.


For many methods (but usually not the `__...__` methods),
you can take over the binding in `__new__` or `__init__`
and populate the instance with prebound methods.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __set_name__ equivalent for instance

2023-11-16 Thread Dieter Maurer via Python-list
Dom Grigonis wrote at 2023-11-16 21:11 +0200:
> ...
>> On 16 Nov 2023, at 21:00, Dieter Maurer  wrote:
>> ...
>> Methods are not bound during instance creation, they are bound during
>> access.
>
>Good to know. What is the criteria for binding then? Does it check if its type 
>is `vanilla` function? If yes, is there any way to simulate it for arbitrary 
>object?

Attribute access (including method binding) is documented in the
language reference.

Functions and descriptors accessed via an instance but found in a class (i.e.
not directly in the instance) are handled specially;
functions are bound. Other objects are returned as is.

`__getattribute__` can be used to take over control over the attribute
access.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Context without manager

2023-11-26 Thread Dieter Maurer via Python-list
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.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extend behaviour of assignment operator

2024-01-10 Thread Dieter Maurer via Python-list
Guenther Sohler wrote at 2024-1-9 08:14 +0100:
>when i run this code
>
>a = cube([10,1,1])
>b = a
>
>i'd like to extend the behaviour  of the assignment operator
>a shall not only contain the cube, but  the cube shall also know which
>variable name it
>was assigned to, lately. I'd like to use that for improved user interaction.

`Acquisition` (--> `PyPI`) implements something similar.

It does not work for variables -- but for attribute access.
Look at the following code:

```
from Acquisition import Implicit

class AccessAwareContainer(Implicit):
  ...

class AccessAwareContent(Implicit):
 ...

container = AccessAwareContainer()
container.content = AccessAwareContent()
```

When you now assign `content = container.content`, then
`content` knows that it has been accessed via `container`.


If fact `content` is not a true `AccessAwareContent` instance
but a wrapper proxy for it. It mostly behaves like an
`AccessAwareContent` object but has additional information
(e.g. it knows the access parent).


It works via a special `__getattribute__` method, essentially
implemented by:

```
   def __getattribute__(self, k):
 v = super().__getattribute__(k)
 return v.__of__(self) if hasattr(v, "__of__") else v
```

Your use case could be implemented similarly (again not for variables
and all objects, but for special classes (and maybe special objects)).

Your `__getattribute__` could look like:
```
   def __getattribute__(self, k):
 v = super().__getattribute__(k)
 try:
   v.name = k
 except TypeError: pass
 return v
```
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Question about garbage collection

2024-01-15 Thread Dieter Maurer via Python-list
Frank Millman wrote at 2024-1-15 15:51 +0200:
>I have read that one should not have to worry about garbage collection 
>in modern versions of Python - it 'just works'.

There are still some isolated cases when not all objects
in an unreachable cycle are destroyed
(see e.g. step 2 of
"https://devguide.python.org/internals/garbage-collector/index.html#destroying-unreachable-objects";).
But Python's own objects (e.g. traceback cycles)
or instances of classes implemented in Python
should no longer be affected.

Thus, unless you use extensions implemented in C (with "legacy finalizer"s),
garbage collection should not make problems.


On the other hand, your application, too, must avoid memory leaks.
Caches of various forms (with data for several sessions) might introduce them.

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


Re: Await expressions (Posting On Python-List Prohibited)

2024-01-27 Thread Dieter Maurer via Python-list
>On 27/01/24 10:46 am, Stefan Ram wrote:
>>But your explanation seems to have no mention of the "something" /
>>"the awaitable object" part following the preposition "on". Shouldn't
>>this awaitable object play a rôle in the explanation of what happens?

You can explain a function call without saying much about the called function.
Similarly, you can explain "await " without saying much about
"".

Important is only: "" evaluates to an "awaitable".
An "awaitable" (usually an `asyncio.Future`, `asyncio.Task` or
call of an `async` function) eventuelly produces
a value and `await ` waits until
this happens and then returns this value.

Not everything which eventually returns a value is an
"awaitable" -- e.g. a call of `time.sleep` is not an "awaitable".
Special provisions are necessary to be able to wait for a value
(and meanwhile do other things).
`asyncio.sleep` has e.g. this provisions and a call of it is an "awaitable".

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


RE: Extract lines from file, add to new files

2024-01-29 Thread Dieter Maurer via Python-list
Rich Shepard wrote at 2024-1-29 08:15 -0800:
> ...
>If this explanation is not sufficiently clear I'll re-write it. :-)

Have you read "https://docs.python.org/3/library/io.html#module-io";?

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


Re: Error in Module

2024-03-11 Thread Dieter Maurer via Python-list
Sanskar Mukeshbhai Joshi wrote at 2024-3-10 18:08 +:
>I had made my project in BCA in Python. When I had complete my project and run 
>the program, at that time I got the error in runnig my project. The error was 
>ModuleNotFoundError: No module named 'flask'.

`flask` is not part of the Python library; it has to be installed separately.

Apparently, you project is a `flask` project (a Web application platform).
In this case, you must run your program in a special `flask`
environment.

I suggest you contact your project mentor to get help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Popping key causes dict derived from object to revert to object

2024-03-21 Thread Dieter Maurer via Python-list
Loris Bennett wrote at 2024-3-21 10:56 +0100:
> ...
>So as I understand it, I need to convert the InstanceState-objects to,
>say, dicts, in order to print them.  However I also want to remove one
>of the keys from the output and assumed I could just pop it off each
>event dict, thus:
>
>event_dicts = [vars(e) for e in events]
>print(type(event_dicts[0]))
>event_dicts = [e.pop('_sa_instance_state', None) for e in event_dicts]
>print(type(event_dicts[0]))
>
>However, this prints
>
>  

`vars` typically returns a `dict`.

>  
This is what you have popped.
>
>If I comment out the third line, which pops the unwanted key, I get
Then you do not change `event_dicts`.

You problem likely is:
`pop` does not return the `dict` after the removal of a key
but the removed value.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Using a background thread with asyncio/futures with flask

2024-03-22 Thread Dieter Maurer via Python-list
Thomas Nyberg wrote at 2024-3-22 11:08 +0100:
> ... `future` use across thread boundaries ...
> Here's an example using just the standard library that
> exhibits the same issue:

I think all `asyncio` objects (futures, tasks, ...)
are meant to be used in a single thread.
If you use them across different threads, you must do special things.

Note that an `await(future)` registers a callback at *future*.
When the future gets its result or exception, the registered callback calls
are scheduled via `self._loop.call_soon`.
`call_soon` must be called from the `asyncio` thread (to which `self._loop`
belongs). A different thread may schedule activities for a loop
but it must use `call_soon_threadsafe` (not `call_soon`).

I would expect that the forbidden `call_soon` call raises an exception
which for reasons I do not know appears to be hidden.


For use across thread boundaries, you likely will use
`concurrent.Future` (not `asyncio.Future`).
You can use `asyncio.futures._chain_futures` to associate
an `asyncio.Future` with a `concurrent.Future`.
Then the fate (result or exception set) of one will be reflected in the other.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Using a background thread with asyncio/futures with flask

2024-03-22 Thread Dieter Maurer via Python-list
[email protected] wrote at 2024-3-22 18:28 +0100:
>Thomas Nyberg wrote at 2024-3-22 11:08 +0100:
>> ... `future` use across thread boundaries ...
>> Here's an example using just the standard library that
>> exhibits the same issue:
> ...
>For use across thread boundaries, you likely will use
>`concurrent.Future` (not `asyncio.Future`).
>You can use `asyncio.futures._chain_futures` to associate
>an `asyncio.Future` with a `concurrent.Future`.
>Then the fate (result or exception set) of one will be reflected in the other.

You must not set the result/exception for a future in a "foreign" thread
("foreign" here means one not associated with the future's loop).
An aternative to the solution sketched above is to set the result
indirectly via `loop.call_soon_threadsafe`. This way, the
result is set in the futures "native" thread.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to discover what values produced an exception?

2024-05-04 Thread Dieter Maurer via Python-list
Johanne Fairchild wrote at 2024-5-3 10:56 -0300:
>How to discover what values produced an exception?  Or perhaps---why
>doesn't the Python traceback show the values involved in the TypeError?
>For instance:
>
>--8<>8---
 (0,0) < 4
>Traceback (most recent call last):
>  File "", line 1, in 
>TypeError: '<' not supported between instances of 'tuple' and 'int'
>--8<>8---
>
>It could have said something like:
>
>--8<>8---
>TypeError: '<' not supported between instances of 'tuple' and 'int'
>  in (0,0) < 4.
>--8<>8---
>
>We would know which were the values that caused the problem, which would
>be very helpful.

Typically, the traceback informs you about the source code line
where the exception has been raised.
When the source line contains literals, you see the values.
If not, then only in special (speak: rather simple) cases the
knowledge of the values will help much.
Usually, a more thorough analysis is required to find out the bug
location and how to fix the bug.

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


Re: From JoyceUlysses.txt -- words occurring exactly once

2024-05-31 Thread Dieter Maurer via Python-list
HenHanna wrote at 2024-5-30 13:03 -0700:
>
>Given a text file of a novel (JoyceUlysses.txt) ...
>
>could someone give me a pretty fast (and simple) Python program that'd
>give me a list of all words occurring exactly once?

Your task can be split into several subtasks:
 * parse the text into words

   This depends on your notion of "word".
   In the simplest case, a word is any maximal sequence of non-whitespace
   characters. In this case, you can use `split` for this task

 * Make a list unique -- you can use `set` for this

>   -- Also, a list of words occurring once, twice or 3 times

For this you count the number of occurrences in a `list`.
You can use the `count` method of lists for this.

All individual subtasks are simple. I am confident that
you will be able to solve them by yourself (if you are willing
to invest a bit of time).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: From JoyceUlysses.txt -- words occurring exactly once

2024-06-04 Thread Dieter Maurer via Python-list
Edward Teach wrote at 2024-6-3 10:47 +0100:
> ...
>The Gutenburg Project publishes "plain text".  That's another problem,
>because "plain text" means UTF-8and that means unicode...and that
>means running some sort of unicode-to-ascii conversion in order to get
>something like "words".  A couple of hoursa couple of hundred lines
>of Cproblem solved!

Unicode supports the notion "owrd" even better "ASCII".
For example, the `\w` (word charavter) regular expression wild card,
works for Unicode like for ASCII (of course with enhanced letter,
digits, punctuation, etc.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Suggested python feature: allowing except in context maneger

2024-06-13 Thread Dieter Maurer via Python-list
Yair Eshel wrote at 2024-6-13 13:01 +0300:
> ...
>I would like to suggest an alternative syntax, that will, in a sense, apply
>the best of both worlds:
>
>import logging
>with open('sample_data/README.md') as f:
>  print (len(f.read()))
>except FileNotFoundError:
>  logging.error("File not")

Are you aware that in the case of a `FileNotFoundError`
no context manager is created (the context manager is the `f`
in your code).

Why not use:
try:
  with open()...
...
except FileNotFoundError:
  ...


I do not think that your use case requires a `with` extension.



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


Re: Difference method vs attribut = function

2024-06-30 Thread Dieter Maurer via Python-list
Ulrich Goebel wrote at 2024-6-28 18:08 +0200:
>Hi,
>
>a class can have methods, and it can have attributes, which can hold a 
>function. Both is well known, of course.
>
>My question: Is there any difference?

I think you should make the distinction "class versus instance attribute"
rather than "mether versus function".

If you look at the `__dict__` of an instance, you see only the
instance variables (the class's `__dict__` gives you the (most) attributes
of the class).

You can access (most) class attributes via an instance;
if a function is accessed in this way, it becomes (typically) a method.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Printing UTF-8 mail to terminal

2024-11-01 Thread Dieter Maurer via Python-list
Loris Bennett wrote at 2024-11-1 10:10 +0100:
> ...
>  mail.set_content(body, cte="quoted-printable")

In the line above, you request the content to use
the "cte" (= "Content-Transfer-Encoding") "quoted-printable"
and consequently, the content is encoded with `quoted-printable`.
Maybe, you do not need to pass `cte`?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Correct module for site customization of path

2024-11-01 Thread Dieter Maurer via Python-list
> ...
>After the recent upgrades I had to install youtube_dl with pipx for the
>new python version.
>When I ran the script which imported youtube_dl, I got an import error
>as it appears the path to the module
>was not in sys.path

I see at several options:

 * install `youtoube_dl` where Python looks for it
   (you can print `sys.path` to find out all the places
   normally checked for importable modules)

 * put a (symbolic) link to `youtoube_dl` at a place
   where Python looks for modules

 * use Pythons' `.pth' feature to tell Python additional
   places where to look for modules.
   You can place `.pth` files where Python looks for modules
   to be imported
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: FileNotFoundError thrown due to file name in file, rather than file itself

2024-11-11 Thread Dieter Maurer via Python-list
Loris Bennett wrote at 2024-11-11 15:05 +0100:
>I have the following in my program:
>try:
>logging.config.fileConfig(args.config_file)
>config = configparser.ConfigParser()
>config.read(args.config_file)
>if args.verbose:
>print(f"Configuration file: {args.config_file}")
>except FileNotFoundError:
>print(f"Error: configuration file {args.config_file} not found.  
> Exiting.")

Do not replace full error information (including a traceback)
with your own reduced error message.
If you omit your "try ... except FileNotFoundError`
(or start the `except` clause with a `raise`), you
will learn where in the code the exception has been raised
and likely as well what was not found (Python is quite good
with such error details).

> ...
>My questions are:
>
>1. Should I be surprised by this behaviour?

Your code contains a major weakness (see above); thus surprises
are not unlikely.

>2. In terms of generating a helpful error message, how should one
>   distinguish between the config file not existing and the log file not
>   existing?

You look at the error information provided by Python
(and its library) rather than hiding it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: FileNotFoundError thrown due to file name in file, rather than file itself

2024-11-13 Thread Dieter Maurer via Python-list
Loris Bennett wrote at 2024-11-12 10:00 +0100:
> ...
>However, it strikes me as not immediately obvious that the logging file
>must exist at this point.  I can imagine a situation in which I want to
>configure a default log file and create it if it missing.

This is what happens usually:
if you open a file with mode `a` or `w`, the file is created
if it does not yet exist.

Thus, a missing log file should not give you the `FileNotFound`
exception.
Look at the exception details: they should tell you what really
was not found (maybe the directory for the logfile).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: FileNotFoundError thrown due to file name in file, rather than file itself

2024-11-12 Thread Dieter Maurer via Python-list
Cameron Simpson wrote at 2024-11-12 08:17 +1100:
>On 11Nov2024 18:24, [email protected]  wrote:
>>Loris Bennett wrote at 2024-11-11 15:05 +0100:
>>>I have the following in my program:
>>>try:
>>>logging.config.fileConfig(args.config_file)
>>>config = configparser.ConfigParser()
>>>config.read(args.config_file)
>>>if args.verbose:
>>>print(f"Configuration file: {args.config_file}")
>>>except FileNotFoundError:
>>>print(f"Error: configuration file {args.config_file} not found.  
>>> Exiting.")
>>
>>Do not replace full error information (including a traceback)
>>with your own reduced error message.
>>If you omit your "try ... except FileNotFoundError`
>>(or start the `except` clause with a `raise`), you
>>will learn where in the code the exception has been raised
>>and likely as well what was not found (Python is quite good
>>with such error details).
>
>Actually, file-not-found is pretty well defined - the except action
>itself is fine in that regard.

The original exception likely tells us which file was not found.
-- 
https://mail.python.org/mailman/listinfo/python-list