Re: object.enable() anti-pattern

2013-05-09 Thread Greg Ewing

Cameron Simpson wrote:

You open a file with "0" modes, so
that it is _immediately_ not writable. Other attempts to make the
lock file thus fail because of the lack of write,


I don't think that's quite right. You open it with
O_CREAT+O_EXCL, which atomically fails if the file
already exists. The read/write modes don't really
come into it, as far as I know.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: object.enable() anti-pattern

2013-05-12 Thread Greg Ewing

Wayne Werner wrote:

On Fri, 10 May 2013, Gregory Ewing wrote:


  f = open("myfile.dat")
  f.close()
  data = f.read()


To clarify - you don't want a class that has functions that need to be 
called in a certain order with *valid input* in order to not crash.


Exactly what does happen - a ValueError is raised because you're(*) 
passing self into the file.read() function, and that input is invalid


The same argument can be applied to:

   foo = Foo()
   foo.do_something()
   foo.enable() # should have done this first

You're passing an invalid input to Foo.do_something,
namely a Foo that hasn't been enabled yet.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-07 Thread Greg Ewing

On 08/11/12 12:06, Oscar Benjamin wrote:

On 7 November 2012 22:16, Joshua Landau  wrote:

That said, losing:
[0] * (2, 3) == [0] * [2, 3]
would mean losing duck-typing in general.


There are precedents for this kind of thing; the
string % operator treats tuples specially, for
example.

I don't think it's all that bad if you regard
the tuple as effectively part of the syntax.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 2.5

2011-06-17 Thread Greg Ewing

PyGUI 2.5 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Lots of new stuff in this version. Highlights include:

  - Improved facilities for customising the standard menus.

  - Functions for creating PyGUI Images from PIL images and numpy arrays.

  - ListButton - a pop-up or pull-down menu of choices.

  - GridView - a user-defined view consisting of a regular grid of cells.

  - PaletteView - a GridView specialised for implementing tool palettes.

There is also a big pile of other improvements and bug fixes. See the
CHANGES file for full details.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.

--
Gregory Ewing
greg.ew...@canterbury.ac.nz
http://www.cosc.canterbury.ac.nz/greg.ewing/
--
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 2.5.3

2011-07-16 Thread Greg Ewing

PyGUI 2.5.3 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Clipboard access now implemented on MacOSX, plus a few
bug fixes.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.

--
Gregory Ewing
greg.ew...@canterbury.ac.nz
http://www.cosc.canterbury.ac.nz/greg.ewing/
--
http://mail.python.org/mailman/listinfo/python-list


ANN: PyGUI 2.4

2011-03-19 Thread Greg Ewing

PyGUI 2.4 is available:

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

Highlights of this release:

* Python 3 Compatible on MacOSX and Windows.

* ScrollableView has been overhauled on Windows and should now
  work with all builds of pywin32 as far as I know.


What is PyGUI?
--

PyGUI is a cross-platform GUI toolkit designed to be lightweight
and have a highly Pythonic API.

--
Gregory Ewing
greg.ew...@canterbury.ac.nz
http://www.cosc.canterbury.ac.nz/greg.ewing/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feature suggestion -- return if true

2011-04-17 Thread Greg Ewing

D'Arcy J.M. Cain wrote:

On Sun, 17 Apr 2011 16:21:53 +1200
Gregory Ewing  wrote:


  def get_from_cache(x):
y = cache.get(x)
if not y:
  y = compute_from(x)
  cache[x] = y
return y


I prefer not to create and destroy objects needlessly.


How does that create objects needlessly?


 def get_from_cache(x):
   if not x in cache:
 cache[x] = compute_from(x)
   return cache[x]


That looks up the cache *twice* for every access. Mine
only does one lookup when the item is already in the
cache.

--
Greg
--
http://mail.python.org/mailman/listinfo/python-list


ANN: SuPy 1.6 for Snow Leopard and Python 2.7

2011-04-24 Thread Greg Ewing

New Binaries of SuPy 1.6 Available
--

   http://www.cosc.canterbury.ac.nz/greg.ewing/SuPy/

I have released two new builds of SuPy 1.6 for MacOSX:

   MacOSX 10.6 (Snow Leopard) System Python 2.6

   User Python 2.7


What is SuPy?
-

SuPy is a plugin for the Sketchup 3D modelling application
that lets you script it in Python.

--
Greg Ewing
greg.ew...@canterbury.ac.nz
--
http://mail.python.org/mailman/listinfo/python-list


Re: "help( pi )"

2017-11-19 Thread Greg Ewing

Cameron Simpson wrote:

Unless one had a misfortune and wanted another docstring.


Good point. I guess having differing docstrings should make
otherwise equal objects ineligible for merging.


 mod1.py:
   MAX_BUFSIZE = 8192
   MAX_BUFSIZE.__doc__ = 'Size of the hardware buffer used for I/O on 
this device.'


 mod2.py
   DEFAULT_CACHESIZE = 8192
   DEFAULT_CACHESIZE.__doc__ = 'Convenient size for the foo cache, not 
to big or too small.'


I think setting the docstring of an existing immutable object
would have to be disallowed -- you need to create a new object
if you want it to have a distinct docstring, e.g.

MAX_BUFSIZE = int(8192, __doc__ = 'Size of the hardware buffer used for I/O on 
this device.')


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


Re: Pre-Pre-PEP: The datetime.timedeltacal class

2022-04-16 Thread Greg Ewing

On 17/04/22 9:17 am, Karsten Hilbert wrote:

Take this medication for 1 month !

is quite likely to mean "take it for 28 days".


Except when your doctor prescribes 90 days worth of tablets,
they come boxes of 84 (6 cards * 14 tablets), and the pharmacist
dutifully opens a box, cuts off an extra 6 and adds them in.

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


Re: Why no list as dict key?

2022-04-20 Thread Greg Ewing

On 21/04/22 6:22 am, Abdur-Rahmaan Janhangeer wrote:

Using Python3.9, i cannot assign a list [1, 2] as key
to a dictionary. Why is that so?


If the contents of the list were to change after using it as
a key, its hash value would no longer match its position in
the dict, so subsequent lookups could fail to find it.

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


Re: Why no list as dict key?

2022-04-20 Thread Greg Ewing

On 21/04/22 8:18 am, Avi Gross wrote:

I am thinking as an example about a program I wrote ages ago that deals with 
equations in symbolic form and maintains a collection of forms of the equation 
it is trying to take a derivative or integral of by applying an assortment of 
typographic rules.


It sounds like you would be better off making all your equation data
structures immutable. Instead of mutating the equation when making
a transformation, return a new equation. Then you can use sets and
dicts to cache them etc. without any problems.

--
Greg

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


Re: code issue

2022-04-21 Thread Greg Ewing

On 22/04/22 5:09 am, Chris Angelico wrote:

This can't be your complete code, because it won't run like this.


Also, the output you showed contains blank lines and lines
with hyphens, and there is nothing in the code you posted
which does that.

If I had to guess, I'd say you have a loop which is supposed
to repeatedly read a value for n and then compute fizzbuzz,
and you have the input statement in the wrong place.

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


Re: Enums and nested classes

2022-04-21 Thread Greg Ewing

On 20/04/22 10:57 pm, Sam Ezeh wrote:

Has anyone here used or attempted to use a nested class inside an enum?

If so, how did you find it? (what did you expect to happen and did
your expectations align with resulting behaviour etc.)


That's a pretty open-ended question. Is there something about
its current behaviour that you think should be different?

--
Greg

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


Re: Python/New/Learn

2022-05-06 Thread Greg Ewing

On 7/05/22 12:27 pm, Stefan Ram wrote:

   But when you read descriptions in books about phonology about
   how the mouth and tongue is positioned to produce certain
   sounds and see pictures of this, your faulty ears are bypassed
   and you get a chance to produce the correct sounds of the
   foreign language even when you might not hear the difference.

   So, one might actually be able to learn the pronunciation
   of a foreign language from text in a book better than from
   an audio tape (or an audio file or a video with sound)!


Such books would certainly help, but I don't think there's any
substitute for actually hearing the sounds if you want to be
able to understand the spoken language. In my experience, you
have to listen to it for quite a while to retrain your ears
to the point where you can even begin to pick out words from
the audio stream.

I kind-of studied French for 5 years in school, with teachers
to learn the pronunication from, but I never got a lot of
practice at it or much chance to hear it spoken. As a result I
have about a 1% success rate at understanding spoken French,
even when I know all the words being used.

--
Greg


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


Re: Seeking deeper understanding of python equality (==)

2022-05-06 Thread Greg Ewing

On 7/05/22 12:22 am, Jonathan Kaczynski wrote:

Stepping through the code with gdb, we see it jump from the compare
operator to the dunder-eq method on the UUID object. What I want to be able
to do is explain the in-between steps.


Generally what happens with infix operators is that the interpreter
first looks for a dunder method on the left operand. If that method
doesn't exist or returns NotImplemented, it then looks for a dunder
method on the right operand.

There is an exception if the right operand is a subclass of the
left operand -- in that case the right operand's dunder method
takes precedence.


Also, if you change `x == y` to `y
== x`, you still see the same behavior, which I assume has to do with
dunder-eq being defined on the UUID class and thus given priority.


No, in that case the conparison method of str will be getting
called first, but you won't see that in pdb because it doesn't
involve any Python code. Since strings don't know how to compare
themselves with uuids, it will return NotImplemented and the
interpreter will then call uuid's method.

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


Re: tail

2022-05-09 Thread Greg Ewing

On 9/05/22 7:47 am, Marco Sulla wrote:

It will fail if the contents is not ASCII.


Why?


For some encodings, if you seek to an arbitrary byte position and
then read, it may *appear* to succeed but give you complete gibberish.

Your method might work for a certain subset of encodings (those that
are self-synchronising) but it won't work for arbitrary encodings.

Given that limitation, I don't think it's reliable enough to include
in the standard library.

--
Greg

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


Re: Changing calling sequence

2022-05-15 Thread Greg Ewing

On 16/05/22 1:20 am, 2qdxy4rzwzuui...@potatochowder.com wrote:

IMO,
classmethods were/are a bad idea (yes, I'm probably in the minority
around here, but someone has to be).


I don't think class methods are a bad idea per se, but having
them visible through instances seems unnecessary and confusing.
I suspect that wasn't a deliberate design decision, but just a
side effect of using a single class dict for both class and
instance things.

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


Re: min, max with position

2022-06-04 Thread Greg Ewing

On 5/06/22 10:07 am, dn wrote:

On 05/06/2022 09.50, Chris Angelico wrote:

min(enumerate(l), key=lambda x: x[1])

(0, 1.618033)


But, but, but which of the above characters is an 'el' and which a 'one'???
(please have pity on us old f...s and the visually-challenged!)



ell = l
one = 1
min(enumerate(ell), key=lambda x: x[one])

Hope that clears it up!11!one!ell

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


Re: How to replace characters in a string?

2022-06-08 Thread Greg Ewing

On 8/06/22 10:26 pm, Jon Ribbens wrote:

Here's a head-start on some characters you might want to translate,


Another possibility that might make sense in this case is to simply
strip out all punctuation before comparing. That would take care of
things being spelled with or without hyphens, commas, etc.

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


Re: How to replace characters in a string?

2022-06-08 Thread Greg Ewing

On 9/06/22 5:55 am, Dennis Lee Bieber wrote:


There are no mutable strings in Python.


If you really want a mutable sequence of characters, you can
use array.array, but you won't be able to use it directly in
place of a string in most contexts.

--
Greg

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


Re: fill out bulletins

2022-06-13 Thread Greg Ewing

Another possibility is to use reportlab to generate a pdf.

--
Greg

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


Re: mapLast, mapFirst, and just general iterator questions

2022-06-14 Thread Greg Ewing

On 15/06/22 7:49 am, Chris Angelico wrote:

If it does need to be used as a module as well as a script, sure. But
(a) not everything does, and (b) even then, you don't need a main()


I think this is very much a matter of taste. Personally I find it tidier
to put the top level code in a function, because it ties it together
visually and lets me have locals that are properly local.

If the file is only ever used as a script, I just put an unconditional
call to the main function at the bottom.

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 21/06/22 2:52 pm, Avi Gross wrote:


This leads to the extremely important question of what would an implementation 
of Python, written completely in C++, be called?


(Pronounced with a comical stutter) "C-p-p-python!")

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 21/06/22 2:38 pm, Paulo da Silva wrote:

Notice that they are, for example, Jython and not JPython.


Jython *was* originally called JPython, but that was judged to be
a trademark violation and they were made to change it.

I don't know how MicroPython has escaped the same fate to date.

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 21/06/22 2:56 pm, Paulo da Silva wrote:
Let's say they reimplement "reference python" CPython in Rust. What is 
better? Change the "reference python" CPython name to RPython, for 
example, or let it as CPython?


The C implementation would still be called CPython, and the new
implementation might be called RPython, or RustyPython, or whatever.
The names are independent of which one is currently blessed as the
reference implementation.

Although if it were called RPython, no doubt a new debate would
flare up over whether the "R" stands for "Rust" or "Reference"...

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 21/06/22 9:27 pm, Paul Rubin wrote:

What?  I never heard of such a dispute.  The PSF got after someone about
it?  Sheesh.


Upon further research, it seems it wasn't the *Python* trademark that
was at issue. From the Jython FAQ page:


1.2   How does Jython relate to JPython?

Jython is the successor to JPython. The Jython project was created in 
accordance with the CNRI JPython 1.1.x license, in order to ensure the 
continued existence and development of this important piece of Python 
software. The intent is to manage this project with the same open 
policies that are serving CPython so well.


The name had to be changed to something other than JPython, because of 
paragraph 4 in the JPython-1.1 license:


4. Licensee may not use CNRI trademarks or trade name, including
   JPython [...] to endorse or promote products [...]


So there was no dispute, they were just following the terms of a
licence.

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 21/06/22 8:37 pm, Christian Gollwitzer wrote:

Am 20.06.22 um 22:47 schrieb Roel Schroeven:
"CPython is a descendant of Pyscript built on Pyodide, a port of 
CPython, or a Python distribution for the browser and Node.js that is 
based on Webassembly and Emscripten."


To me, this sentence is so badly cobbled together that it could be the 
output of a KI of some sort (GPT-3) trying to summarize stuff from the 
web.


It looks to me like the output of a Markov chain that's been fed
with all the latest programming buzzwords.

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


Re: "CPython"

2022-06-21 Thread Greg Ewing

On 22/06/22 4:42 am, MRAB wrote:

On 2022-06-21 03:52, Avi Gross via Python-list wrote:


This leads to the extremely important question of what would an 
implementation of Python, written completely in C++, be called?

C++Python
CPython++
C+Python+
DPython
SeaPython?
SeeSeaSiPython


CincPython?


Python+=1

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


Re: Question about learning Python

2022-09-09 Thread Greg Ewing

On 8/09/22 6:57 am, Chris Angelico wrote:

Not as detrimental as starting with BASIC, and then moving on to x86
assembly language, and trying to massage the two together using CALL
ABSOLUTE in order to get mouse input in your GW-BASIC programs.


Or starting with hand-assembled SC/MP machine code and then moving
on to Applesoft BASIC.

--
Greg

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


Re: PyObject_CallFunctionObjArgs segfaults

2022-09-30 Thread Greg Ewing

On 1/10/22 8:18 am, MRAB wrote:
It's OK to INCREF them, provided that you DECREF them when you no longer 
need them, and remember that if it's a "new reference" you'd need to 
DECREF it twice.


Which means there would usually be no point in doing the extra
INCREF/DECREF. You still need to know whether it's a new reference
or not and treat it accordingly.

--
Greg

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


Re: Changing 'Scripts/*.exe'

2022-10-04 Thread Greg Ewing

On 4/10/22 10:49 pm, 2qdxy4rzwzuui...@potatochowder.com wrote:

(I could even move
the file to another folder on the original Mac, but that didn't mean
much, because those old file systems were entirely flat (directories and
folders were an illusion maintained by the Finder)


That was only true in the very early days. A proper hierarchical
file system was available as soon as hard disks became common
(around the Mac II era I think?)

However, internally each file on a volume was identified by a
File ID (something a bit like an inode number) and that was
stored in the alias and used as the first means of finding the
file. There was also a pathname stored in the alias, but that
was only used as a backup in case the file couldn't be found
using the File ID.

So a Mac alias was in some ways more powerful than a
symlink, but in other ways less -- e.g. there was no equivalent
to a relative symlink. Also aliases are more like a Windows
shortcut in that they aren't resolved automatically in the
kernel -- programs need to be aware of them and take explicit
action to resolve them.

Things are even more confusing in MacOSX, which has both
aliases *and* symlinks, they behave differently, and the Finder
doesn't tell you which you're looking at. :-(

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


Re: an oop question

2022-11-02 Thread Greg Ewing

On 2/11/22 9:54 am, Julieta Shem wrote:

But we've left behind a more basic requirement --- the Stack
class wishes for all the methods already written in some class called
Pair,


Is that *really* what you want, though?

To my way of thinking, a Stack and a Pair are quite different
data structures, each having their own characteristic operations.

Things I want to be able to do with a Stack:
- Create an empty stack
- Push an item onto the top of the stack
- Pop an item off the top of the stack

Things I want to be able to do with a Pair:
- Create a pair containing two given objects
- Get the first item
- Get the second item

I don't see any overlap between these at the conceptual level.
Possibly I might want to use Pairs as part of the *implementation*
of a stack, but that doesn't mean that any Pair methods should
appear as Stack methods.

Here's how I might do this in a functional style using Python:

class Pair:
def __init__(self, first, second):
self._first = first
self._second = second
def first(self):
return self._first
def second(self):
return self._second

class Stack:
def __init__(self):
self._data = None
def push(self, item):
result = Stack()
result._data = Pair(item, self._data)
return result
def pop(self):
rest = Stack()
rest._data = self._data.second()
return self._data.first(), rest

Note that neither Stack nor Pair inherits from the other.

--
Greg

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


Re: an oop question

2022-11-02 Thread Greg Ewing

On 3/11/22 1:37 pm, Julieta Shem wrote:

The code for computing the length of a Pair (which is really a linked
list) happens to be the same for computing the length of a Stack.


I would question whether that should be a method of Pair at all,
since it's not the length of the pair itself, but the length of
a structure built out of pairs.

But in any case, the way to do this in a conceptually clean way
is for the length method of Stack to call whatever it is that
computes the length of a linked list of Pairs. This is what
the term "delegation" refers to.

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


Re: an oop question

2022-11-04 Thread Greg Ewing

On 4/11/22 1:29 am, Julieta Shem wrote:

Perhaps I can reduce the
class Pair to just being a pair as we know it, made of two things, then
we create a class called Sequence, which is really a composition of
Pairs, comes with a length method and we derive Stack from it.


That sounds better. But be careful -- a Sequence class would
probably be expected to have methods for e.g. inserting and
removing things in the middle, which you might not want to
allow for a Stack.

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


Re: an oop question

2022-11-04 Thread Greg Ewing

On 4/11/22 12:50 am, Chris Angelico wrote:

In Python, everything is an object. Doesn't that equally mean that
Python is purely OOP?


Depends on what you mean by "purely oop". To me it suggests a
language in which dynamically-dispatched methods are the only
form of code. Python is not one of those, because it has
stand-alone functions.

I'm not sure I know of *any* language that is purely oop in
that sense. Smalltalk probably comes the closest, but then its
code blocks are essentially lexically-scoped anonymous functions.
You *could* write Smalltalk code in a procedural style by
assigning a bunch of code blocks to names and calling them like
functions. Not that there would be any reason to do that other
than as a party trick.

Java looks like it's fairly purely OO at first glance, but it
has static methods, which are really stand-alone functions by
another name. Also it has some primitive types such as ints
and floats that don't behave in an OO way at all.

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


Re: an oop question

2022-11-04 Thread Greg Ewing

r...@zedat.fu-berlin.de (Stefan Ram) writes [that Barbara Liskov said]:


|If for each object o1 of type S there is an object o2 of
|type T such that for all programs P defined in terms of T,
|the behavior of P is unchanged when o1 is substituted for o2
|then S is a subtype of T.


That seems overly restrictive, because it wouldn't allow S to
override a method of T and make it do something different --
which we do all the time in practice.


Class contracts must hold for subclasses.


That sounds like a much better way of saying it!

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


Re: an oop question

2022-11-04 Thread Greg Ewing

On 4/11/22 7:51 am, Julieta Shem wrote:


(The empty documentation seems to satisfy the principle.)


All the more reason to document your classes!

More seriously, there's always at least a (possibly fuzzily) implied
contract, because of the names you choose for things if nothing else.

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


Re: an oop question

2022-11-04 Thread Greg Ewing

On 5/11/22 4:25 am, Chris Angelico wrote:

Maybe it's one of those terms that is useless for actual coding
(because practicality beats purity), but good for discussions?


I'm not sure it's much good for discussions, either. I don't
really care whether a language is "purely OO" or not, whatever
that means, because I don't see purity of OO as a virtue.
All I care about is what actual features then language has.

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


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

2022-11-13 Thread Greg Ewing

On 14/11/22 1:31 pm, Jon Ribbens wrote:

On 2022-11-13, DFS  wrote:

But why is it allowed in the first place?


Because it's an expression, and you're allowed to execute expressions.


To put it a bit more clearly, you're allowed to evaluate
an expression and ignore the result.

--
Greg

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


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

2022-11-13 Thread Greg Ewing

On 14/11/22 3:13 pm, MRAB wrote:
But if it's an expression where it's expecting a statement and it's not 
a call, then it's probably a bug.


The key word there is "probably". If there's any chance it
could be not a bug, it can't be an error. At most it should
be a warning, and that's what linters are for. I wouldn't
like the core interpreter to be producing a bunch of warnings
for things like this.

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


Re: String to Float, without introducing errors

2022-12-18 Thread Greg Ewing

On 19/12/22 6:35 am, Paul St George wrote:

So I am working on a physics paper with a colleague. We have a theory about 
Newtons Cradle.

We want to illustrate the paper with animations.

Because there is a problem, I am investigating in all areas. ... I would like 
to be in control of or fully aware of what goes on under the bonnet.


When you convert a string to a float, you're already getting the closest
possible value in binary floating point.

For things like physics simulations, you need to design your algorithms
so that they're tolerant of small inaccuracies in the representation of
your numbers. If those are causing you problems, it sounds like there
is some kind of numerical instability in your algorithm that needs to
be addressed.

It's also possible that there is just a bug somewhere in your code, and
the problem really has nothing to do with floating point inaccuracies.

If you can post some code we might be able to help you further.

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


Re: String to Float, without introducing errors

2022-12-19 Thread Greg Ewing

On 19/12/22 9:24 am, Stefan Ram wrote:

 So what's the time until a mass of one gram
 arrives at the ground versus a mass of ten grams? I think
 one needs "Decimal" to calculate this!


Or you can be smarter about how you calculate it.

Differentiating t with respect to m gives

dt/dm = -0.5 * sqrt(2 * s * r**2 / (G * (M + m)**3))

which, since m is much smaller than M, is approximately

   -0.5 * sqrt(2 * s * r**2 / (G * M**3))

So

>>> G = 6.6743015E-11
>>> r = 6.371E6
>>> M = 5.9722E24
>>> dtdm = -0.5 * sqrt(2*s*(r**2) / (G * M**3))
>>> dtdm * (1/1000 - 10/1000)
3.4004053539917275e-28

which agrees with your Decimal calculation to 3 digits,
and should be as precise as the input numbers (about
4 digits in this case).

This is a good example of why it's important to choose
an appropriate numerical algorithm!

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


Re: NoneType List

2022-12-31 Thread Greg Ewing

On 1/01/23 11:36 am, avi.e.gr...@gmail.com wrote:

And, of course, we had the philosophical question of why the feature was
designed to not return anything ... rather than return the changed
object.


My understanding is that Guido designed it that way to keep a
clear separation between mutating and non-mutating methods, and
to help catch mistakes resulting from mixing them up.

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


Re: To clarify how Python handles two equal objects

2023-01-10 Thread Greg Ewing

On 11/01/23 11:21 am, Jen Kris wrote:

where one object derives from another object (a = b[0], for example), any 
operation that would alter one will alter the other.


I think you're still confused. In C terms, after a = b[0], a and b[0]
are pointers to the same block of memory. If you change that block of
memory, then of course you will see the change through either pointer.

Here's a rough C translation of some of your Python code:

/* mx1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] */
int **mx1 = (int **)malloc(3 * sizeof(int *));
mx1[0] = (int *)malloc(3 * sizeof(int));
mx1[0][0] = 1;
mx1[0][1] = 2;
mx1[0][2] = 3;
mx1[1] = (int *)malloc(3 * sizeof(int));
mx1[1][0] = 4;
mx1[1][1] = 5;
mx1[1][2] = 6;
mx1[2] = (int *)malloc(3 * sizeof(int));
mx1[2][0] = 7;
mx1[2][1] = 8;
mx1[2][2] = 9;

/* arr1 = mx1[2] */
int *arr1 = mx[2];

/* arr1 = [ 10, 11, 12 ] */
arr1 = (int *)malloc(3 * sizeof(int));
arr1[0] = 10;
arr1[1] = 11;
arr1[2] = 12;

Does that help your understanding?

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


Re: Fast lookup of bulky "table"

2023-01-15 Thread Greg Ewing

On 16/01/23 2:27 am, Dino wrote:
Do you have any idea about the speed of a SELECT query against a 100k 
rows / 300 Mb Sqlite db?


That depends entirely on the nature of the query and how the
data is indexed. If it's indexed in a way that allows sqlite to
home in directly on the wanted data, it will be very fast. If
it has to fall back on a linear search, it probably won't be
significantly faster than your existing Python implementation.

--
Greg

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


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

2023-01-18 Thread Greg Ewing

On 19/01/23 10:40 am, Dan Kolis wrote:

I guess I don't full understand what bothers me about the repetition of the 
imports so much.


It's doubtful that every module uses every one of those imports.
It looks like someone had a standard block of imports that they
blindly pasted at the top of every file, to avoid having to think
about which ones were actually needed.

If you're looking for advice, I would suggest:

* Only import what you use in a particular file (this doesn't
have much effect on efficiency, but there's less clutter for
the reader.)

* Only use short names for modules that are *very* frequently
referenced. Use full unabbreviated names for everything else.

* Don't 'import foo as foo', just 'import foo'.

* Don't try to line the code up in columns, it doesn't really
help readability IMO.

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


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

2023-01-23 Thread Greg Ewing

On 2023-01-22 at 18:19:13 -0800,
Jach Feng  wrote:

1) Modify the sys.argv by inserting an item '--' before parsing it, ie.
sys.argv.insert(1, '--')
args = parser.parse_args()


If you do that, you'll never be able to have any actual options, so
using argparse seems like overkill. Just pull the argument out of
argv directly.

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


Re: bool and int

2023-01-27 Thread Greg Ewing

On 26/01/23 6:10 am, Chris Angelico wrote:

And that's a consequence of a system wherein there is only one concept
of "success", but many concepts of "failure". Whoever devised that
system was clearly a pessimist :)


Murphy's Law for Unix: If something can go wrong, it will go
wrong 255 times out of 256.

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


Re: evaluation question

2023-01-30 Thread Greg Ewing

On 30/01/23 10:41 pm, mutt...@dastardlyhq.com wrote:

What was the point of the upheaval of converting
the print command in python 2 into a function in python 3 if as a function
print() doesn't return anything useful?


It was made a function because there's no good reason for it
to have special syntax in the language.

Functions don't need to return things to justify their existence,
and in fact the usual convention is that functions whose purpose
is to have an effect just return None.

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


Re: evaluation question

2023-01-31 Thread Greg Ewing

On 31/01/23 10:24 pm, mutt...@dastardlyhq.com wrote:

All languages have their ugly corners due to initial design mistakes and/or
constraints. Eg: java with the special behaviour of its string class, C++
with "=0" pure virtual declaration. But they don't dump them and make all old
code suddenly cease to execute.


No, but it was decided that Python 3 would have to be backwards
incompatible, mainly to sort out the Unicode mess. Given that,
the opportunity was taken to clean up some other mistakes as well.

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


Re: evaluation question

2023-01-31 Thread Greg Ewing

On 1/02/23 7:33 am, Stefan Ram wrote:

Thomas Passin  writes:



   Some people say it is a function now so that you can redefine it.


Well, that's one benefit, but I wouldn't say it's the main one.

The point is really that you can do *anything* with it now that
you can do with a regular function -- pass it as an argument,
wrap it with another function, define your own function with a
similar signature for duck-typing purposes, etc.


   It would still be possible to have a special syntax for the outermost
   expression of an expression statement that would allow one to omit
   the parentheses,


That's only one of the syntactic oddities of the old print
statement, thogh. There was also the >> thing, special treatment
of trailing commas, etc.

Also, introducing a paren-less call syntax would be a very big
and controversial change that would be way out of proportion to
the problem.

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


Re: evaluation question

2023-01-31 Thread Greg Ewing

On 1/02/23 1:17 pm, dn wrote:
1 nothing "ceased to execute" and Python 2 was maintained and developed 
for quite some time and in-parallel to many Python 3 releases.


And a lot of effort was put into making the transition as easy
as possible, e.g. 2to3, and the features added to 2.7 to make
it easier to write code that would work in both versions.

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


Re: Licensing?

2023-02-02 Thread Greg Ewing

On 3/02/23 6:38 am, Jon Ribbens wrote:

If you change someone else's code then you have created a derived
work, which requires permission from both the original author and you
to copy. (Unless you change it so much that nothing remains of the
original author's code, of course.)


"Nothing" is probably a bit extreme; somewhere between "exactly the
same" and "completely different" there will be a borderline case,
although exactly where the border lies would require a court case
to determine.

When in doubt, the sensible and courteous thing would be to include
the original copyright notice as requested, maybe with a "based on
work by..." attribution.

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


Re: evaluation question

2023-02-02 Thread Greg Ewing

On 3/02/23 5:09 am, mutt...@dastardlyhq.com wrote:

What if its 10s of thousands of lines of
core production code? If the company it belongs to wants to add new Python 3
features it can't just plug them into the code because it won't run under
Python 3, they have to do a full overhaul or even complete rewrite and that
costs a lot of time and money.


A possible strategy in that case would have been to incrementally
rewrite it in such a way that the code would run in both 2.7 and 3.x
(various features were added to 2.7 to make that possible).

When that point is reached, you can then switch to running it with
Python 3 and start using the new features.

Also, if you're a company whose business is totally reliant on some
piece of code, it would be prudent to plan ahead and budget for
rewriting or replacing it at some point.

People seem to think that because code doesn't wear out like
hardware, you don't have to budget for replacing it. But you can't
expect third party software to be maintained forever -- particularly
when, as with Python, the maintenance is mainly being done by
*volunteers*.

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


Re: argparse presence of switch

2021-01-12 Thread Greg Ewing

On 13/01/21 7:13 am, Chris Angelico wrote:


This is what different actions are for. I'd probably use
action="store_true" here; that should mean that args.register will be
set to True if "-r" was passed, or False if it wasn't.


Yes, otherwise it expects another argument following -r
containing a value.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Greg Ewing

On 13/01/21 4:18 am, Grant Edwards wrote:


AFAIK, Python can't be used to write device drivers for any popular OS


At least not until some crazy person embeds Python in the
Linux kernel...

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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Greg Ewing

On 13/01/21 7:57 pm, Christian Gollwitzer wrote:

  What do you mean, "until" ?

https://medium.com/@yon.goldschmidt/running-python-in-the-linux-kernel-7cbcbd44503c 


He's using Micropython. That's cheating! :-)

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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Greg Ewing

On 14/01/21 11:09 am, Grant Edwards wrote:

Perhaps I need to recalibrate my adjectives, but with
256KB+ of flash and 32KB+ of RAM, I wouldn't call them "small"


It's small by today's standards, when you consider that
multiple GB of RAM is commonplace now in most "real" computers.

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


Re: Application window geometry specifier

2021-01-13 Thread Greg Ewing

On 14/01/21 1:58 pm, Chris Angelico wrote:

On Thu, Jan 14, 2021 at 11:53 AM Python  wrote:


I believe it is or was quite common
for large, integrated applications like DAWs, graphical design
software, etc. to remember where you placed your various floating
toolbars and add-ons


Not just large, integrated applications. If I open Intaglio
(a modestly sized drawing app) on my Mac right now, the palettes
are all where I left them last time.


The results will differ based on whether the user in question has
basically just one primary application (an IDE, or some gigantic app
like Adobe PhotoShop) that they spend all their time in, or if they're
using myriad different applications. Especially in the latter case, it
is far FAR better to put control in the user's hands


I don't follow. If the app is just remembering where the user
put things, then it *is* putting control in the user's hands.

And I don't see what difference it makes how many different apps
they use. Leaving things where the user put them seems like a good
idea regardless.

Ideally, the OS or window manager would do the remembering, but
if it doesn't provide such a facility, I don't see any harm in
allowing the app to *request* (not force) a certain position for
a window.

The app can of course abuse that privilege, but that's the fault
of the app, not the feature.

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


Re: why sqrt is not a built-in function?

2021-01-14 Thread Greg Ewing

Aother thing to consider is that math.sqrt is not the only
sqrt function in Python. There is also one in cmath, and
in the wider ecosystem, another one in numpy. Being explicit
about which one you're using is a good thing.

Concerning exponentiation, it can be used to achieve the same
thing as sqrt, but the sqrt function probably uses a more
efficient algorithm.

Also, exponentiation assumes you're okay with getting a
complex result:

>>> (-27)**0.5
(3.181725716174721e-16+5.196152422706632j)

So it's not quite the same thing as math.sqrt().

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


Re: conceptual problem (was: A beginning beginner's question about input, output and . . .

2021-01-14 Thread Greg Ewing

On 14/01/21 11:49 am, Cameron Simpson wrote:

The "pure" OOP approach, where method calls are used as messages to set
or fetch aspects of the object, is usually does with getter and setter
methods like:

 x = o.getX()
 o.setX(9)


People use get and set methods, not because it's somehow morally
wrong to expose attributes directly, but as a workaround for the
lack of a language feature.

In C++ and Java, different calling syntax is required for direct
access and access mediated by methods, so if you start out exposing
something directly and then change your mind, all the code using it
has to be changed. For this reason, people got into the habit of
wrapping everything in get and set methods from the beginning,
"just in case".

Python doesn't have this problem -- you can turn an attribute
into a property at any time, and nothing else needs to change.
So get and set methods are unnecessary and actively discouraged
in Python.

(C#, if I understand correctly, gets this sort of half-right.
You can turn an attribute into a property, and the calling *source*
doesn't change, but it all has to be recompiled -- which kind of
defeats the purpose.)

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


Re: Exploring terminfo

2021-01-15 Thread Greg Ewing

On 16/01/21 7:33 am, Grant Edwards wrote:

Starting in Python 3., python's stdio file objects are _not_
on top of the libc FILE streams: they're directly on top of the file
descriptor.


This sounds like rather a bad situation, because it means that
any C library using stdio is going to interact badly with Python
stdio.

Can something be done about this? Maybe Python stdio objects
should flush all the C stdio streams before writing anything?

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


Re: why sqrt is not a built-in function?

2021-01-15 Thread Greg Ewing

On 16/01/21 10:14 am, Michael F. Stemper wrote:

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python.


It's not an *obvious* way, so there's no Zen conflict.

As for why it exists, it's part of the mechanism that implements
imports -- 'import' statements get compiled into a call to
__import__.

It also provides a way of importing something specifed by a
string at runtime, so it can be useful.

--
Greg

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


Re: Exploring terminfo

2021-01-15 Thread Greg Ewing

On 16/01/21 3:37 pm, Chris Angelico wrote:

Surely it should be the other way around? If you use the C stdio
streams, flush them after use.


1. You might not know that you're (implicitly) using C stdio.

2. There doesn't seem to be an easy way to flush C stdio from
Python any more.

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


Re: Exploring terminfo

2021-01-16 Thread Greg Ewing

On 16/01/21 4:17 pm, Chris Angelico wrote:

But somewhere along the way, you're finding that there's a problem,
which implies that SOMETHING is calling on C stdio. That thing,
surely, should be the thing responsible for flushing?


The C library using stdio has no way of knowing that something
else (e.g. Python) is bypassing stdio. That's an unusual thing
to do in the C world, so you can't really blame the authors
of the library for failing to anticipate it.

It's also unreasonable to expect a C library to flush after
every write, as that would defeat the purpose of stdio buffering.

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


Re: Exploring terminfo

2021-01-16 Thread Greg Ewing

On 17/01/21 12:40 pm, Chris Angelico wrote:

This is true. However, at some point, the boundary is crossed from
Python into the C library. Something, at that point, knows. It's very
common to have a flush option available, so it should be used.


I'm wondering whether the problem in this particular case stems
from trying to use parts of curses without initialising it
properly. I expect that initialising curses would put stdout
into some kind of unbuffered mode, and the rest of it assumes
that this has been done.

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


Re: Exploring terminfo

2021-01-17 Thread Greg Ewing

On 18/01/21 3:34 am, Alan Gauld wrote:

The problem is terminfo is not really part of curses.
Curses is built on top of terminfo.


As far as I can tell from the man pages, terminfo itself
is just a file format. The only programmatic interfaces I
can find for it *are* part of curses:

del_curterm(3x), mvcur(3x), putp(3x), restartterm(3x), set_curterm(3x), 
setterm(3x), setupterm(3x), tigetflag(3x), tigetnum(3x), tigetstr(3x), 
tparm(3x), tputs(3x), vid_attr(3x), vid_puts(3x), vidattr(3x), 
vidputs(3x) - curses interfaces to terminfo database


tgetent(3x), tgetflag(3x), tgetnum(3x), tgetstr(3x), tgoto(3x), 
tputs(3x) - direct curses interface to the terminfo capability database


--
Greg

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


Re: Exploring terminfo

2021-01-18 Thread Greg Ewing

On 19/01/21 2:34 pm, Alan Gauld wrote:

To be fair that's a limitation of the C curses library. putp() is a
wrapper around tputs() even there, and you can't change what it does.
The gap in the curses module is that it doesn't offer the tputs()
option as an alternative.


Seems to me it would be useful to have something that returns
what tputs() would have output, as a string, so you can send it
where you want.

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


Re: Best practice for handling exceptions raised at lower levels?

2021-02-02 Thread Greg Ewing

On 3/02/21 9:24 am, Dan Stromberg wrote:


But how do you know what exceptions could be raised?


Mostly I find that it's not really necessary to know precisely
which exceptions could be raised.

The way I usually deal with exceptions is:

1. If it descends from OSError, I assume it results from some
external condition, so I catch it at a level where I know what
the user was trying to accomplish and can report it in a
meaningful way. E.g.

def open_connection(address):
try:
return some_library.open_thing(address)
except OSError as e:
tell_user("Couldn't connect to %s: %s" % (address, e))

2. If it's anything else, I assume it's a bug and let it
propagate.

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


Re: super() in injected methods

2021-02-11 Thread Greg Ewing

On 12/02/21 7:05 am, Andras Tantos wrote:


     a = B()
     a.m(41)
     a.m = MethodType(method, a)
     a.m(42)


Are you sure you really need to inject methods into instances
like this? What problem are you trying to solve by doing so?
There's almost certainly a better way to approach it.

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


Re: New Python implementation

2021-02-11 Thread Greg Ewing

On 12/02/21 11:33 am, Mr Flibble wrote:

neos isn't a Python package so that isn't a problem.


It might be a bit confusing if it ever becomes part of the
wider Python ecosystem, though.

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


Re: super() in injected methods

2021-02-11 Thread Greg Ewing

On 12/02/21 3:39 pm, Andras Tantos wrote:
Now, when a Port gets assigned a NetType, it needs to gain all sorts of 
new features. It for example should have a 'length' attribute that tells 
how many bits are needed to represent its possible values.


The way I would probably approach this is to have a single
Port type with all the methods that might be required, and
forward their implementations to the NetType.

e.g.

class Port:

@property
def length(self):
return self.net_type.length

Another possibility might be to change the __class__ of the port
object at run time to a subclass of Port having the required
features. That would be a lot easier and more efficient than
adding individual methods to every Port instance, and super()
should work normally.

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


Re: weirdness with list()

2021-02-28 Thread Greg Ewing

On 28/02/21 1:17 pm, Cameron Simpson wrote:

[its length in bytes] is presented via the object's __len__ method,



BUT... It also has a __iter__ value, which like any Box iterates over
the subboxes.


You're misusing __len__ here. If an object is iterable and
also has a __len__, its __len__ should return the number of
items you would get if you iterated over it. Anything else
is confusing and can lead to trouble, as you found here.


But is there a cleaner way to do this?


Yes. Give up on using __len__ to get the length in bytes,
and provide another way to do that.

--
Greg

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


Re: Why assert is not a function?

2021-03-02 Thread Greg Ewing

On 3/03/21 12:24 pm, Chris Angelico wrote:

if PRODUCTION:
 def assert(*a, **kw): pass

would work if it were a function :)


But would cost you a useless function call for every assert
in production mode.

--
Greg

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


Re: Canonical conversion of dict of dicts to list of dicts

2021-03-31 Thread Greg Ewing

On 31/03/21 7:37 pm, dn wrote:

Python offers mutable (can be changed) and immutable (can't) objects
(remember: 'everything is an object'):
https://docs.python.org/3/reference/datamodel.html?highlight=mutable%20data


While that's true, it's actually irrelevant to this situation.


   $ a = "bob"
   $ b = a
   $ b = "bert"
   $ a
  'bob'


Here, you're not even attempting to modify the object that is
bound to b; instead, you're rebinding the name b to a different
object. Whether the object to which b was previously bound is
mutable or not makes no difference.

You can see this if you do the equivalent thing with lists:

>>> a = ["alice", "bob", "carol"]
>>> b = a
>>> b
['alice', 'bob', 'carol']
>>> b = ['dave', 'edward', 'felicity']
>>> a
['alice', 'bob', 'carol']
>>> b
['dave', 'edward', 'felicity']

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


Re: Horrible abuse of __init_subclass__, or elegant hack?

2021-04-02 Thread Greg Ewing

On 3/04/21 10:36 am, Chris Angelico wrote:

It means exactly what you'd expect. The tricky part comes when you try
to knife the block of chocolate, and it makes for a hilarious party
game.


A guillotine could be useful in the case of Whittaker's.
IMO they don't make the grooves deep enough, making it
quite tricky to break off a row cleanly.

I'd upload a patch for that, but it doesn't seem to be
open source. At least I can't find it on chochub.

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


Re: Friday Finking: initialising values and implied tuples

2021-04-04 Thread Greg Ewing

On 5/04/21 11:47 am, dn wrote:

I think I've read that the compiler is smart-enough to realise that the
RHS 'literal-tuples'?'tuple-literals' are being used as a 'mechanism',
and thus the inits are in-lined.


It does indeed seem to do this in some cases:

>>> def g(i, j, k):
...  a, b, c = i, j, k
...
>>> dis(g)
  2   0 LOAD_FAST0 (i)
  2 LOAD_FAST1 (j)
  4 LOAD_FAST2 (k)
  6 ROT_THREE
  8 ROT_TWO
 10 STORE_FAST   3 (a)
 12 STORE_FAST   4 (b)
 14 STORE_FAST   5 (c)
 16 LOAD_CONST   0 (None)
 18 RETURN_VALUE

If the RHS is a literal, it's a bit different:

>>> def f():
...  a, b, c = 1, 2, 3
...
>>> dis(f)
  2   0 LOAD_CONST   1 ((1, 2, 3))
  2 UNPACK_SEQUENCE  3
  4 STORE_FAST   0 (a)
  6 STORE_FAST   1 (b)
  8 STORE_FAST   2 (c)
 10 LOAD_CONST   0 (None)
 12 RETURN_VALUE

Here the tuple creation is being done at compile time,
so there's still an unpacking operation. It might not be
much different speed-wise from loading the values separately,
though.

--
Greg

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


Re: Yield after the return in Python function.

2021-04-05 Thread Greg Ewing

On 6/04/21 4:02 am, Terry Reedy wrote:
*Any* use of 'yield' in a function makes the function a generator 
function.  ...  If there were a 'dead 
(unreachable) code' exception, a reader or compiler would have to 
analyze each use of 'yield' and decide whether it is reachable or not. 


It would also break existing code. An unreachable "yield" is
sometimes used as a way to get a generator that doesn't yield
anything.

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


Re: Unsubscribe/can't login

2021-05-05 Thread Greg Ewing

On 6/05/21 12:58 am, Peter Otten wrote:

Does that happen with all my messages?


I've seen two pairs of duplicate messages from you in this
thread so far, with the same content but slightly different
line wrapping. Looks like a gateway somewhere isn't recognising
them as the same message.

Reading comp.lang.python with Thunderbird.

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


Re: Proposal: Disconnect comp.lang.python from python-list

2021-05-06 Thread Greg Ewing

My opinion on all this: The volume in this newsgroup is nowhere
near high enough to be worth changing anything.

This thread itself now contains more messages than the recent
neopython trollage that prompted it.

--
Greg

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


Re: learning python ...

2021-05-24 Thread Greg Ewing

On 25/05/21 9:27 am, Cameron Simpson wrote:

On 24May2021 16:17, hw  wrote:

>

Or it doesn't forget
about the old one and the old one becomes inaccessible (unless you
have a reference to it, if there is such a thing in python).  How do
you call that?


You're conflating values
(objects, such as an int or a string) with variables (which _are_
references in Python,


I think hw might have meant the C++ notion of a reference to
a *variable*. There is no equivalent of that in Python.

Python does have references to *objects*. All objects live on
the heap and are kept alive as long as there is at least one
reference to them.

If you rebind a name, and it held the last reference to an
object, there is no way to get that object back.

On the other hand, if you shadow a name, the original name
still exists, and there is usually some way to get at it,
e.g.

>>> int = 42
>>> int
42
>>> __builtins__.int

>>>

--
Greg

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


Re: learning python ...

2021-05-25 Thread Greg Ewing

On 25/05/21 2:59 pm, hw wrote:
Then what is 'float' in the case of isinstance() as the second 
parameter, and why can't python figure out what 'float' refers to in 
this case?  


You seem to be asking for names to be interpreted differently
when they are used as parameters to certain functions.

Python doesn't do that sort of thing. The way it evaluates
expressions is very simple and consistent, and that's a good
thing. It means there aren't any special cases to learn and
remember.

Maybe you're not aware that isinstance is just a function,
and not any kind of special syntax?


Perhaps type names should be keywords to avoid confusion.


Python has quite a lot of built-in types, some of them in
the builtin namespace, some elsewhere. Making them all keywords
would be impractical, even if it were desirable.

And what about user-defined types? Why should they be treated
differently to built-in types? Or are you suggesting there
should be a special syntax for declaring type names?

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


Re: learning python ...

2021-05-25 Thread Greg Ewing

On 25/05/21 5:56 pm, Avi Gross wrote:

Var = read in something from a file and make some structure like a data.frame
Var = remove some columns from the above thing pointed to by Var
Var = make some new calculated columns ditto
Var = remove some rows ...
Var = set some kind of grouping on the above or sort it and so on.


As long as all the values are of the same type, this isn't too bad,
although it might interfere with your ability to give the intermediate
results names that help the reader understand what they refer to.

A variable that refers to things of different *types* at different
times is considerably more confusing, both for a human reader and
for any type checking software you might want to use.


How can you write a recursive function without this kind of variable shadowing? 
Each invocation of a function places the internal namespace in front of the 
parent so the meaning of a variable name used within is always backed by  all 
the iterations before it.


Um, no. What you're describing is called "dynamic scoping", and
Python doesn't have it. Python is *lexically* scoped, meaning that
only scopes that textually enclose the function in the source are
searched for names. Frames on the call stack don't come into it.


So what if you suggest we allow re-use of names but WARN you. ... The first 50 
places may be in other instances of the recursive function and you have already 
been warned this way 49 times


If this were to be done, the shadowing would be detected at compile
time, so you would only be warned once.

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


Re: learning python ...

2021-05-25 Thread Greg Ewing

On 26/05/21 3:33 am, Dennis Lee Bieber wrote:

the OBJECTS have a type and can not change type.


Well... built-in types can't, but...

>>> class A:
...  pass
...
>>> class B:
...  pass
...
>>> a = A()
>>> type(a)

>>> a.__class__ = B
>>> type(a)


--
Greg

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


Re: imaplib: is this really so unwieldy?

2021-05-25 Thread Greg Ewing

On 26/05/21 5:21 am, hw wrote:

On 5/25/21 11:38 AM, Cameron Simpson wrote:

You'll need to import "sys".


aving to import another library just to end a program 
might not be ideal.


The sys module is built-in, so the import isn't really
loading anything, it's just giving you access to a
namespace.

But if you prefer, you can get the same result without
needing an import using

   raise SystemExit(1)

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


Re: learning python ...

2021-05-25 Thread Greg Ewing

On 2021-05-24, Alan Gauld via Python-list  wrote:

Although wouldn't it be "expected boolean expression" rather than
conditional expression? Python doesn't care how the argument  to 'if'
is arrived at so long as it's a boolean.


This isn't really true either. Almost every object in Python has
an interpretation as true or false, and can be used wherever a
boolean value is needed.

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


Re: learning python ...

2021-05-26 Thread Greg Ewing

On 26/05/21 7:15 pm, hw wrote:
it could at least figure out which, the 
type or the variable, to use as parameter for a function that should 
specify a variable type when the name is given.  Obviously, python knows 
what's expected, so why not chose that.


It knows, but not until *after* the function is called. Not
when the parameters are being evaluated.

Note that not even C does what you're asking for. If you use
a type name where a variable name is expected or vice versa
in C, you get a compile-time error. It doesn't try to
automagically figure out what you mean. The only difference
is that Python gives you the error at run time.

Also, you seem to be thinking only of the case where the type
name appears directly in the call. But what about this:

int = 42
type = int
if isinstance(something, type):
...

Would you expect Python to auto-correct this as well?

Maybe a special 
syntax for declaring type names which then can not become ambigous so 
easily would be a good thing?


The fact that types are treated as a form of data is a useful
feature. It means you can use the full power of the language on
them. Dividing names into two kinds, types and non-types, would
severely diminish that power.

I already wondered that the scope of variables is not limited to the 
context they are declared within:


for number in something:
     # do stuff


This has been a subject of debate for quite a long time.
Many people feel that a for-loop variable should be local to
the loop, but Guido deliberately didn't make it that way.
He felt it was useful to be able to refer to the loop
variable after the loop finishes. That way you can do things
like search for something in a loop, break out early when it's
found, and the loop variable then contains the thing you found.

It also has the benefit of being simple and consistent with
the way scoping and assignments work in the rest of the language.

There are other ways to code a search, of course, but it's been
the way it is from the beginning, and changing it now would be
massively disruptive.

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


Re: Turtle module

2021-05-26 Thread Greg Ewing

On 27/05/21 4:17 am, Chris Angelico wrote:

Worst case, it
is technically available as the ._fullcircle member, but I would
advise against using that if you can help it!


If you're worried about that, you could create your own
turle subclass that tracks the state how you want.

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


(OT) Re: Applying winpdb_reborn

2021-05-29 Thread Greg Ewing

On 30/05/21 1:46 pm, dn wrote:

We always referred to it as an "oh-two-nine" ("029").


I had the privilege of helping to dismantle a couple of those
when they were decommissioned at the University of Canterbury.

Amazing pieces of technology -- purely electromechanical, no
electronics in sight. Even the little dot-matrix printer that
wrote human-readable characters along the top of the card was
all mechanical!

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


Re: Definition of "property"

2021-05-31 Thread Greg Ewing

On 31/05/21 8:20 am, Alan Gauld wrote:


That's a very Pythonic description.


If it's a book about Python, it needs to be. The word "property"
has a very specialised meaning in Python.

In some other languages it's used the way we use "attribute" in
Python. So a Python-specific definition is necessarily going
to be very different from a generic one.

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


Re: Definition of "property"

2021-05-31 Thread Greg Ewing

On 31/05/21 4:57 am, Irv Kalb wrote:

Perhaps the best I've found so far is from the Python documentation:

A property object has getter, setter, and deleter methods usable as decorators 
that create a copy of the property with the corresponding accessor function set 
to the decorated function.


That's not a definition of a property -- it's talking about a
mechanism that provides one way of creating a property, using
decorators. DON'T quote that as a definition!

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


Re: Definition of "property"

2021-05-31 Thread Greg Ewing

On 31/05/21 9:13 am, Jon Ribbens wrote:

No, I said it pretends to be a *data* attribute.


I don't think it's pretending to be anything. From the outside,
it's just an attribute.

Data attributes are more common than non-data attributes, so
we tend to assume that an attribute is a data attribute until
told otherwise. But that's just our psychological bias, not
because of any pretence on the part of properties.

Also, there's a sense in which *all* attributes are properties.
At the lowest level, all attribute accesses end up calling
a method. It's just that in most cases the method is implemented
in C and it looks up a value in the object's dict.

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


Re: Definition of "property"

2021-06-01 Thread Greg Ewing

On 1/06/21 2:34 am, Jon Ribbens wrote:

 From the outside, it's just a *data* attribute. Which, from the inside,
it isn't. Hence "pretending".


But what is it about the external appearance that would make
you think it's a data attribute, rather than some other kind
of attribute?

(I'm assuming that by "data attribute" you mean a piece of
data that's stored directly in the object. If you mean
something else, we might be talking at cross purposes.)

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


Re: Definition of "property"

2021-06-01 Thread Greg Ewing

On 1/06/21 7:01 am, Alan Gauld wrote:

That was the point, the OP said it was a book about OOP.
Not a book about "OOP in Python".


In that case it would be best to avoid the word, or give
a definition of the way he's using it, making it clear
that it's not a universal definition. Python's definition
is somewhat unusual, and so would not be appropriate.

--
Greg

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


Re: Behaviour of pop() for dictionaries

2021-06-14 Thread Greg Ewing

On 14/06/21 4:19 am, BlindAnagram wrote:
Am I missing the obvious way to obtain the value (or the key) from a 
dictionary that is known to hold only one item?


v = d.popitem()[1]

More importantly, is there a good reason why we don't have d.pop() for 
dictionaries?


My guess is because it's not generally useful to get an arbitrary
value from a dict without its corresponding key. Hence the existence
of popitem().

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


Re: optimization of rule-based model on discrete variables

2021-06-14 Thread Greg Ewing

On 14/06/21 4:15 am, Elena wrote:

Given a dataset of X={(x1... x10)} I can calculate Y=f(X) where f is this
rule-based function.

I know an operator g that can calculate a real value from Y: e = g(Y)
g is too complex to be written analytically.

I would like to find a set of rules f able to minimize e on X.


There must be something missing from the problem description.
From what you've said here, it seems like you could simply find
a value k for Y that minimises g, regardless of X, and then f
would consist of a single rule: y = k.

Can you tell us in more concrete terms what X and g represent?

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


Re: Terminology: EU language skills, and Master to Main (or ...)

2021-06-14 Thread Greg Ewing

On 13/06/21 3:21 pm, dn wrote:

Will referring to
skilled professionals as 'masters (of their profession/craft)'
transgress (international or at least US-instigated) 'Political
Correctness'?


And what about all the university degrees with the word
"master" in their names?

Worst of all, will episodes of Doctor Who featuring the
Master be banned?

--
Greg

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


Re: optimization of rule-based model on discrete variables

2021-06-14 Thread Greg Ewing

On 15/06/21 12:51 am, Elena wrote:

I see what you mean, so I try to explain it better: Y is a vector say [y1,
y2, ... yn], with large (n>>10), where yi = f(Xi) with Xi = [x1i, x2i, ...
x10i] 1<=i<=n. All yi and xji assume discrete values.

I already have a dataset of X={Xi} and would like to find the rules f able
to minimize a complicated-undifferenciable Real function g(f(X)).
Hope this makes more sense.


Hmmm, so the problem breaks down into two parts:
(1) find a vector Y that minimises g
(2) find a set of rules that will allow you to predict each component
of Y from its corresponding X values

Is that right?

x1...x10 are 10 chemical components that can be absent (0), present (1), 
modified (2). yi represent a quality index of the mixtures and g is a 
global quality of the whole process.


I ztill don't really understand. What are you going to do with this
function f once you have it?

I would have thought the idea was that if someone gives you a new
mixture X[n+1] you can use f to predict how well it will work.
But that will just give you a y[n+1], and it's not clear what to
do with that. Do you append it to Y and feed an n+1 component
vector into g?

I think I still need more information about the underlying problem
before I can help you much.

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


Re: Why the list creates in two different ways? Does it cause by the mutability of its elements? Where the Python document explains it?

2021-06-15 Thread Greg Ewing

On 15/06/21 3:18 pm, Jach Feng wrote:

From a user's point, I don't really care how Python creates thoseinstances, > 
either using an already exist one or create a new one, as
long as each element (and its sub-element) are independent from each
other so a modification of one will not influence the other. The real
problem is there are different methods can be used to build it and some
will fail in this purpose. The * operator is one of them, but anyone
else? I really like to know:-)


This really has nothing to do with how the tuples are created.
It all depends on what you choose to put in them.

When you use square brackets to build a list, you can be sure that
it will create a new list object each time.

Also, if you create two tuples, by any means, containing distinct
elements, you can be sure that you will get two distinct tuple
objects.

So, if you do this:

a = [1, 2]
b = [1, 2]
c = [1, 2]
d = [1, 2]

s = (a, b)
t = (c, d)

then you are guaranteed to get four different list objects and
two diffferent tuple objects.

Does that help to ease your fears?

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


  1   2   3   4   5   >