Re: nonlocal fails ?

2019-11-15 Thread Gregory Ewing

On 16/11/19 8:22 am, Chris Angelico wrote:

That's the typical sort of description you get from someone who mostly
understands Python's semantics, but is hung up on the idea that
everything is either call-by-value or call-by-reference, and is trying
to figure out which box Python fits into.


Or they may have read the definition of "call by value" in the
Algol60 report, which says that "The actual parameter expression
is evaluated and the result is assigned to the formal parameter."
Which is exactly what Python does...

(Notably, that definition doesn't contain the word "value" at all.
So people who argue about the meaning of "call by value" based
on the meaning of "value" are barking in the wrong direction.)

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


Re: How execute at least two python files at once when imported?

2019-11-08 Thread Gregory Ewing

Cameron Simpson wrote:
I was unsure as to how serialised this was: just the import data 
structures or the whole source-of-the-module.


It's the whole source. I found that out the hard way once -- I had
a thread that imported a module whose main code ran an event processing
loop. It stopped any other threads from running, since the import
statement never finished.

--
Greg

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


Re: OOP - how to abort an __init__ when the initialisation code fails ?

2019-11-07 Thread Gregory Ewing

Oscar Benjamin wrote:

In Python the original exception message plus traceback is often very
informative (to a programmer!) about the problem.


That's okay, exception chaining preserves the whole traceback if
you want to dig down that far.


Catching and
reraising can mean that you end up crafting an error message somewhere
higher up where the filename isn't known any more.


Well, the idea is to catch it some place where the filename *is*
known. And when reraising, only add to the error message rather
than replacing it altogether, so once the filename is in there
it stays there, even if another catch-and-reraise occurs higher
up.

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


Re: How execute at least two python files at once when imported?

2019-11-07 Thread Gregory Ewing

Cameron Simpson wrote:
Spencer's modules run unconditional stuff in addition to defining 
classes. That may cause trouble.


It will -- because of the import lock, they won't run simultaneously
in the same process.

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


Re: What PEPs are worth reading after you've read a textbook/Beazley but want to understand details/innerworkings

2019-11-05 Thread Gregory Ewing

Gilmeh Serda wrote:


Can't wait until we get to PEP 84657675, or PEP 33


PEP TREE(3) promises to be even more exciting!

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


Re: OOP - how to abort an __init__ when the initialisation code fails ?

2019-11-05 Thread Gregory Ewing

Peter J. Holzer wrote:

On 2019-11-04 18:18:39 -0300, Luciano Ramalho wrote:


In addition, as Rob said, it is usually a bad idea to wrap several
lines of code in a single try/except block



I disagree with this. While it is sometimes useful to wrap a single
line, in my experience it rarely is. The scope of the try ... except
should be a unit from a semantic point of view. For example, if you
open a file and write some data to it, you could write:

try:
f = open("a.file", "w")
except OSError as e:
... handle exception
try:
f.write("some")
except OSError as e:
... handle exception
try:
f.write("data")
except OSError as e:
... handle exception
try:
close(f)
except OSError as e:
... handle exception

But not only is this hard to read and ugly as heck, what would be the
point? 


Much better to write:

try:
with open("a.file", "w") as f:
f.write("some")
f.write("data")
except OSError as e:
... handle exception

Or maybe don't catch it here at all but just let it bubble up until it
hits a level where dealing with it makes sense from the user's point of
view


Often it makes sense to do both -- catch the exception and
re-raise it with a more informative error message, e.g.

 try:
 with open(filename, "w") as f:
 f.write("some")
 f.write("data")
 except OSError as e:
 raise OSError("Couldn't write fibble data to %s: %s" % (filename, e))

That way you don't get frustrating Microsoft style error
messages which say "The system could not open the specified file"
while giving no clue about *which* file was specified... aarggh!

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


Re: Instantiating sub-class from super

2019-10-14 Thread Gregory Ewing

DL Neil wrote:
Is there a technique or pattern for taking a (partially-) populated 
instance of a class, and re-creating it as an instance of one of its 
sub-classes?


Often you can assign to the __class__ attribute of an instance
to change its class.

Python 3.7.3 (default, Apr  8 2019, 22:20:19)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Person:
...  pass
...
>>> class Male(Person):
...  pass
...
>>> p = Person()
>>> p.__class__ = Male
>>> isinstance(p, Male)
True
>>>

You would then be responsible for initialising any attributes of
Male that Person didn't have.

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


Re: Odd delays when cwd is on a network mount

2019-10-11 Thread Gregory Ewing

Cameron Simpson wrote:
Python's default sys.path includes the current working directory.  


Only in an interactive session, where it usually makes sense.

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


Re: Unicode UCS2, UCS4 and ... UCS1

2019-09-19 Thread Gregory Ewing

Eli the Bearded wrote:

There isn't anything called UCS1.


Apparently there is, but it's not a character set, it's a loudspeaker.

https://www.bhphotovideo.com/c/product/1205978-REG/yorkville_sound_ucs1_1200w_15_horn_loaded.html

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


Re: UserList from module collections

2019-09-10 Thread Gregory Ewing

ast wrote:


So what UserList is used for ?


It's mostly a leftover from the days when you couldn't subclass
built-in types. But it can still be useful if you want a custom
sequence object that doesn't inherit all of the built-in list
type's behaviour.

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


Re: issue in handling CSV data

2019-09-10 Thread Gregory Ewing

Sharan Basappa wrote:

Now, if you see the print after getting the data, it looks like this:

## 
[['"\t"81' '"\t5c'] 
 ['"\t"04' '"\t11'] 
 ['"\t"e1' '"\t17'] 
 ['"\t"6a' '"\t6c'] 
 ['"\t"53' '"\t69'] 
 ['"\t"98' '"\t87'] 
 ['"\t"5c' '"\t4b'] 
## 


But now you have weird things such as unmatched single quotes.

It seems that whichever way you try to interpret it -- tab
delimited or comma delimited -- it doesn't entirely make sense.
That leads me to believe it has been corrupted somehow.

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


Re: Color representation as rgb, int and hex

2019-09-09 Thread Gregory Ewing

Eko palypse wrote:

I thought a method called fromhex would imply that bytes for an integer
should be created


Why should it imply that? You're asking it to create some bytes
from a string of hex digits -- no mention of integers. The obvious
thing to do is to put the bytes in the order they apper in the
string.

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


Re: [Python-ideas] Re: Automatic translation of Python to assembly language

2019-09-09 Thread Gregory Ewing

Mark at PysoniQ.com wrote:
> an extension (.dll or .so) is not generally included in a
> makefile because it's dynamically linked and not incorporated into an
> executable -- which Python doesn't have.

If I change the source, the .dll or .so needs to be re-created. That's
a build step, and as such I'm going to want to automate it. Whether
I do that using a Makefile or some other tool isn't the point. The
point is that if I'm required to use a point-and-click interface,
then I can't automate it.

If there is an alternative interface that can be automated, that's fine.
But either way, the point and click interface is useless to me, and
therefore not a selling point for me in any way. I suspect the same
is true for many other people on the Python lists.

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


Re: An "Object" class?

2019-08-31 Thread Gregory Ewing

Cristian Cocos wrote:

And that is because entities belonging to the same
taxonomical class ("clade") have common features, and also inherit the
features of the taxonomical parent.


I think the notion you're after is what is known in the Python
world as a "protocol". This is an informal collection of methods
and behaviours that an object can conform to, which makes it
usable in certain ways. Some fundamental ones include the
sequence protocol, the mapping protocol, and the iterator
protocol.

I'm not aware of a diagram, but the "Built-In Types" section
of the Library Reference describes all the major protocols and
lists the types that belong to them.

Originally these protocols did not have any formal embodiment.
Nowadays Python has ABCs (Abstract Base Classes) which provides
a way to formalise them. You may also find it instructive to
look at the docs for the collections.abc module.

Note that ABCs a bit weird, because you can register a class as
belonging to an ABC, so that isinstance() and issubclass() will
behave as though the class inherits from the ABC even though
it doesn't. For example,

>>> import collections.abc
>>> issubclass(list, collections.abc.Sequence)
True
>>> list.__mro__
(, )

Unfortunately this means there is no easy way to find all the
ABCs that a given class is a member of, so you'll have to rely
on documentation to build the taxonomy that you're after.

Also, there is no requirement for a class implementing a given
protocol to be registered with a corresponding ABC. Most of the
built-in ones are, but there are plenty of classes out in the wild
that aren't. So there isn't any foolproof way for a program to ask
an object a question like "are you a sequence".

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


Re: An "Object" class?

2019-08-30 Thread Gregory Ewing

Cristian Cocos wrote:


type(print)





isinstance(print, builtin_function_or_method)


Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'builtin_function_or_method' is not defined

Just curious why builtin_function_or_method doesn't work as an argument of
isinstance().


Because the type object in question is not bound to the name
'builtin_function_or_method' in the builtin namespace. There
is a way to get at it, though:

>>> import types
>>> types.BuiltinFunctionType

>>> isinstance(print, types.BuiltinFunctionType)
True

When it comes to objects that form part of the interpreter's
internal machinery, the names shown when you print their types
are often just suggestive and aren't meant to be taken literally.
Most of them are available in the 'types' module, however,
possibly under different names. The reasons for all this are
buried in a lot of messy history.


The bottom line is that I am trying to figure out where exactly the world
of Python types _diverges from_ what I would expect as a mathematician. It
makes it easier for me to learn Python this way.


I'm not sure that focusing on classes as mathematical sets is all
that useful. In Python, what class an object belongs to isn't
usually very important. Much more relevant is how the object
*behaves*. We call this "duck typing" -- if it walks like a duck
and quacks like a duck then it might as well be a duck, even if
it doesn't belong to a class called "Duck".

This is why Python doesn't have e.g. an elaborate tower of
numeric types as is seen in some other languages. It just isn't
necessary for getting things done, and Python, being a very
pragmatic language, is all about getting things done.

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


Re: absolute path to a file

2019-08-16 Thread Gregory Ewing

On Sat, Aug 17, 2019 at 2:27 AM Paul St George  wrote:


BUT does not work with
| print('test2:',os.path.realpath(n.image.filepath))|

This returns only
|/image01.tif|


What does n.image.filepath look like on its own? If it starts
with a leading slash, then os.path.realpath will think it's
already an absolute path and leave it alone.

The problem then is why it's getting a leading slash in the
first place. It looks like the result of something naively
trying to append a filename to an empty directory path.

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


Re: Create multiple sqlite tables, many-to-many design

2019-08-15 Thread Gregory Ewing

Chris Angelico wrote:

I prefer to say "Trails" for the table, and "Trail" would then refer
to a single row from that table.


That makes sense for a data structure in your program that contains a
collection of rows. But I've come to the view that SQL tends to read
better if the names of the database tables are singular, because in SQL
you're writing assertions about individual rows, not the tables in
their entirety.

So I would write something like

   select T.name, T.id from Trail T

but I would assign the resulting list of rows to a variable named
"trails" in my program.

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


Re: Create multiple sqlite tables, many-to-many design

2019-08-14 Thread Gregory Ewing

MRAB wrote:
Another thing you might want to avoid is naming something with what it 
is, e.g. "Trails_Table" (why not just "Trails").


Or possibly just "Trail", since any table potentially contains
multiple rows, so making all your table names plural doesn't
add any information.

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


Re: Transfer Image from Raspberry Pi (Python) to Android app (Java)

2019-07-22 Thread Gregory Ewing

rkartun...@yahoo.com wrote:

This
code does successfully read in the bytes until there are around 2000-3000
bytes left to be read and then it seems to freeze on the int bytes_read =
in.read(msg_buff, 0, msg_buff.length) line.


This happens because you're trying to read more bytes than the sender
is sending. The receiver is trying to read a whole bufferful and has no
way to know that there aren't any more bytes coming, so it waits forever.

Your receiver needs to read exactly the right number of bytes. Keep
track of the number of bytes left to read, and when it's less than
the buffer size, issue a read for just that number instead of a whole
bufferful.

(The code you have would work if the sender closed its end of the
connection after sending the image, but you can't do that if you
want to get an OK message back.)

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


Re: List comprehension strangeness

2019-07-22 Thread Gregory Ewing

Nicholas Cole wrote:
 [x.id for x in some_function()]


According to the profiler, some_function was being called 52,000 times


Is some_function recursive, by any chance?

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


Re: Help? How do i solve this problem with Python List Concept

2019-05-11 Thread Gregory Ewing

Chris Angelico wrote:

Given that we're dealing with a Nigerian inheritance, your Python
program will probably need to start with "import smtplib", and the
list in question will be the addresses of the people to send your 419
to


Obviously it's a Nigerian homework scam.

"Dearest Sir,I am the youngest son of a wealthy Nigerian businessman
who died leaving the sum of N$230,000(two Hundred and thirty thousand
nigerianDollars) to be split between his 10 childern. I urgently need
your help to calculate the amount of my inheritance..."

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


Re: Generating generations of files

2019-05-01 Thread Gregory Ewing

Avi Gross wrote:

UNIX flowed the fields together with a limit of 14 that included an
actual optional period as a counted character.


The Unix kernel has no notion of a filename extension; a filename
is just a sequence of bytes. Using a dot-suffix to indicate a
file type is just a user-level convention.

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


Re: Generating generations of files

2019-05-01 Thread Gregory Ewing

On 2019-04-30, Cameron Simpson  wrote:


I'm pretty sure the VMS built in file versioning
went on the scheme MRAB described: rewriting version.rpt caused the old 
version to become "version.rpt;n" where n counted up from 1.


The version numbers certainly counted upwards. But I'm fairly sure
a version number was assigned as soon as you created a file, and
if you referred to just "version.rpt" it would default to the
latest version. Also I think a directory listing would only show
the latest version of each file unless you told it otherwise.

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


Re: How to catch a usefull error message ?

2019-04-25 Thread Gregory Ewing

Vincent Vande Vyvre wrote:

But the "return 0" is a common case for an "Foo_init()"

see: 
https://docs.python.org/3.5//extending/newtypes.html#adding-data-and-methods-to-the-basic-example


Look carefully at the init function from that example:

static int
Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
{
PyObject *first=NULL, *last=NULL, *tmp;

static char *kwlist[] = {"first", "last", "number", NULL};

if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
  &first, &last,
  &self->number))
return -1;
^

See that?

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


Re: need help understanding: converting text to binary

2019-04-23 Thread Gregory Ewing

Cameron Simpson wrote:
If you don't know the encoding then you don't know you're looking at a 
hex digit. OTOH, if the binary data contain ASCII data then you do know 
the encoding: it is ASCII.


Not necessarily, it could be a superset of ASCII such as latin-1 or
utf-8.

You do need to know that it is such an encoding, however. If the
encoding is completely unknown, you can't make any assumptions.

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


Re: How to catch a usefull error message ?

2019-04-23 Thread Gregory Ewing

Vincent Vande Vyvre wrote:

static int
ImgProc_init(ImgProc *self, PyObject *args, PyObject *kwds)
{
PyObject *tmp;
char *fname;

if (!PyArg_ParseTuple(args, "s", &fname))
return NULL;


You should be returning -1 here, not NULL.

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


Re: Friday Filosofical Finking: Import protections

2019-04-18 Thread Gregory Ewing

DL Neil wrote:
Thus the basic question: why do we (apparently) so seldom consider the 
possibility of an ImportError?


Because the cases in which we can do something useful about
it are relatively rare.

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


Re: immutability is not strictly the same as having an unchangeable value, it is more subtle

2019-04-18 Thread Gregory Ewing

Arup Rakshit wrote:

What protocols I need to
learn, to define a custom immutable class ?


That depends on how strictly you want to enforce immutability.

The easiest thing is not to enforce it at all and simply refrain
from mutating it. This is very often done.

You can provide some protection against accidental mutation
by using properties, for example,

class Foo:

def __init__(self, x):
self._x = x

@property
def x(self):
return self._x

This will let you read the x attribute but not directly assign
to it. Of course, it doesn't prevent someone from accessing the
underlying _x attribute, but there's no way to do that for a
class defined in Python. The only way to make a completely
bulletproof immutable object would be to write an extension
module in C or Cython.

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


Re: Why inspect.isclass says iter() a class?

2019-04-10 Thread Gregory Ewing

Chris Angelico wrote:

At the moment, it isn't defined particularly as either a function or a
class,


Well, it's listed under a section called "Functions", so the reader
could be forgiven for assuming that it's a function. From a high
level point of view, it is -- you call it and it returns something.
Concretely, it happens to be implemented as a class, but that's not
something you need to know in order to use it, so the docs don't
mention it.

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


Re: From parsing a class to code object to class to mappingproxy to object (oh my!)

2019-04-06 Thread Gregory Ewing

adam.pre...@gmail.com wrote:

I've figured from this that I could do most
variable access by just generating LOAD/STORE_NAME and the FAST is an
(important) optimization.


Yes, that's possible, although access to intermediate scopes
(i.e. nonlocal) will need something else.


An
important exception there would be for built-ins and presumably imported
stuff, right?


No, importing things just binds names in your module namespace,
so LOAD_GLOBAL does for them too. Also builtins, since if
LOAD_GLOBAL doesn't find something in the module namespace,
it looks in the builtins.


I'm asking because right now I've literally hard-coded some logic that tells
me if I'm generating a class body so I know to use names. I just feel kind of
silly doing that.


There's nothing silly about that -- it's effectively what CPython
does.

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


Re: From parsing a class to code object to class to mappingproxy to object (oh my!)

2019-04-05 Thread Gregory Ewing

adam.pre...@gmail.com wrote:

Something I
don't really understand from a code generation perspective is the switch over
to STORE_NAME for class methods.


That's because, in this particular situation, the locals are
being kept in a dict instead of an array.

When compiling an ordinary function, the compiler figures out
what locals there are, and generates LOAD_FAST and STORE_FAST
opcodes to access them by index.

But when compiling a class body, it uses a dict to hold the
locals, and generates LOAD_NAME and STORE_NAME opcodes to
access it.

These opcodes actually date from very early versions of
Python, when locals were always kept in a dict. When
optimised locals were introduced, the old mechanism was kept
around for building class dicts. (There used to be one or
two other uses, but I think classes are the only one left
now.)

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


Re: From parsing a class to code object to class to mappingproxy to object (oh my!)

2019-03-31 Thread Gregory Ewing

adam.pre...@gmail.com wrote:

What is the plumbing taking the result of that code object over to this
proxy? I'm assuming __build_class__ runs that code object and then starts
looking for new names and see to create this. 



Is this mapping proxy the
important thing for carrying the method declaration?


No, the mapping proxy is only there to prevent Python code from directly
accessing the dict holding the class's attributes. (If that were
allowed, bad things could be done that would crash the interpreter.)

There's a fairly good analysis of what __build_class__ does here:

https://eli.thegreenplace.net/2012/06/15/under-the-hood-of-python-class-definitions

Briefly, it creates a dict to serve as the class's namespace dict,
then executes the class body function passed to it, with that dict
as the local namespace. So method defs and other assignments go
straight into what will become the class namespace when the class
object is created.


I'm then assuming that in object construction, this proxy is carried by some
reference to the final object in such a way that if the class's fields are
modified, all instances would see the modification unless the local object
itself was overridden.


There's nothing fancy going on at that stage. The object contains
a reference to its class, that's all. If an attribute is not found
in the object, it is then looked for in the namespace of its class,
then its base classes in mro order. (Actually it's more complicated
than that to allow for descriptors, but that's the basic idea.)

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


Re: array of characters?

2019-03-22 Thread Gregory Ewing

Paul Rubin wrote:

- array('u') works but it is deprecated, and (not sure) the doc page
  says the object size is 2 bytes, so it may only handle BMP characters


The docs actually say "Depending on the platform, it can be 16 bits or 32
bits".

With Python 3.5 on MacOSX, it seems to work and hold the full range of
unicode characters.

Not sure why this is being deprecated instead of just making it always
32 bits. I'll make some enquiries.

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


Re: Question regarding the local function object

2019-03-16 Thread Gregory Ewing

Terry Reedy wrote:
I believe 
that CPython function objects must currently all have the same size or 
at least the same max size and conclude that CPython currently allocates 
them from a block of memory that is some multiple of that size.


I wouldn't be surprised if there is a free list for function objects,
which would make it even more likely that you would observe this
kind of re-use.

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


Re: Help!!! How to apply my created function to another function

2019-03-10 Thread Gregory Ewing

djoy...@gmail.com wrote:


def buildVector(v) :
print(v[0],v[1],v[2])


If you want to be able to use the result of this function
in another computation, you need to return it, not print it:

def buildVector(v) :
return (v[0],v[1],v[2])

Similarly with buildRandomVector and vectorMagnitude.

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


Re: Lifetime of a local reference

2019-03-01 Thread Gregory Ewing

Alan Bawden wrote:

The Java compiler has no way to know whether a variable references an
object with a finalize() method that has side effects


It should be able to tell in some situations, e.g.

String a = "hello";
String b = a.replace('e', 'u');

There's no way that b can reference anything other than a
plain String instance at this point.

Maybe Java implementations are living dangerously and making
assumptions beyond this. My point is that I would expect a
Python implementation to be careful enough not to get this
wrong.

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


Re: Lifetime of a local reference

2019-02-27 Thread Gregory Ewing

Thomas Jollans wrote:

If the inspect module's stack frame inspection machinery is supported,
then any function call might access any local... (though I don't think a
compliant Python implementation necessarily has to support the inspect
module fully).


You can be devious even without using the expect module:

def fun():
f = open("lock.txt", "w")
do_stuff(innocent_argument)

do_stuff = exec
innocent_argument = "f.write('foo')"

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


Re: Lifetime of a local reference

2019-02-27 Thread Gregory Ewing

Alan Bawden wrote:

the Java Language
Specification contains the following language:

   Optimizing transformations of a program can be designed that reduce the
   number of objects that are reachable to be less than those which would
   naively be considered reachable.  For example, a Java compiler or code
   generator may choose to set a variable or parameter that will no longer be
   used to null to cause the storage for such an object to be potentially
   reclaimable sooner.


However, it only makes sense to do that if the compiler can be
sure that reclaiming the object can't possibly have any side
effects. That's certainly not true of things like file objects
that reference resources outside of the program. I'd be pretty
upset if a Java implementation prematurely closed my files on
the basis of this clause.

Similar considerations apply to Python. Even more so, because
its dynamic nature makes it next to impossible for the compiler
to prove much of anything about side effects. So I wouldn't
expect a Python implementation to even try to drop any
references early. If it does, I would hope it darn well knows
what it's doing.

Summary: You don't have to worry about it.

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


Re: Quirk difference between classes and functions

2019-02-26 Thread Gregory Ewing

Thomas Jollans wrote:

I imagine there's a justification for the difference in behaviour to do
with the fact that the body of a class is only ever executed once, while
the body of a function is executed multiple times.


I suspect there isn't any deep reason for it, rather it's just
something that fell out of the implementation, in particular
the decision to optimise local variable access in functions
but not other scopes.

When compiling a function, the compiler needs to know which
variables are local so that it can allocate slots for them in
the stack frame. But when executing a class body, the locals
are kept in a dict and are looked up dynamically.

The compiler *could* be made to treat class bodies the same
way as functions in this regard, but it would be extra work
for little or no benefit. Most code in class bodies just
defines new names without referring to anything else in the
same scope.

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


Re: Quirk difference between classes and functions

2019-02-25 Thread Gregory Ewing

Chris Angelico wrote:

Classes and functions behave differently. Inside a function, a name is
local if it's ever assigned to; but in a class, this is not the case.


Actually, it is. Assigning to a name in a class body makes it part
of the class namespace, which is the local namespace at the time
the class body is executed.

The unusual thing about a class namespace is that it doesn't
form part of the scope of closures created within the class.
So methods, for example, can't directy see attributes of the
class they're defined in.

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


Re: What's the address for?

2019-02-18 Thread Gregory Ewing

Stefan Ram wrote:

  What's so important about the (presumed) address of a
  function that it is shown on every stringification of
  each function?


Its value isn't important at all. It's just a way of
distinguishing different objects in debugging output.

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


Re: FW: Why float('Nan') == float('Nan') is False

2019-02-15 Thread Gregory Ewing

Avi Gross wrote:

I can see why you may be wondering. You see the nan concept as having a
specific spelling using all lowercase and to an extent you are right.


No, he's talking about this particular line from the transcript you
posted:

>>>float("  nan")
> Nan

This suggests that the interpreter printed out that particular
nan value as "Nan" with a capital N. But that's not what my
Python 3.5.1 interpreter does:

Python 3.5.1 (default, Jun  1 2016, 13:15:26)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> float("  nan")
nan

Grant was asking whether that's *really* what your interpreter
printed out, and if so, which version of Python it was, because
it's quite a surprising thing for it to do.

Personally I think it's more likely that the N got capitalised
somehow on the way from your terminal window to the mail message.

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


Re: Convert a list with wrong encoding to utf8

2019-02-15 Thread Gregory Ewing

vergos.niko...@gmail.com wrote:

[python] con = pymysql.connect( db = 'clientele', user = 'vergos', passwd =
'**', charset = 'utf8' ) cur = con.cursor() [/python]

From that i understand that the names being fetched from the db to pyhton
script are being fetced as utf8, right?


No, I don't think so.

As far as I can tell from a brief reading of the MySQL docs, that only
sets the *connection* encoding, which is concerned with transferring
data over the connection between the client and the server. It has no
bearing on the encoding used to decode data fetched from the database.

That's determined by metadata stored in the database itself. It seems
that MySQL lets you specify database encodings at three different levels:
for the database as a whole, for a specific table, and for a specific
field of a table.

What I think is happening is that the column you're reading the names
from is tagged in the database as being encoded in latin1, *but* this
is incorrect for some of the names, which are actually encoded in
utf8.

This would explain why some of the data you looked at was printed
with hex escapes, and why name.encode('latin1').decode('utf8')
appeared to fix it. The encode('latin1') gets back the original raw
bytes, and the decode('utf8') decodes them again using the correct
encoding.

However, not *all* of the data is like this -- some of it is correctly
stored in the database, and is coming back already correctly decoded
with no further processing needed. So, when you blindly try to re-code
all the names in the list, it fails on the first correctly-decoded one
it encounters.

Again, try printing out the whole list of names, and post it here (or
a good chunk of it if it's very long). It will give us a better idea
of what's going on.

If this theory is correct, then there isn't really any "right" way
to deal with it -- the fundamental problem is that the data in the
database is corrupted.

The best long-term solution would be to clean up the database. But if
you have to deal with it as it is, you'll need to use some kind of
heuristic to decide when a particular string needs "fixing", and
what needs to be done to fix it.

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


Re: Convert a list with wrong encoding to utf8

2019-02-14 Thread Gregory Ewing

vergos.niko...@gmail.com wrote:

I just tried:

names = tuple( [s.encode('latin1').decode('utf8') for s in names] )

but i get
UnicodeEncodeError('latin-1', 'Άκης Τσιάμης', 0, 4, 'ordinal not in range(256)')


This suggests that the string you're getting from the database *has*
already been correctly decoded, and there is no need to go through the
latin1 re-coding step.

What do you get if you do

   print(names)

immediately *before* trying to re-code them?

What *may* be happening is that most of your data is stored in the
database encoded as utf-8, but some of it is actually using a different
encoding, and you're getting confused by the resulting inconsistencies.

I suggest you look carefully at *all* the names in the list, straight
after getting them from the database. If some of them look okay and
some of them look like mojibake, then you have bad data in the database
in the form of inconsistent encodings.

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


Re: the python name

2019-01-18 Thread Gregory Ewing

DL Neil wrote:

(not that New Zealanders need to know much about snakes!)


Probably recommended when we visit Australia, though.

Also we seem to have imported some of their spiders in recent
years, so it's only a matter of time before their snakes
follow.

I wonder if we could get Australia to pay for a snake-proof
wall across the Tasman?

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


Re: the python name

2019-01-16 Thread Gregory Ewing

Dennis Lee Bieber wrote:

Getting too close to REXX (which was something like Restructured
EXtended eXecutor).


And if we continue the theme of dinosaur evolution, we end up
with Tyrannosaurus REXX.

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


Re: the python name

2019-01-16 Thread Gregory Ewing

Avi Gross wrote:

The question that seems to come up too often about the python name is a
distraction. In particular, it is answered fairly prominently in many places
as just being a nonsensical name because a founder once liked a comedic
entity that chose an oddball name, so they did too.


That may be how it started, but I don't think Python is a silly name
for a programming language at all.

There's a long tradition of naming things after animals that have some
of the qualities you want people to associate with them. In the case
of Python, it's not a particularly fast animal, but it is sleek and
powerful, and its minimal design has a certain elegance to it.
So, I think it's very appropriate.

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


Re: sampling from frequency distribution / histogram without replacement

2019-01-14 Thread Gregory Ewing

duncan smith wrote:

Hello,
  Just checking to see if anyone has attacked this problem before
for cases where the population size is unfeasibly large.


The fastest way I know of is to create a list of cumulative
frequencies, then generate uniformly distributed numbers and
use a binary search to find where they fall in the list.
That's O(log n) per sample in the size of the list once it's
been set up.

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


Re: zeroed out

2018-12-12 Thread Gregory Ewing

MRAB wrote:
Later processors have a DAS instruction, which is used after BCD 
subtraction.


The humble 6502 doesn't have DAA/DAS, but instead has a decimal mode flag.


The 68000 also had a Decimal Add instruction, but disappointingly
it only worked a byte at a time. I guess running COBOL at high
speed wasn't a priority by then.

But for sheer unadulterated decimalness, you can't beat the
custom CPU that HP used in their handheld calculators in the
70s and 80s. Early versions of it did *only* decimal arithmetic
(on 14-digit registers and memory locations). An option for
binary wasn't added until the HP-41.

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


Re: Accessing clipboard through software built on Python

2018-10-27 Thread Gregory Ewing

Musatov wrote:

From a webpage.


Does it always come from the same web site? If so, you may be able
to scrape the web page to get the username and address, and then
have hot keys for pasting them.

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


Re: Is it dangeous when using custom metaclass?

2018-10-15 Thread Gregory Ewing

jf...@ms4.hinet.net wrote:

class Structure(metaclass=StructureMeta): ...

class PolyHeader(Structure): ...

As my understanding, the metaclass's __init__ was called when a class was
created. In the above example, both the Structure and PolyHeader called it.
My question is: because the PolyHeader inherited Structure, is it reasonable
for PolyHeader to call this __init__ again? Will it cause any possible
trouble?


It's reasonable for both to call it, because they're distinct
instances of StructureMeta, each of which need to be initialised.

Whether it will cause a problem depends on what StructureMeta's
__init__ is supposed to do. Presumably you want a given structure
class to start allocating its offsets where its base class left
off, in which case you may need to do something like this:

class StructureMeta(type):
def __init__(self, clsname, bases, clsdict):
if bases:
   offset = bases[0].offset # assuming there isn't more than one base
else:
   offset = 0
...

(BTW, why do you use setattr() to set the offset attribute
instead of just doing self.offset = offset?)

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


Re: Python indentation (3 spaces)

2018-10-15 Thread Gregory Ewing

Cameron Simpson wrote:
I can't express how pleasing it is to see the traditional vi-vs-emacs 
wars supplanted by emacs-vs-emacs :-)


We're the People's Front of Emacs, not the Emacs People's Front!

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


Re: ESR "Waning of Python" post

2018-10-12 Thread Gregory Ewing

Paul Rubin wrote:

I even wonder what happens if you turn Py_INCREF etc. into no-ops,
install the Boehm garbage collector in a stop-the-world mode, and
disable the GIL.


I suspect you would run into problems with things that need
mutual exclusion but don't do any locking of their own, because
the GIL is assumed to take care of it.

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


Re: ESR "Waning of Python" post

2018-10-10 Thread Gregory Ewing

Paul Rubin wrote [concerning GIL removal]:

It's weird that Python's designers were willing to mess up the user
language in the 2-to-3 transition but felt that the C API had to be kept
sarcosanct.  Huge opportunities were blown at multiple levels.


You say that as though we had a solution for GIL removal all
thought out and ready to go, and the only thing that stopped us
is that it would have required changing the C API.

But it's not like that at all. As far as I know, all the
attempts that have been made so far to remove the GIL have
led to performance that was less than satisfactory. It's a
hard problem that we haven't found a good solution to yet.

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


Re: From Mathematica to Jypyter

2018-10-10 Thread Gregory Ewing

Thomas Jollans wrote:
Sure it is. He's contrasting *private* gain with *public* loss. If there 
is any ambiguity here it is whether there is a threat *of* a public 
loss, or *to* a public loss ^_^


I don't think you've spotted the error yet. I'm trying to
provide a clue as to which word you need to examine...

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


Re: From Mathematica to Jypyter

2018-10-10 Thread Gregory Ewing

Chris Angelico wrote:

You mean at the level of words, or sentences?


I mean at the word level, so that a dumb algorithm can find
spelling errors. Auto-correcting errors at the semantic level
would require considerably better AI than we have at the moment.

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


Re: From Mathematica to Jypyter

2018-10-10 Thread Gregory Ewing

Rhodri James wrote:
I'm a great fan of erroneous spelling and this blog needs a spelling 
check as this quote shows


"Mathematica exemplifies the horde of new Vandals whose pursuit of 
private gain threatens a far greater pubic loss–the collapse of social 
systems that took centuries to build."


OK, colour me confused.  The only spelling mistake I can spot in that is 
in the subject line of this thread.  What am I missing?


Presumably Romer meant that it was a loss suffered by everyone,
but that's not quite what he wrote.

BTW, an automatic spelling checker wouldn't have helped here.
We really need to redesign English spelling so that it has
error correction built in.

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


Re: How to change '\\' to '\'

2018-09-27 Thread Gregory Ewing

Jach Fong wrote:

I get a string item, for example path[0], from path = os.get_exec_path()
It's something like "\\Borland\\Bcc55\\Include"


It doesn't actually have double backslashes in it, that's just a
result of how the string is being displayed. No conversion is
needed.

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


Re: clever exit of nested loops

2018-09-27 Thread Gregory Ewing

Neal Becker wrote:
but it does violate the principle "Exceptions should 
be used for exceptional conditions).


Python doesn't really go in for that philosophy.
Exceptions are often used for flow control, e.g.
StopIteration.

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


Re: Verifying the integrity/lineage of a file

2018-09-04 Thread Gregory Ewing

Grant Edwards wrote:

Writing your own crypto software isn't a problem, and it can be very
educational.

Just don't _use_ your own crypto software.


Okay, so find a friend who also likes writing crypto
software, and use each other's software. Problem solved. :-)

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


Re: Question about floating point

2018-08-30 Thread Gregory Ewing

Steven D'Aprano wrote:
The right way is to 
set the rounding mode at the start of your application, and then let the 
Decimal type round each calculation that needs rounding.


It's not clear what you mean by "rounding mode" here. If you
mean whether it's up/down/even/whatever, then yes, you can
probably set that as a default and leave it.

However, as far as I can see, Decimal doesn't provide a
way of setting a default number of decimal places to
which results are rounded. You can set a default *precision*,
but that's not the same thing. (Precision is the total
number of significant digits, not the number of digits
after the decimal point.)

So if you're working with dollars and cents and want all
your divisions rounded to 2 places, you're going to have
to do that explicitly each time.

I don't think this is a bad thing, because often you
don't want to use the same number of places for everything,
For example, people dealing with high-volume low-value goods
often calculate with unit prices having more than 2 decimal
places. In those kinds of situations, you need to know
exactly what you're doing every step of the way.

We have here a brilliant hammer specially designed for 
banging in just this sort of nail,


Except that we don't, we actually have an impact screwdriver,
so you've going to have to bring your hammer to deal with
nails properly. And a single size of hammer isn't going to
suit all kinds of nail.

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


Re: Question about floating point

2018-08-30 Thread Gregory Ewing

Steven D'Aprano wrote:
Why in the name of all that's holy would anyone want to manually round 
each and every intermediate calculation when they could use the Decimal 
module and have it do it automatically?


I agree that Decimal is the safest and probably easiest way to
go, but saying that it "does the rounding automatically" is
a bit misleading.

If you're adding up dollars and cents in Decimal, no rounding
is needed in the first place, because it represents whole
numbers of cents exactly and adds them exactly.

If you're doing something that doesn't result in a whole
number of cents (e.g. calculating a unit price from a total
price and a quantity) you'll need to think about how you want it
rounded, and should probably include an explicit rounding step,
if only for the benefit of someone else reading the code.

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


Re: Question about floating point

2018-08-28 Thread Gregory Ewing

Frank Millman wrote:
I have been trying to explain why 
they should use the decimal module. They have had a counter-argument 
from someone else who says they should just use the rounding technique 
in my third example above.


It's possible to get away with this by judicious use of rounding.
There's a business software package I work with that does this --
every number is rounded to a defined number of decimal places
before being stored in its database, so the small inaccuracies
resulting from inexact representations don't get a chance to
accumulate.

If you're going to do this, I would NOT recommend using the
rounding technique in your example -- it seems to itself be
relying on accidents of the arithmetic. Use the round()
function:

>>> 1.1 + 2.2
3.3003
>>> round(1.1 + 2.2, 1)
3.3

Also, if you go this route, always keep in mind *why* it works --
it relies on the actual value always being close enough to
a multiple of a power of 10 that it rounds to the correct
value when converted to decimal.


Are there edge cases where that rounding method could fail?


Yes, it's easy to come up with examples that make it fail,
e.g. multiplying by a large number, or adding up a few billion
monetary amounts before rounding. These things are very
unlikely to happen in an accounting application, but they
are theoretically possible.

So, you can probably make it work if you're careful, but for
peace of mind I would still recommend using Decimal, because
Python has it, and it eliminates all of these potential
problems.

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


Re: Broken pip

2018-08-28 Thread Gregory Ewing

Chris Angelico wrote:

On 2018-08-28 13:19, Larry Martell wrote:

source .bashrc

I'm not sure what the point of it is, but
maybe it's ensuring that your $PATH is set correctly.


The installation you just did might have edited your
.bashrc file (to modify PATH etc.), so it ensures that
your current shell is up to date with those changes.

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


Re: Pylint false positives

2018-08-20 Thread Gregory Ewing

Marko Rauhamaa wrote:

Lexically, there is special access:

   class C:
   def __init__(self, some, arg):
   c = self
   class D:
   def method(self):
   access(c)
   access(some)
   access(arg)


That's only because the definition of method() is lexically
inside the definition of __init__(). It has nothing to do
with nesting of the *class* statements.

Inner classes in Java have some special magic going on that
doesn't happen with nested classes in Python.


the reason to use a class is that there is no handier way to create
a method dispatch or a singleton object.


That's perfectly fine, but you can do that without creating
a new class every time you want an instance. You just have
to be *slightly* more explicit about the link between the
inner and outer instances.

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


Re: Pylint false positives

2018-08-20 Thread Gregory Ewing

Marko Rauhamaa wrote:

Some of these chores are heavier, some of them are lighter. But where I
have used Python, performance hasn't been a bottleneck. It it were, I'd
choose different approaches of implementation.


The point is that creating a class object every time you want a
closure is pointlessly wasteful. There is *no benefit whatsoever*
in doing that. If you think there is, then it's probably because
you're trying to write Java programs in Python.


But now I'm thinking the original Java approach (anonymous inner
classes) is probably the most versatile of them all. A single function
rarely captures behavior. That's the job of an object with its multiple
methods. In in order to create an ad-hoc object in Python, you will need
an ad-hoc class.


An important difference between Python and Java here is that in
Python the class statement is an *executable* statement, whereas
in Java it's just a declaration. So putting a class statement
inside a Python function incurs a large runtime overhead that
you don't get with a Java inner class.

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


Re: Pylint false positives

2018-08-20 Thread Gregory Ewing

Marko Rauhamaa wrote:

Chris Angelico :


3) Every invocation of method() has to execute the class body, which
takes time.


That's what happens with every method invocation in Python regardless.


No, it doesn't! Invoking a method involves creating a bound method
object, which is very small and lightweight. Executing a class
statement creates a class object, which is enormous by comparison,
and quite expensive to initialise.

A quick test of your Outer class vs. Chris Angelico's version
suggests that yours is about 12 times slower at creating instances
of Inner.

from timeit import timeit

class Outer1:

def method(self):
outer = self
class Inner:
def spam(self, a, b):
outer.quarantine(a, b)
return Inner()

def quarantine(self, a, b):
pass


def test1():
x = Outer1()
for i in range(10):
y = x.method()
y.spam(1, 2)


class Outer2:

class Inner:

def __init__(self, outer):
self.outer = outer

def spam(self, a, b):
self.outer.quarantine(a, b)

def method(self):
return self.Inner(self)

def quarantine(self, a, b):
pass


def test2():
x = Outer2()
for i in range(10):
y = x.method()
y.spam(1, 2)


t1 = timeit(test1, number = 1)
print("Nested class:", t1)

t2 = timeit(test2, number = 1)
print("Non-nested class:", t2)

print("Ratio =", t1 / t2)

--
Results:
--
Nested class: 1.89952481718
Non-nested class: 0.15806536600030086
Ratio = 12.01733729573816

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


Re: Pylint false positives

2018-08-20 Thread Gregory Ewing

Marko Rauhamaa wrote:

At least some of the methods of inner classes are closures (or there
would be no point to an inner class).


In Python there is no such thing as an "inner class" in the Java
sense. You can nest class statements, but that just gives you
a class that happens to be an attribute of another class.
Nothing in the nested class has any special access to anything
in the containing class.

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


Re: Fishing from PyPI ?

2018-08-06 Thread Gregory Ewing

Chris Warrick wrote:

The unusual domain is a common staple of Mailchimp, which is an e-mail
newsletter platform (it was used to mail out the announcement), and
they replace all links with tracking ones in their list-manage.com
domain.


Sounds like you need to find a mail service that doesn't
screw around with the contents of your messages. This is
really quite obnoxious, IMO.

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


Re: coding style - where to declare variables

2018-07-23 Thread Gregory Ewing

Steven D'Aprano wrote:

So let me see if I understand your argument...

- we should stop using the term "binding", because it means 
  nothing different from assignment;

- binding (a.k.a. "assignment") comes from lambda calculus;
- which has no assignment (a.k.a. "binding").


No, that's not what Marko is saying at all. He's pointing
out that the term "binding" means something completely
different in lambda calculus.

The terms "bound variable" and "free variable" in lambda
calculus mean what in Python we would call a "local
variable" vs. a "non-local variable". They have nothing
to do with assignment at all.

Marko is asking us to stop using the word "binding" to
refer to assignment because of the potential confusion
with this other meaning.

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


Re: Glyphs and graphemes [was Re: Cult-like behaviour]

2018-07-19 Thread Gregory Ewing

Chris Angelico wrote:

On Thu, Jul 19, 2018 at 4:41 PM, Gregory Ewing
 wrote:


(Google doesn't seem to think so -- it asks me whether
I meant "assist shop". Although it does offer to translate
it into Czech...)


Into or from?? I'm thoroughly confused now!


Hard to tell. This is what the link said:

assistshop - Czech translation - bab.la English-Czech dictionary
https://en.bab.la/dictionary/english-czech/assistshop
Translation for 'assistshop' in the free English-Czech dictionary and many other 
Czech translations.


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


Re: Glyphs and graphemes [was Re: Cult-like behaviour]

2018-07-18 Thread Gregory Ewing

Stefan Ram wrote:

  »assistshop«,


Is that a word?

(Google doesn't seem to think so -- it asks me whether
I meant "assist shop". Although it does offer to translate
it into Czech...)

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


Re: Glyphs and graphemes [was Re: Cult-like behaviour]

2018-07-18 Thread Gregory Ewing

Stefan Ram wrote:

Gregory Ewing  writes:



That's debatable. I've never thought of it that way and I'm
fairly certain I don't pronounce it that way. My tongue does
not do the same thing when I say "ch" as it does when I
say "tsh".


archives   ˈɑɚ kɑɪvz (n)
bachelor   ˈbæʧ lɚ (n)
machine məˈʃin
cash    kæʃ
dachshund  ˈdɑks ˌhʊnt


I'm talking specifically about the "ch" sound in
"bachelor", "change", etc. It sounds and feels like
a single sound to me.

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


Re: Glyphs and graphemes [was Re: Cult-like behaviour]

2018-07-18 Thread Gregory Ewing

MRAB wrote:
"ch" usually represents 2 phonemes, basically the sounds of "t" followed 
by "sh";


That's debatable. I've never thought of it that way and I'm
fairly certain I don't pronounce it that way. My tongue does
not do the same thing when I say "ch" as it does when I
say "tsh".

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


Re: Cult-like behaviour [was Re: Kindness]

2018-07-15 Thread Gregory Ewing

Abdur-Rahmaan Janhangeer wrote:

maybe another word for pep revocation is fork


No, anyone can fork Python whenever they want, no discussion
required, without affecting Python itself.

Revoking a PEP would mean removing its implementation from
the main CPython repository.

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


Re: Cult-like behaviour [was Re: Kindness]

2018-07-14 Thread Gregory Ewing

Paul Rubin wrote:

If you see the historical absence
of an assignment operator in Python as a mistake, then the introduction
of := is a fix for the mistake that only happened because people kept
complaining.


That's not quite the same thing. There was no a PEP saying
that there would never be assignment expressions in Python, so
there was room for useful debate. Now that the := PEP is
accepted, further argument about it is not productive. As
far as I know, no PEP has ever been revoked after acceptance,
and that's a good thing for the stability of the language.

It's like the rule sports usually have that the referee's
decision is final, even if it turns out to be wrong. At some
point you need to make a decision and move on.

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


Re: Guido van Rossum resigns as Python leader

2018-07-13 Thread Gregory Ewing

Larry Martell wrote:

And while we're talking about the Dutch, why is the country called
Holland, but then also The Netherlands, but the people are Dutch?


And Germany is called Deutchland?

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


Re: Guido van Rossum resigns as Python leader

2018-07-13 Thread Gregory Ewing

Chris Angelico wrote:

and eventually a 99.99% Dutch solution
will be produced.


Does this mean we need an is_probably_dutch() function?

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


Re: Kindness

2018-07-13 Thread Gregory Ewing

Joe Pfeiffer wrote:

He once went on for *weeks* about C's (yes, this was in c.l.c) failure
to have what he regards as a "proper" for-loop.


That could only have happened if there were people willing
to keep replying to him about it for weeks. So, if it was
a bad thing, you can't say it was entirely his fault.

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


Re: about main()

2018-07-06 Thread Gregory Ewing

Robin Becker wrote:
The 
villagers will shout "hey siri I need a compiler" and one will be 
provided


Then one day someone says "Hey, Siri, make me an artificial
intelligence that can respond to voice commands", and then
it's not long before the AIs are breeding by themselves and
take over. Berries are no longer required after that.

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


Re: about main()

2018-07-05 Thread Gregory Ewing

Steven D'Aprano wrote:
Even the Eskimos and Inuit, living in some of the harshest 
environments on earth, managed to have a relatively wide variety of foods 
in their diet.


They might be living on a very wide variety of berries.

Or perhaps, in their language, "berry" simply means "food".

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


Re: Congrats to Chris for breaking his PEP curse

2018-07-04 Thread Gregory Ewing

Steven D'Aprano wrote:
Not everything in Python uses a strict left-to-right reading order. Just 
like English really.


Well, English is read left to right, but it doesn't always
mean things in the order it says them. :-)

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


Re: File names with slashes [was Re: error in os.chdir]

2018-07-04 Thread Gregory Ewing

Mikhail V wrote:

There is one issue that I can't write \ on the end:
r"C:\programs\util\"

But since I know it's a path and not a file, I just write without trailing \.


Indeed. There's never a need to put a backslash on the end of
a path, as long as you always use os.path functions or
equivalent to manipulate them. Which is a good idea anyway,
since it will make things easier if anyone ever wants to
run the code on something other than Windows.

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


Re: PEP 526 - var annotations and the spirit of python

2018-07-04 Thread Gregory Ewing

Steven D'Aprano wrote:

but the type checker should infer that if you assign None to a variable 
which is declared int, you must have meant Optional[int] rather than just 
int.


This seems to be equivalent to saying that *all* types are
Optional, in which case what point is there in having Optional
at all?

Indeed, that's often the best way, except for the redundant type hint, 
which makes you That Guy:


x: int = 0  # set x to the int 0


But you've shown in an earlier example that such a hint is
*not* always redundant, e.g.

   x = 0
   x = 2.5

is legal and useful, whereas

   x: int = 0
   x = 2.5

ought to be a type error.

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


Re: Congrats to Chris for breaking his PEP curse

2018-07-04 Thread Gregory Ewing

Ian Kelly wrote:

I can't now write all my statements as:

f(f := lambda f: do_something())


No, but you should be able to do

   (f := lambda f: do_something())(f)

although since you're binding f in a scope that can be seen
by the lambda, there's probably not much point in passing it,
you could just do

   (f := lambda: do_something())()

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


Re: PEP 526 - var annotations and the spirit of python

2018-07-04 Thread Gregory Ewing

Ben Finney wrote:

Abdur-Rahmaan Janhangeer  writes:


[…]
*cut at this point*


Ooh, I like that last step! How do we make that happen on demand?


You mention that Nazis ate fish.

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


Re: PEP 526 - var annotations and the spirit of python

2018-07-04 Thread Gregory Ewing

Grant Edwards wrote:

On 2018-07-03, Dan Stromberg  wrote:


I used to write useful programs that ran in 256 bytes of RAM.


Me too.


The hex monitor I wrote for the keypad/display on my first
computer fitted in 256 bytes. Which was important, seeing
as the whole machine only had 1.5k.

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


Re: Multi-threading with a simple timer?

2018-07-04 Thread Gregory Ewing

Another way on unix that doesn't use signals:

import select, sys

print("Enter something: ", end = "")
sys.stdout.flush()
fds = select.select((0,), (), (), 5)
if fds[0] == [0]:
data = sys.stdin.readline()
print("You entered:", data)
else:
print("Too late!")

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


Re: Multi-threading with a simple timer?

2018-07-03 Thread Gregory Ewing

Robin Becker wrote:
if I leave out the signal.signal(signal.SIGALRM,signal.SIG_IGN) then the 
timeout function gets called anyway.


Yes, it needs some more stuff around it to make it useful.
Probably you also want the signal handler to raise an
exception and catch it somewhere rather than exiting
the process.

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


Re: File names with slashes [was Re: error in os.chdir]

2018-07-03 Thread Gregory Ewing

Mikhail V wrote:

  s= "\"s\""   ->
  s=  {"s"}


But now you need to find another way to represent set literals.

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


Re: PEP 526 - var annotations and the spirit of python

2018-07-03 Thread Gregory Ewing

Steven D'Aprano wrote:

"Jack of all trades, master of none" sort of thing?

Or are you thinking more along the lines of one of those guys who masters 
a new language in an hour and reaches expert level in a week?


I'm not talking about someone who hasn't mastered anything.
I'm talking about someone who has mastered the art of
programming in general. Such a person can learn enough
about an unfamiliar language to do something useful with
it in quite a short time.

why pay somebody to 
learn the language at full senior rates when there are millions of senior 
developers who already know the language?


If they're truly a seasoned programmer, you'll get your
money's worth out of them long before they've mastered
every nook and cranny of the language.

Whereas if you hire a total greenhorn who knows Java
on paper but has no practical programming experience,
you'll be paying them for quite a while before they're
doing you more good than harm.

If you can find someone who's both a seasoned developer
*and* experienced in the particular language required,
that's a bonus, but only a small one.

Also, it assumes you can find two people who are both
equally experienced, except that one knows Java and the
other doesn't.

My conjecture is that given two people, who have been
programming for the same length of time, one of which
knows a wide variety of languages other than Java, and
one that knows *only* Java, the one that knows multiple
languages will almost certainly be a better programmer,
and will be better value for money *even though* it
will take him a little bit of time to pick up Java.

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


Re: Multi-threading with a simple timer?

2018-07-02 Thread Gregory Ewing

David D wrote:

Is there a SIMPLE method that I can have a TIMER count down at a user input
prompt - if the user doesn't enter information within a 15 second period, it
times out.


import signal, sys

def timeout(*args):
print("Too late!")
sys.exit(0)

signal.signal(signal.SIGALRM, timeout)
signal.setitimer(signal.ITIMER_REAL, 15)
data = input("Enter something: ")
print("You entered: ", data)

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


Re: EXTERNAL: OSError: [Errno 48] Address already in use

2018-07-02 Thread Gregory Ewing

Marko Rauhamaa wrote:

Nevertheless, the later socket object cannot unilaterally take over a
socket using SO_REUSEADDR. The earlier socket object must have set the
same option previously.


I just did an experiment that suggests that's not the case.
I created a socket without SO_REUSEADDR, made a connection to
it, and killed it. Then I created another socket within the
timeout period with SO_REUSEADDR, and it succeeded.

This was on MacOSX -- it's possible that other systems
behave differently.

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


Re: PEP 526 - var annotations and the spirit of python

2018-07-02 Thread Gregory Ewing

Ian Kelly wrote:

Just because somebody knows a dozen languages
doesn't mean that they can come up with the correct algorithm,


That doesn't mean there's no correlation. Someone who is familiar
with a variety of languages is also very likely to be self-motivated
and have enough passion and curiosity to have acquired a broad and
deep knowledge of other aspects of the craft.


If your production system is built out of a dozen languages,
you may have a well-tuned system where each language was chosen for a
solid, specific reason; but you've also got a maintenance nightmare on
the day that the one programmer who actually understands all of it
decides to leave.


There are good reasons to restrict the number of languages used, but
it doesn't mean that language-specific job advertisements are the
best way to go about getting staff. The company doesn't really want
a "Java programmer" or whatever, they want a *good* programmer. A
truly good programmer will be able to learn about the language
being used on the job.

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


Re: File names with slashes [was Re: error in os.chdir]

2018-07-01 Thread Gregory Ewing

eryk sun wrote:

Python 2 raw strings are half-baked.


Obviously the "r" actually stand for "rare".

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


Re: Assignments to ps1

2018-07-01 Thread Gregory Ewing

Stefan Ram wrote:

from sys import ps1
ps1 = 'alpha'


>>> import sys
>>> sys.ps1 = "alpha"
alpha

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


Re: $s and %d in python

2018-06-30 Thread Gregory Ewing

Cameron Simpson wrote:
The variable my_height is an int, and for an int both these things are 
the same.


But note that 'd' and 's' can give different results when
other formatting options are present, e.g.

>>> "%05d" % 42
'00042'
>>> "%05s" % 42
'   42'

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


Re: EXTERNAL: OSError: [Errno 48] Address already in use

2018-06-30 Thread Gregory Ewing

Dan Stromberg wrote:

On Thu, Jun 28, 2018 at 10:30 PM, Marko Rauhamaa  wrote:


Well, the same security issue can be demonstrated without SO_REUSEADDR:

The security issue can be real but is not directly related with
SO_REUSEADDR.


Yes, it can.  It just takes longer.


I don't see how the address-reuse timeout can be a security
measure, because the process trying to take over the address
can easily circumvent it by setting SO_REUSEADDR.

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


Re: Should nested classes in an Enum be Enum members?

2018-06-29 Thread Gregory Ewing

Cameron Simpson wrote:
It tends to mean "weird", but perhaps a more nuanced phrasing might be 
unusual and strange, and usually connotes some degree of over complication.


When used in a derogatory way it means "excessively elaborate".
The Baroque period was characterised by extremely ornate
architecture, music, etc.

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


Re: Should nested classes in an Enum be Enum members?

2018-06-29 Thread Gregory Ewing

Ethan Furman wrote:
They are the list of dates in which US banks are closed for electronic 
business (funds transfers and things).


That sems like something that would be better specified in
a configuration file than hard-wired into the code, in case
the rules change.

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


  1   2   3   4   5   6   7   8   9   10   >