Re: Making Classes Subclassable

2016-07-04 Thread dieter
Lawrence D’Oliveiro  writes:

> Some of the classes in Qahirah, my Cairo binding 
>  I found handy to reuse elsewhere, for 
> example in my binding for Pixman . 
> Subclassing is easy, but then you need to ensure that operations inherited 
> from the superclass return instances of the right class. This means that 
> superclass methods must never refer directly to the class by name for 
> constructing new objects; they need to obtain the current class by more 
> indirect means.

--> "type(obj)" or "obj.__class__" (there are small differences)
give you the type/class of "obj".

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


Re: Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL]

2016-07-04 Thread dieter
"Owen Brandon"  writes:

> I have a query regarding the support of decompression for Unix compressed .Z 
> files in Python's gzip module. The gzip system utility supports this using 
> the '-d' switch, but the python module does not.

When I am right, then the "zipfile" module handles ".Z" compressed files.

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Lawrence D’Oliveiro
On Monday, July 4, 2016 at 6:08:51 PM UTC+12, Jussi Piitulainen wrote:
> Something could be done, but if the intention is to allow
> mathematical notation, it needs to be done with care.

Mathematics uses single-character variable names so that multiplication can be 
implicit.

An old, stillborn language design from the 1960s called CPL* had two syntaxes 
for variable names:
* a single lowercase letter, optionally followed by any number of primes “'”;
* an uppercase letter followed by letters or digits.

It also allowed implicit multiplication; single-letter identifiers could be run 
together without spaces, but multi-character ones needed to be delimited by 
spaces or non-identifier characters. E.g.

  Sqrt(bb - 4ac)
  Area ≡ Length Width

*It was never fully implemented, but a cut-down derivative named BCPL did get 
some use. Some researchers at Bell Labs took it as their starting point, first 
creating a language called “B”, then another one called “C” ... well, the rest 
is history.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Making Classes Subclassable

2016-07-04 Thread Lawrence D’Oliveiro
On Monday, July 4, 2016 at 7:58:07 PM UTC+12, dieter wrote:
> --> "type(obj)" or "obj.__class__" (there are small differences)
> give you the type/class of "obj".

When would it not be the same?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Marko Rauhamaa
Lawrence D’Oliveiro :

> Mathematics uses single-character variable names so that
> multiplication can be implicit.

I don't think anybody developed mathematical notation systematically.
Rather, over the centuries, various masters came up with personal
abbreviations and shorthand, which spread among admirers and students
through emulation. The resulting two-dimensional hodgepodge needs to be
supplemented by much natural-language handwaving. Rigorous treatment
needs to use a formal language, eg: http://us.metamath.org/mpeuni/evlslem2.html>.

Anyway, most programming has little use for mathematics. Thus, a
general-purpose programming language shouldn't bend over backwards to
placate that particular application domain.


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


ANN: Python Meeting Düsseldorf - 06.07.2016

2016-07-04 Thread eGenix Team: M.-A. Lemburg
[This announcement is in German since it targets a local user group
 meeting in Düsseldorf, Germany]



ANKÜNDIGUNG

  Python Meeting Düsseldorf

   http://pyddf.de/

Ein Treffen von Python Enthusiasten und Interessierten
 in ungezwungener Atmosphäre.

   Mittwoch, 06.07.2016, 18:15 Uhr
   Raum 1, 2.OG im Bürgerhaus Stadtteilzentrum Bilk
 Düsseldorfer Arcaden, Bachstr. 145, 40217 Düsseldorf

Diese Nachricht ist auch online verfügbar:
http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2016-07-06


NEUIGKEITEN

 * Bereits angemeldete Vorträge:

   Stefan Richthofer
"JyNI – Native CPython-Extensions in Jython"

   Marc-Andre Lemburg
"Stand-Alone Applikationen mit eGenix PyRun"

   Charlie Clark
"Eine kurze Einführung in SQLAlchemy: Was es ist und
wie man es benutzen kann"

   Jens Diemer
"PyLucid – ein Open Source CMS auf Django Basis"

   Weitere Vorträge können gerne noch angemeldet werden: [email protected]

 * Startzeit und Ort:

   Wir treffen uns um 18:15 Uhr im Bürgerhaus in den Düsseldorfer
   Arcaden.

   Das Bürgerhaus teilt sich den Eingang mit dem Schwimmbad und
   befindet sich an der Seite der Tiefgarageneinfahrt der Düsseldorfer
   Arcaden.

   Über dem Eingang steht ein großes "Schwimm' in Bilk" Logo. Hinter
   der Tür direkt links zu den zwei Aufzügen, dann in den 2. Stock
   hochfahren. Der Eingang zum Raum 1 liegt direkt links, wenn man aus
   dem Aufzug kommt.

   Google Street View: http://bit.ly/11sCfiw



EINLEITUNG

Das Python Meeting Düsseldorf ist eine regelmäßige Veranstaltung in
Düsseldorf, die sich an Python Begeisterte aus der Region wendet:

 * http://pyddf.de/

Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal,
auf dem wir die Vorträge nach den Meetings veröffentlichen:

 * http://www.youtube.com/pyddf/

Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld,
in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf:

 * http://www.egenix.com/
 * http://www.clark-consulting.eu/



PROGRAMM

Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space
und Lightning Talks, wobei die Gewitter bei uns auch schon mal
20 Minuten dauern können ;-).

Lightning Talks können vorher angemeldet werden, oder auch spontan
während des Treffens eingebracht werden. Ein Beamer mit XGA Auflösung
steht zur Verfügung.

Lightning Talk Anmeldung bitte formlos per EMail an [email protected]



KOSTENBETEILIGUNG

Das Python Meeting Düsseldorf wird von Python Nutzern für Python
Nutzer veranstaltet. Um die Kosten zumindest teilweise zu
refinanzieren, bitten wir die Teilnehmer um einen Beitrag in Höhe von
EUR 10,00 inkl. 19% Mwst, Schüler und Studenten zahlen EUR 5,00
inkl. 19% Mwst.

Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen.



ANMELDUNG

Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir
bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung
eingegangen. Es erleichtert uns allerdings die Planung.

Meeting Anmeldung bitte formlos per EMail an [email protected]



WEITERE INFORMATIONEN

Weitere Informationen finden Sie auf der Webseite des Meetings:

http://pyddf.de/

Mit freundlichen Grüßen,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Jul 04 2016)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...   http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...   http://zope.egenix.com/


::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
  http://www.malemburg.com/

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


Re: Creating a calculator

2016-07-04 Thread Pierre-Alain Dorange
DFS  wrote:

> 
> 2 lines?  Love it!
> 
> But apparently eval==evil.
> 
> http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
> 
> I bet you get hammered about it here on clp.

It was a software to be deploy, it was just for educational purpose.

-- 
Pierre-Alain Dorange   Moof 

Ce message est sous licence Creative Commons "by-nc-sa-2.0"

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread BartC

On 04/07/2016 03:30, Steven D'Aprano wrote:

On Mon, 4 Jul 2016 10:17 am, BartC wrote:


On 04/07/2016 01:00, Lawrence D’Oliveiro wrote:

On Monday, July 4, 2016 at 11:47:26 AM UTC+12, eryk sun wrote:

Python lacks a mechanism to add user-defined operators. (R has this
capability.) Maybe this feature could be added.


That would be neat. But remember, you would have to define the operator
precedence as well. So you could no longer use a recursive-descent
parser.


That wouldn't be a problem provided the new operator symbol and its
precedence is known at a compile time, and defined before use.


You're still having problems with the whole Python-as-a-dynamic-language
thing, aren't you? :-)


Well it isn't completely dynamic, not unless code only exists as a eval 
or exec argument string (and even there, any changes will only be seen 
on calling eval or exec again on the same string).


Most Pythons seem to pre-compile code before executing the result. That 
pre-compilation requires that operators and precedences are known in 
advance and the resulting instructions are then hard-coded before execution.



In full generality, you would want to be able to define unary prefix, unary
suffix and binary infix operators, and set their precedence and whether
they associate to the left or the right. That's probably a bit much to
expect.


No, that's all possible. Maybe that's even how some language 
implementations work, defining all the set of standard operators at the 
start.



But if we limit ourselves to the boring case of binary infix operators of a
single precedence and associtivity, there's a simple approach: the parser
can allow any unicode code point of category "Sm" as a legal operator, e.g.
x ∇ y. Pre-defined operators like + - * etc continue to call the same
dunder methods they already do, but anything else tries calling:

x.__oper__('∇', y)
y.__roper__('∇', x)

and if neither of those exist and return a result other than NotImplemented,
then finally raise a runtime TypeError('undefined operator ∇').


A simpler approach is to treat user-defined operators as aliases for 
functions:


def myadd(a,b):
return a+b

operator ∇:
   (myadd,2,+3)   # map to myadd, 2 operands, prio 3, LTR

x = y ∇ z

is then equivalent to:

x = myadd(y,z)

However you will usually want to be able overload the same operator for 
different operand types. That means mapping the operator to one of 
several methods. Maybe even allowing the operator to have either one or 
two operands.


Trickier but still doable I think.

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Jussi Piitulainen
Lawrence D’Oliveiro writes:

> On Monday, July 4, 2016 at 6:08:51 PM UTC+12, Jussi Piitulainen wrote:
>> Something could be done, but if the intention is to allow
>> mathematical notation, it needs to be done with care.
>
> Mathematics uses single-character variable names so that
> multiplication can be implicit.

Certainly on topic, though independent of Unicode. I was thinking of
different classes of operator symbols.

> An old, stillborn language design from the 1960s called CPL* had two
> syntaxes for variable names:
> * a single lowercase letter, optionally followed by any number of primes “'”;
> * an uppercase letter followed by letters or digits.
>
> It also allowed implicit multiplication; single-letter identifiers
> could be run together without spaces, but multi-character ones needed
> to be delimited by spaces or non-identifier characters. E.g.
>
>   Sqrt(bb - 4ac)
>   Area ≡ Length Width
>
> *It was never fully implemented, but a cut-down derivative named BCPL
> did get some use. Some researchers at Bell Labs took it as their
> starting point, first creating a language called “B”, then another one
> called “C” ... well, the rest is history. 

There's been at least D, F, J, K (APL family), R, S (_before_ R), T (a
Lisp), X (the window system), Z (some specification language).

Any single-letter non-ASCII names yet? Spelled-out like Lambda and Omega
don't count.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Special attributes added to classes on creation

2016-07-04 Thread Xiang Zhang
On Monday, July 4, 2016 at 12:02:41 AM UTC+8, Steven D'Aprano wrote:
> I have some code which can preprocess (using a metaclass) or postprocess
> (using a decorator) a class:
> 
> @process
> class K:
> pass
> 
> 
> class K(metaclass=process):
> pass
> 
> 
> Both should give the same result, but I have found that the results are
> slightly different because the dict passed to process as a metaclass is
> different from the the class dict seen by the decorator. I can demonstrate
> the difference in Python 3.6 by using this metaclass/decorator:
> 
> class process(type):
> def __new__(meta, *args):
> if len(args) == 1:
> # decorator usage
> cls = args[0]
> d = cls.__dict__
> elif len(args) == 3:
> # metaclass usage
> name, bases, d = args
> cls = super().__new__(meta, *args)
> print(sorted(d.keys()))
> return cls
> 
> 
> If I then try it against two identical (apart from their names) classes, I
> get these results:
> 
> 
> py> @process
> ... class K:
> ... x = 1
> ...
> ['__dict__', '__doc__', '__module__', '__weakref__', 'x']
> py> class Q(metaclass=process):
> ... x = 1
> ...
> ['__module__', '__qualname__', 'x']
> 
> 
> 
> Now if I check the newly created Q, I see the same keys K has:
> 
> py> sorted(Q.__dict__.keys())
> ['__dict__', '__doc__', '__module__', '__weakref__', 'x']
> 
> 
> Is there any documentation for exactly what keys are added to classes when? 
> 
> 
> 
> 
> -- 
> Steven
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

eryk sun has a very good explanation. I want to add two points:

1. __qualname__ though passed in class creation, but it won't appear in the 
class.__dict__ since it is deliberately deleted from __dict__ in type_new.

2. __dict__ and __weakref__ are possible to be added even when there is not 
__slots__. __dict__ can be added when the base class's dictoffset == 0 and 
__weakref__ can be added when the base class's weakrefoffset == 0 && 
tp_itemsize == 0. An example is:

In [2]: class T(int):
   ...: pass
   ...: 

In [3]: T.__dict__
Out[3]: mappingproxy({'__module__': '__main__', '__dict__': , '__doc__': None})

I think this is a nice design in attribute searching.

BTW, I think this is a implementation detail. If you rely on it, it may easily 
break in the future.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread BartC

On 04/07/2016 02:15, Lawrence D’Oliveiro wrote:

On Monday, July 4, 2016 at 12:40:14 PM UTC+12, BartC wrote:

The structure of such a parser doesn't need to exactly match the grammar
with a dedicated block of code for each operator precedence. It can be
table-driven so that an operator precedence value is just an attribute.


Of course. But that’s not a recursive-descent parser any more.



All the parsers I write work the same way. If I can't describe them as 
recursive descent, then I don't know what they are.


This is just recognising that a bunch of specialised functions that are 
very similar can be reduced to one or two more generalised ones.


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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Jussi Piitulainen
BartC writes:

> A simpler approach is to treat user-defined operators as aliases for
> functions:
>
> def myadd(a,b):
>   return a+b
>
> operator ∇:
>(myadd,2,+3)   # map to myadd, 2 operands, prio 3, LTR
>
> x = y ∇ z
>
> is then equivalent to:
>
> x = myadd(y,z)
>
> However you will usually want to be able overload the same operator
> for different operand types. That means mapping the operator to one of
> several methods. Maybe even allowing the operator to have either one
> or two operands.
>
> Trickier but still doable I think.

Julia does something like that. The parser knows a number of symbols
that it treats as operators, some of them are aliases for ASCII names,
all operators correspond to generic functions, and the programmer can
add methods for their own types (or for pre-existing types) to these
functions.

Prolog opens its precedence table for the programmer. I don't know if
there's been any Unicode activity, or any activity, in recent years, but
there are actually two different issues here: what is parsed as an
identifier, and what identifiers are treated as operator symbols (with
what precedence and associativity).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a calculator

2016-07-04 Thread Antoon Pardon
Op 01-07-16 om 15:52 schreef Steven D'Aprano:
> On Fri, 1 Jul 2016 10:25 pm, Christopher Reimer wrote:
>
>> For my BASIC interpreter, each line of BASIC is broken this way into
>> tokens.
> [...]
>> By using * to unpack the split line, my program no longer crashes and no
>> try/except block is needed to work around the crash. A later line of code
>> will test the expression, ignore if empty or run regex if full.
> I wish you wouldn't describe this as "crash".

I wish you wouldn't mix semantic levels.

>
> The Python interpreter should never crash. That would be a segmentation
> fault, and that is considered to be a very serious bug.

But in that case your computer didn't crash. That would be a your computer
freezing, or rebooting.

>
> But *raising an exception* is another story. Raising exceptions is not a
> crash, it is the interpreter working as expected. This statement:

A segment violation is not a crash either, your computer/os will just
carry on.

>
> line_number, keyword, expr = "20 END".split(' ', 2)
>
> is SUPPOSED to raise an exception, if it didn't, the interpreter would be
> broken. To call that a "crash" is horribly misleading.

Supposed by whom? The line may be supposed to raise an exception by
the languager designer, that doesn't mean the programmer meant to
write an instruction that would raise an exception. So the programmer
can correctly assert the line was not supposed to raise an exception.

-- 
Antoon.

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


Spot the bug: getoptquestion.py

2016-07-04 Thread Oscar

Is this:

a) a bug in getopt.getopt
b) a bug in my code
c) a great way to keep me busy for a while
d) all of the above?


#!/usr/bin/python

from __future__ import print_function
from getopt import getopt, GetoptError
import sys

try:
opts, args = getopt(sys.argv[1:], 'b', ['bug '])

except GetoptError as err:
print('Caught:', repr(err))

else:
if opts:
for opt, arg in opts:

if opt in ('-b', '--bug'):
print ("Ceci n'est pas un bug!")
else:
#print ('Missed option: "{0}"'.format(opt))
print ('Missed option:', opt)
else:
print('Usage:', sys.argv[0],'-b|--bug') 


-- 
[J|O|R] <- .signature.gz
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-04 Thread jmp

On 07/01/2016 04:13 PM, Steven D'Aprano wrote:

But classes are not like the others: they must be instantiated before they
can be used, and they are more than just a mere namespace grouping related
entities. Classes support inheritance. Classes should be used for "is-a"
relationships, not "has-a" relationships. Although classes (and instances)
are namespaces, they provide fundamentally different kind of behaviour than
modules and packages.


A namespace would not hurt but I really don't get why you don't consider 
classes a valid and rather helpful namespace.


1/ classes do not have to be instantiated.
2/ the fact that classes are more than a namespace is not an argument. 
Almost any object in python is able to do more than what you are 
actually using.
3/ Classes are used as much as 'is-a' than 'has-a', class instances 
*have* a state usually described by attributes
4/ "Although classes (and instances) are namespaces, ". You seem to 
contradict yourself. It was probably a rhetorical construct but it's 
rather confusing.


jm

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


Re: Spot the bug: getoptquestion.py

2016-07-04 Thread Chris Angelico
On Mon, Jul 4, 2016 at 9:24 PM, Oscar  wrote:
> Is this:
>
> a) a bug in getopt.getopt
> b) a bug in my code
> c) a great way to keep me busy for a while
> d) all of the above?
>
>
> #!/usr/bin/python
>
> from __future__ import print_function
> from getopt import getopt, GetoptError
> import sys
>
> try:
> opts, args = getopt(sys.argv[1:], 'b', ['bug '])
>
> except GetoptError as err:
> print('Caught:', repr(err))
>
> else:
> if opts:
> for opt, arg in opts:
>
> if opt in ('-b', '--bug'):
> print ("Ceci n'est pas un bug!")
> else:
> #print ('Missed option: "{0}"'.format(opt))
> print ('Missed option:', opt)
> else:
> print('Usage:', sys.argv[0],'-b|--bug')

Well, first thing I'd do is wipe out your try/except. It's not really
achieving much (you effectively catch an exception to print it to the
console and terminate).

But then what I'm seeing is that you have 'bug ' (with a trailing
space) in your list of long options, so getopt returns '--bug ' as a
long option. Is that a bug? I dunno. Why do you have the trailing
space? In any case, it's pretty easy to see if you change one line of
your code to:

print('Missed option: %r' % opt)

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


Re: Namespaces are one honking great idea

2016-07-04 Thread Chris Angelico
On Mon, Jul 4, 2016 at 9:23 PM, jmp  wrote:
> On 07/01/2016 04:13 PM, Steven D'Aprano wrote:
>>
>> But classes are not like the others: they must be instantiated before they
>> can be used, and they are more than just a mere namespace grouping related
>> entities. Classes support inheritance. Classes should be used for "is-a"
>> relationships, not "has-a" relationships. Although classes (and instances)
>> are namespaces, they provide fundamentally different kind of behaviour
>> than
>> modules and packages.
>
>
> A namespace would not hurt but I really don't get why you don't consider
> classes a valid and rather helpful namespace.
>
> 1/ classes do not have to be instantiated.
> 2/ the fact that classes are more than a namespace is not an argument.
> Almost any object in python is able to do more than what you are actually
> using.
> 3/ Classes are used as much as 'is-a' than 'has-a', class instances *have* a
> state usually described by attributes
> 4/ "Although classes (and instances) are namespaces, ". You seem to
> contradict yourself. It was probably a rhetorical construct but it's rather
> confusing.

Functions within the namespace can't call other functions within the
same namespace using unqualified names. This was a stated requirement.

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Rustom Mody
On Monday, July 4, 2016 at 3:56:43 PM UTC+5:30, BartC wrote:
> On 04/07/2016 02:15, Lawrence D’Oliveiro wrote:
> > On Monday, July 4, 2016 at 12:40:14 PM UTC+12, BartC wrote:
> >> The structure of such a parser doesn't need to exactly match the grammar
> >> with a dedicated block of code for each operator precedence. It can be
> >> table-driven so that an operator precedence value is just an attribute.
> >
> > Of course. But that’s not a recursive-descent parser any more.
> >
> 
> All the parsers I write work the same way. If I can't describe them as 
> recursive descent, then I don't know what they are.
> 
> This is just recognising that a bunch of specialised functions that are 
> very similar can be reduced to one or two more generalised ones.

In gofer (likewise Haskell) one can concoct any operator and give it a 
precedence
and associativity -- l,r,non

Internals of Haskell I do not know, but of gofer I can say the following:

Implementation is in C.
Uses yacc to parse all operators left-assoc, same precedence
Then post-processes the tree with an elegant little shift-reduce parser
based on specified precedences and associativities.

I sometimes teach this to my kids as an example of how 
FP-style comments can clarify arcane imperative code:

Mark Jones (gofer author) original version + My version made executable
http://blog.languager.org/2016/07/a-little-functional-parser.html
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Spot the bug: getoptquestion.py

2016-07-04 Thread Oscar
In article ,
Chris Angelico   wrote:
>On Mon, Jul 4, 2016 at 9:24 PM, Oscar  wrote:
>> Is this:
>>
>> a) a bug in getopt.getopt
>> b) a bug in my code
>> c) a great way to keep me busy for a while
>> d) all of the above?
>>
>>
>> #!/usr/bin/python
>>
>> from __future__ import print_function
>> from getopt import getopt, GetoptError
>> import sys
>>
>> try:
>> opts, args = getopt(sys.argv[1:], 'b', ['bug '])
>>
>> except GetoptError as err:
>> print('Caught:', repr(err))
>>
>> else:
>> if opts:
>> for opt, arg in opts:
>>
>> if opt in ('-b', '--bug'):
>> print ("Ceci n'est pas un bug!")
>> else:
>> #print ('Missed option: "{0}"'.format(opt))
>> print ('Missed option:', opt)
>> else:
>> print('Usage:', sys.argv[0],'-b|--bug')
>
>Well, first thing I'd do is wipe out your try/except. It's not really
>achieving much (you effectively catch an exception to print it to the
>console and terminate).

It does something: it shows that --bug on my commandline did not throw
an GetoptError. I could post the whole 400 line script, but decided to
cut it down to a demonstration of a subtle bug that i introduced in my
script. So far, answers b) and c) certainly do apply.


>But then what I'm seeing is that you have 'bug ' (with a trailing
>space) in your list of long options, so getopt returns '--bug ' as a
>long option.

You found it much faster than I did! ;-)

As i learned now, --b and --bu will also match '--bug ', as they are not
ambigous. So, of course '--bug' also returns '--bug ' in opts.

But it took me quite a while before I found my logic wasn't working
further down the script, just because I somehow introduced a space
character somewhere where it shouldn't have been.


> Is that a bug? I dunno. Why do you have the trailing
>space?

Because I'm stupid. It should not have been there at all. I've been
readjusting and reformatting my long 'getopt' line all day long and
somewhere my thumb must have hit my spacebar when I wasn't paying
attention. So a hard-to-find bug (for me at least) was introduced.

Now I also did not spot the trailing space in the loop where I was
evaluating the options when I added some debug statements. This sure 
got me scratching my head. The option is there, why doesn't my code do
what it's supposed to do? I sure was looking in the wrong place. I
better use repr() for debugging purposes next time. Thanks for the tip.

But is this not at least a bit unexpected behaviour from getopt? On one
hand, if I want to have trailing spaces in my longoptions, why not just
play along and allow them? On the other hand, a space is a delimiter on
the commandline. Does it make sense to allow it as a parameter to
getopt()? And if getopt would silently strip it, would that be a bug?

I agree that it's hard to debate wheter it is a bug, but I wanted to
share this experience anyway... ;-)


> In any case, it's pretty easy to see if you change one line of
>your code to:
>print('Missed option: %r' % opt)

Or uncomment my hint in the OP. But repr() is even better indeed.
-- 
[J|O|R] <- .signature.gz
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Ned Batchelder
On Monday, July 4, 2016 at 6:05:20 AM UTC-4, BartC wrote:
> On 04/07/2016 03:30, Steven D'Aprano wrote:
> > On Mon, 4 Jul 2016 10:17 am, BartC wrote:
> >
> >> On 04/07/2016 01:00, Lawrence D’Oliveiro wrote:
> >>> On Monday, July 4, 2016 at 11:47:26 AM UTC+12, eryk sun wrote:
>  Python lacks a mechanism to add user-defined operators. (R has this
>  capability.) Maybe this feature could be added.
> >>>
> >>> That would be neat. But remember, you would have to define the operator
> >>> precedence as well. So you could no longer use a recursive-descent
> >>> parser.
> >>
> >> That wouldn't be a problem provided the new operator symbol and its
> >> precedence is known at a compile time, and defined before use.
> >
> > You're still having problems with the whole Python-as-a-dynamic-language
> > thing, aren't you? :-)
> 
> Well it isn't completely dynamic, not unless code only exists as a eval 
> or exec argument string (and even there, any changes will only be seen 
> on calling eval or exec again on the same string).
> 
> Most Pythons seem to pre-compile code before executing the result. That 
> pre-compilation requires that operators and precedences are known in 
> advance and the resulting instructions are then hard-coded before execution.

This is the key but subtle point that all the discussion of parser mechanics
are missing: Python today needs no information from imported modules in
order to compile a file.  When the compiler encounters "import xyzzy" in
a file, it doesn't have to do anything to find or read xyzzy.py at compile
time.

If operators can be invented, they will only be useful if they can be
created in modules which you then import and use.  But that would mean that
imported files would have to be found and read during compilation, not
during execution as they are now.

This is a huge change.

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


Re: Spot the bug: getoptquestion.py

2016-07-04 Thread Chris Angelico
On Mon, Jul 4, 2016 at 10:38 PM, Oscar  wrote:
> But is this not at least a bit unexpected behaviour from getopt? On one
> hand, if I want to have trailing spaces in my longoptions, why not just
> play along and allow them? On the other hand, a space is a delimiter on
> the commandline. Does it make sense to allow it as a parameter to
> getopt()? And if getopt would silently strip it, would that be a bug?
>

This is really the crux of the matter. Honestly, I've no idea. The
getopt module is designed to match the C getopt function, which I've
never used; for my command-line parsing, I use argparse instead
(usually via some wrapper that cuts down the duplication, like clize).

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


EuroPython 2016: Please configure your tickets

2016-07-04 Thread M.-A. Lemburg
The EuroPython website supports buying tickets for other people
(friends, colleagues, etc.). As a result, it is necessary to assign
the tickets you buy to either yourself or someone else. The assignment
process is explained below.


Please tell us your preferences
---

The reason we’re interested in you applying this configuration as soon
as possible, is that the tickets include a number of preferences which
we need to know about in order to properly prepare the conference.

When assigning tickets you will fill some fields, telling us your
t-shirt size and cut (women or men style) and your diet
preferences. If you don’t provide this information, we cannot assure
we’ll have the right t-shirt available for you. Likewise, if you are
vegetarian, it is important to mark this in the preferences, so that
we can order enough vegetarian food.


How to assign tickets to attendees
--

First you need to log in and go to your profile and, if you already
bought your tickets, you will see something similar to this. Click on
"View your tickets".

After you have navigated to the tickets, we need you to assign the
ticket: simply hover over the ticket and you will see two
options. Please select, if the ticket is for you or for someone else.

Remember: Before assigning the ticket the other persons, these must be
registered on the website. Otherwise, the assignment won’t work.

If you have assigned the tickets to someone else, please let them
know. The system will send out automatic emails, but it’s safer to
send a separate email so that the information doesn’t get lost in a
spam filter.


How to edit the fields of the tickets
-

After assigning the ticket, each attendee will need to fill out the
ticket preferences using his/her profile page (don’t forget to click
save to store the settings).

Some additional help for the preference form:

 * Tagline: This line will appear after you name. Be original!

 * Diet: Omnivorous, Vegetarian or Other (we’ll try to provide food
   for other diets as well)

 * Python experience: Whats your experience level with Python? You can
   also enter “no comment”, if you prefer not to make this information
   public.

 * Dates: Which days do you plan to attend. This is not binding in any
   way, it just helps us to better prepare for the conference.


With gravitational regards,
--
EuroPython 2016 Team
http://ep2016.europython.eu/
http://www.europython-society.org/


PS: Please forward or retweet to help us reach all interested parties:
https://twitter.com/europython/status/749960553280528384
Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL]

2016-07-04 Thread Robert Kern

On 2016-07-04 09:00, dieter wrote:

"Owen Brandon"  writes:


I have a query regarding the support of decompression for Unix compressed .Z 
files in Python's gzip module. The gzip system utility supports this using the 
'-d' switch, but the python module does not.


When I am right, then the "zipfile" module handles ".Z" compressed files.


No, that handles PKZIP .zip files. There are third-party modules that handle the 
.Z format, but shelling out to external programs may still be preferable:


  https://github.com/umeat/unlzw

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread BartC

On 04/07/2016 13:47, Ned Batchelder wrote:

On Monday, July 4, 2016 at 6:05:20 AM UTC-4, BartC wrote:

On 04/07/2016 03:30, Steven D'Aprano wrote:



You're still having problems with the whole Python-as-a-dynamic-language
thing, aren't you? :-)



Most Pythons seem to pre-compile code before executing the result. That
pre-compilation requires that operators and precedences are known in
advance and the resulting instructions are then hard-coded before execution.


This is the key but subtle point that all the discussion of parser mechanics
are missing: Python today needs no information from imported modules in
order to compile a file.  When the compiler encounters "import xyzzy" in
a file, it doesn't have to do anything to find or read xyzzy.py at compile
time.


Yeah, there's that small detail. Anything affecting how source is to be 
parsed needs to known in advance.



If operators can be invented, they will only be useful if they can be
created in modules which you then import and use.  But that would mean that
imported files would have to be found and read during compilation, not
during execution as they are now.

This is a huge change.


I've used a kind of 'weak' import scheme elsewhere, corresponding to C's 
'#include'.


Then the textual contents of that 'imported' module are read by the 
compiler, and treated as though they occurred in this module. No new 
namespace is created.


I think that could work in Python provided whatever is defined can 
tolerate having copies redefined in each module that includes the same 
file. Anything that is defined once and is never assigned to nor 
modified for example.


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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Ned Batchelder
On Monday, July 4, 2016 at 10:36:54 AM UTC-4, BartC wrote:
> On 04/07/2016 13:47, Ned Batchelder wrote:
> > On Monday, July 4, 2016 at 6:05:20 AM UTC-4, BartC wrote:
> >> On 04/07/2016 03:30, Steven D'Aprano wrote:
> 
> >>> You're still having problems with the whole Python-as-a-dynamic-language
> >>> thing, aren't you? :-)
> 
> >> Most Pythons seem to pre-compile code before executing the result. That
> >> pre-compilation requires that operators and precedences are known in
> >> advance and the resulting instructions are then hard-coded before 
> >> execution.
> >
> > This is the key but subtle point that all the discussion of parser mechanics
> > are missing: Python today needs no information from imported modules in
> > order to compile a file.  When the compiler encounters "import xyzzy" in
> > a file, it doesn't have to do anything to find or read xyzzy.py at compile
> > time.
> 
> Yeah, there's that small detail. Anything affecting how source is to be 
> parsed needs to known in advance.
> 
> > If operators can be invented, they will only be useful if they can be
> > created in modules which you then import and use.  But that would mean that
> > imported files would have to be found and read during compilation, not
> > during execution as they are now.
> >
> > This is a huge change.
> 
> I've used a kind of 'weak' import scheme elsewhere, corresponding to C's 
> '#include'.
> 
> Then the textual contents of that 'imported' module are read by the 
> compiler, and treated as though they occurred in this module. No new 
> namespace is created.
> 
> I think that could work in Python provided whatever is defined can 
> tolerate having copies redefined in each module that includes the same 
> file. Anything that is defined once and is never assigned to nor 
> modified for example.

You are hand-waving over huge details of semantics that are very important
in Python.  For example, it is very important not to have copies of
classes.  Importing a module must produce the same module object
everywhere it is imported, and the classes defined in the module must
be defined only once.

This is what makes catching exceptions work (because it is based on an
exception being an instance of a particular class), and what makes
class attributes shared among all the instances of the class.

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


file.seek() and file.tell() look inconsistent to me

2016-07-04 Thread Marco Buttu

Hi all,

if I open a file in text mode, do you know why file.seek() returns the 
number of bytes, and file.tell() takes the number of bytes? I was 
expecting the number of characters, like write() does:


>>> f = open('myfile', 'w')
>>> f.write('aè')
2

It seems to me not consistent, and maybe could also be error prone:

>>> f.seek(2)
2
>>> f.write('c')
1
>>> f.close()
>>> open('myfile').read()
   ...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3...


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


Re: Namespaces are one honking great idea

2016-07-04 Thread jmp

On 07/04/2016 01:37 PM, Chris Angelico wrote:

On Mon, Jul 4, 2016 at 9:23 PM, jmp  wrote:

On 07/01/2016 04:13 PM, Steven D'Aprano wrote:


But classes are not like the others: they must be instantiated before they
can be used, and they are more than just a mere namespace grouping related
entities. Classes support inheritance. Classes should be used for "is-a"
relationships, not "has-a" relationships. Although classes (and instances)
are namespaces, they provide fundamentally different kind of behaviour
than
modules and packages.



A namespace would not hurt but I really don't get why you don't consider
classes a valid and rather helpful namespace.

1/ classes do not have to be instantiated.
2/ the fact that classes are more than a namespace is not an argument.
Almost any object in python is able to do more than what you are actually
using.
3/ Classes are used as much as 'is-a' than 'has-a', class instances *have* a
state usually described by attributes
4/ "Although classes (and instances) are namespaces, ". You seem to
contradict yourself. It was probably a rhetorical construct but it's rather
confusing.


Functions within the namespace can't call other functions within the
same namespace using unqualified names. This was a stated requirement.

ChrisA



Ho, I missed that one.

But if it's the only missing requirement, wouldn't be like stating that 
python instances are not instances because methods cannot call other 
methods without "self."ed qualified name ? We like explicit qualified 
stuff in python right ? ("explicit is better than implicit")


jm



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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread BartC

On 04/07/2016 15:46, Ned Batchelder wrote:

On Monday, July 4, 2016 at 10:36:54 AM UTC-4, BartC wrote:

On 04/07/2016 13:47, Ned Batchelder wrote:



This is a huge change.


I've used a kind of 'weak' import scheme elsewhere, corresponding to C's
'#include'.



I think that could work in Python provided whatever is defined can
tolerate having copies redefined in each module that includes the same
file. Anything that is defined once and is never assigned to nor
modified for example.


You are hand-waving over huge details of semantics that are very important
in Python.  For example, it is very important not to have copies of
classes.  Importing a module must produce the same module object
everywhere it is imported, and the classes defined in the module must
be defined only once.


So that would be something that doesn't tolerate copies.

But I think that a bigger change for Python wouldn't be new ways of 
doing imports, but the concept of having a user-defined anything that is 
a constant at compile-time. And not part of a conditional statement either.


Usually anything that is defined can be changed at run-time so that the 
compiler can never assume anything.


--
Bartc

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


Structure of program development

2016-07-04 Thread Michael Smolen
Folks:

I am new to this programming adventure. I've gotten past the introductory 
chapters in 'How to..." books and now want to start developing a much more 
complicated program that I will use repeated for different applications. When I 
worked in Perl there was an option to write a program in a text editor, save 
it, and then run in with Perl. Is such a thing possible in Python? If not, how 
do I develop a 500+ lines of code?

A second question of the basic design. If I write a program, can I move it to a 
computer that is without any Python software, or does that machine have to 
download the Python software? Does Python products contain all parts of a 
developed program or is it a series of 'call' statements?

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


Re: Well, I finally ran into a Python Unicode problem, sort of

2016-07-04 Thread Marko Rauhamaa
BartC :
> Usually anything that is defined can be changed at run-time so that the
> compiler can never assume anything.

The compiler can't assume anything permanent, but it could heuristically
make excellent guesses at runtime. It needs to verify its guesses at the
boundaries of compiled code and gradually keep expanding the boundaries.
If the guesses end up being wrong, it has to correct its assumptions and
recompile the relevant parts of the code.


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


Re: Structure of program development

2016-07-04 Thread Chris Warrick
On 4 July 2016 at 18:07, Michael Smolen <[email protected]> wrote:
> Folks:
>
> I am new to this programming adventure. I've gotten past the introductory 
> chapters in 'How to..." books and now want to start developing a much more 
> complicated program that I will use repeated for different applications. When 
> I worked in Perl there was an option to write a program in a text editor, 
> save it, and then run in with Perl. Is such a thing possible in Python? If 
> not, how do I develop a 500+ lines of code?

Yes, the same way it works in Perl. Use the .py file extension and run
the `python` interpreter from command line, or use an IDE that would
help you with that.

> A second question of the basic design. If I write a program, can I move it to 
> a computer that is without any Python software, or does that machine have to 
> download the Python software? Does Python products contain all parts of a 
> developed program or is it a series of 'call' statements?

You must either install a Python interpreter on that machine, or
distribute one with your program.

-- 
Chris Warrick 
PGP: 5EAAEA16
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Structure of program development

2016-07-04 Thread BartC

On 04/07/2016 17:07, Michael Smolen wrote:

Folks:

I am new to this programming adventure. I've gotten past the introductory chapters 
in 'How to..." books and now want to start developing a much more complicated 
program that I will use repeated for different applications. When I worked in Perl 
there was an option to write a program in a text editor, save it, and then run in 
with Perl. Is such a thing possible in Python? If not, how do I develop a 500+ lines 
of code?

A second question of the basic design. If I write a program, can I move it to a 
computer that is without any Python software, or does that machine have to 
download the Python software? Does Python products contain all parts of a 
developed program or is it a series of 'call' statements?


It can work the same way. Write the 500-line program in, say, prog.py 
using any text editor.


Then run it using:

python prog.py


--
Bartc

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


Re: Structure of program development

2016-07-04 Thread Alan Evangelista



I am new to this programming adventure. I've gotten past the introductory chapters 
in 'How to..." books and now want to start developing a much more complicated 
program that I will use repeated for different applications. When I worked in Perl 
there was an option to write a program in a text editor, save it, and then run in 
with Perl. Is such a thing possible in Python? If not, how do I develop a 500+ lines 
of code?


Yes. You can do it for every programming language I know, otherwise development 
would be impossible.


A second question of the basic design. If I write a program, can I move it to a 
computer that is without any Python software, or does that machine have to 
download the Python software? Does Python products contain all parts of a 
developed program or is it a series of 'call' statements?


The target system must have the Python interpreter and standard library, which are always installed 
together.


A software developed in Python must contain the method calls to the Python standard library, 3rd 
party libraries
and/or custom code. It may or not contain the Python runtime environment (interpreter and std 
library). In Linux,
for instance, it is standard to not include dependencies (eg Python runtime environment) in an 
application, but

reuse the one already installed in the target system.


Regards

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


Re: Structure of program development

2016-07-04 Thread Jussi Piitulainen
Michael Smolen writes:

> Folks:
>
> I am new to this programming adventure. I've gotten past the
> introductory chapters in 'How to..." books and now want to start
> developing a much more complicated program that I will use repeated
> for different applications. When I worked in Perl there was an option
> to write a program in a text editor, save it, and then run in with
> Perl. Is such a thing possible in Python? If not, how do I develop a
> 500+ lines of code?

This is indeed possible.

If you can find your way to a command line of your operating system and
launch a Python interactive session by typing "python" or "python3" to
the command prompt and pressing the enter key, then you have access to
the program that can execute your Python code that is in the file that
you created with a text editor. All you have to do is, give the name of
your file as an argument to python or python3. You get a stack trace,
fix your program, and try again.

Some text editors understand Python syntax, or can be set to understand
Python syntax, just like they support Perl and many other languages.
This is merely a convenience. Python need not know what you used to
write the code.

> A second question of the basic design. If I write a program, can I
> move it to a computer that is without any Python software, or does
> that machine have to download the Python software? Does Python
> products contain all parts of a developed program or is it a series of
> 'call' statements?

The straightforward thing is to have Python installed.

Beyond that, I don't have personal experience, so I won't offer any
advice. Others will know.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: file.seek() and file.tell() look inconsistent to me

2016-07-04 Thread MRAB

On 2016-07-04 16:48, Marco Buttu wrote:

Hi all,

if I open a file in text mode, do you know why file.seek() returns the
number of bytes, and file.tell() takes the number of bytes? I was
expecting the number of characters, like write() does:

 >>> f = open('myfile', 'w')
 >>> f.write('aè')
2

It seems to me not consistent, and maybe could also be error prone:

 >>> f.seek(2)
2
 >>> f.write('c')
1
 >>> f.close()
 >>> open('myfile').read()
...
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3...


Some encodings, such as UTF-8, use a variable number of bytes per 
character (codepoint, actually), so in order to seek to a certain 
character position you would need to read from a known position, e.g. 
the start of the file, until you reached the desired place.


Most of the time you're seeking to a position that was previously 
returned by tell anyway.


I think it's a case of "practicality beats purity".

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


Need help compiling Python-devel

2016-07-04 Thread TM
Hi,

I have successfully compiled Python-2.7.12 on AIX 6.1 TL09, using steps
below. However I need the python-devel library/headers. How do I compile
Python, so that I can use this?

# ./configure --with-gcc="gcc" --with-cxx="gcc" --disable-ipv6
# make

Any help is greatly appreciated.

Thanks,
Tony
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Structure of program development

2016-07-04 Thread BartC

On 04/07/2016 17:55, Chris Warrick wrote:


A second question of the basic design. If I write a program, can I move it to a 
computer that is without any Python software, or does that machine have to 
download the Python software? Does Python products contain all parts of a 
developed program or is it a series of 'call' statements?


You must either install a Python interpreter on that machine, or
distribute one with your program.


If only it was that simple. My Windows Python 3.4 installation comprises 
5200 files over 1300 directories, totalling 100MB.


Other Pythons are a bit smaller, so I don't know what extras that 
includes. Which is part of the problem: you have to employ yet more 
extras to figure out the files needed to create a tidy distribution.


However the Linuxes I've seen tend to have Python pre-installed. Then 
you can just supply the .py files of the application.



--
Bartc


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


Re: file.seek() and file.tell() look inconsistent to me

2016-07-04 Thread Christian Heimes
On 2016-07-04 17:48, Marco Buttu wrote:
> Hi all,
> 
> if I open a file in text mode, do you know why file.seek() returns the
> number of bytes, and file.tell() takes the number of bytes? I was
> expecting the number of characters, like write() does:

Your expectations are not correct. tell() and seek() of a file in binary
mode return the current position of the file descriptor. For a file in
text mode, tell() and seek() use a opaque number [1]. The number
reflects the internal state of the text IO object. You can't draw any
conclusion from it. You are only allowed to seek to offsets which you
have acquired by tell(), too.


[1] https://docs.python.org/3/library/io.html#io.TextIOBase.tell

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


Re: Namespaces are one honking great idea

2016-07-04 Thread Lawrence D’Oliveiro
On Monday, July 4, 2016 at 11:37:44 PM UTC+12, Chris Angelico wrote:

> Functions within the namespace can't call other functions within the
> same namespace using unqualified names. This was a stated requirement.

Doesn’t my @namespace decorator provide that?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-04 Thread Lawrence D’Oliveiro
On Tuesday, July 5, 2016 at 10:10:04 AM UTC+12, I wrote:
>
> On Monday, July 4, 2016 at 11:37:44 PM UTC+12, Chris Angelico wrote:
> 
> > Functions within the namespace can't call other functions within the
> > same namespace using unqualified names. This was a stated requirement.
> 
> Doesn’t my @namespace decorator provide that?

No it doesn’t.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Running yum/apt-get from a virtualenv

2016-07-04 Thread Matt Wheeler
On Fri, 24 Jun 2016, 03:32 Tiglath Suriol,  wrote:

> Let us say that I install PostgreSQL from an activated virtualenv using
> yum or apt-get, will PostgrSQL be local or global?
>

Global

I understand that virtualenv isolates the Python environment only, so I
> surmise that it will make no difference installing with yum/apt-get inside
> or outside the virtualenv.
>

That is correct. The way the virtualenv works is by adding a new path (the
virtualenv bin dir) to the beginning of $PATH. That means that programs
which are in your virtualenv (python, pip, entry points to any packages you
have installed) will override system versions, because they come first. Of
course that won't apply to yum,apt,etc.

But that would not be the case with say Psycopg2 which would be isolated in
> the virtualenv, because it is a Python module.  Is that right?
>

Yes

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


RE: Gzip module does not support Unix compressed .Z files [SEC=UNOFFICIAL]

2016-07-04 Thread Owen Brandon
That's actually the module that I wrote for this purpose (adapted Mark Adler's 
C code) - I haven't optimised it very much.

Brandon Owen 
GNSS Network Operator  |  Geodesy and Seismic Monitoring Group
Community Safety and Earth Monitoring Division  |  GEOSCIENCE AUSTRALIA

Phone:  +61 2 6249 9192    Fax:  +61 2 6249 
Email:  [email protected]    Web:  www.ga.gov.au
Cnr Jerrabomberra Avenue and Hindmarsh Drive Symonston ACT
GPO Box 378 Canberra ACT 2601 Australia
Applying geoscience to Australia's most important challenges


-Original Message-
From: Python-list 
[mailto:[email protected]] On Behalf Of 
Robert Kern
Sent: Tuesday, 5 July 2016 12:18 AM
To: [email protected]
Subject: Re: Gzip module does not support Unix compressed .Z files 
[SEC=UNOFFICIAL]

On 2016-07-04 09:00, dieter wrote:
> "Owen Brandon"  writes:
>
>> I have a query regarding the support of decompression for Unix compressed .Z 
>> files in Python's gzip module. The gzip system utility supports this using 
>> the '-d' switch, but the python module does not.
>
> When I am right, then the "zipfile" module handles ".Z" compressed files.

No, that handles PKZIP .zip files. There are third-party modules that handle 
the .Z format, but shelling out to external programs may still be preferable:

   https://github.com/umeat/unlzw

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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

Geoscience Australia Disclaimer: This e-mail (and files transmitted with it) is 
intended only for the person or entity to which it is addressed. If you are not 
the intended recipient, then you have received this e-mail by mistake and any 
use, dissemination, forwarding, printing or copying of this e-mail and its file 
attachments is prohibited. The security of emails transmitted cannot be 
guaranteed; by forwarding or replying to this email, you acknowledge and accept 
these risks.
-

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


Re: Structure of program development

2016-07-04 Thread Lawrence D’Oliveiro
On Tuesday, July 5, 2016 at 7:51:18 AM UTC+12, BartC wrote:

> However the Linuxes I've seen tend to have Python pre-installed.

Some are even dropping Python 2, and only having Python 3 by default.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Structure of program development

2016-07-04 Thread Chris Angelico
On Tue, Jul 5, 2016 at 9:56 AM, Lawrence D’Oliveiro
 wrote:
> On Tuesday, July 5, 2016 at 7:51:18 AM UTC+12, BartC wrote:
>
>> However the Linuxes I've seen tend to have Python pre-installed.
>
> Some are even dropping Python 2, and only having Python 3 by default.

Yes, so your best bet is to aim for Python 3.3+ or 3.4+ compatibility,
and start your program like this:

#!/usr/bin/env python3

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


Re: Structure of program development

2016-07-04 Thread Michael Torrie
On 07/04/2016 01:50 PM, BartC wrote:
> On 04/07/2016 17:55, Chris Warrick wrote:
> 
>>> A second question of the basic design. If I write a program, can I move it 
>>> to a computer that is without any Python software, or does that machine 
>>> have to download the Python software? Does Python products contain all 
>>> parts of a developed program or is it a series of 'call' statements?
>>
>> You must either install a Python interpreter on that machine, or
>> distribute one with your program.
> 
> If only it was that simple. My Windows Python 3.4 installation comprises 
> 5200 files over 1300 directories, totalling 100MB.
> 
> Other Pythons are a bit smaller, so I don't know what extras that 
> includes. Which is part of the problem: you have to employ yet more 
> extras to figure out the files needed to create a tidy distribution.
> 
> However the Linuxes I've seen tend to have Python pre-installed. Then 
> you can just supply the .py files of the application.

There are various packagers out there that can wrap up your python
script with the interpreter and any library files necessary to run it.
I would bet the result is far less than 100 MB.  I'm sure you could
develop a python application that would use all 100 MB of the files that
comprise the standard library and the helper libraries if you really tried.

I'm not up to date on the latest packagers, but I know at one time folks
used py2exe, and some used cx_freeze.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-04 Thread Steven D'Aprano
On Mon, 4 Jul 2016 09:23 pm, jmp wrote:

> On 07/01/2016 04:13 PM, Steven D'Aprano wrote:
>> But classes are not like the others: they must be instantiated before
>> they can be used, and they are more than just a mere namespace grouping
>> related entities. Classes support inheritance. Classes should be used for
>> "is-a" relationships, not "has-a" relationships. Although classes (and
>> instances) are namespaces, they provide fundamentally different kind of
>> behaviour than modules and packages.
> 
> A namespace would not hurt but I really don't get why you don't consider
> classes a valid and rather helpful namespace.

I never said that.

This is where the term "namespace" can be ambiguous. "Namespace" can refer
to any of:

- an abstract mapping of symbols (names) to values;

- specific kinds of namespaces:

  * the concrete C++/C#/PHP data type called "namespace";
  * Python packages and modules;
  * classes;
  * instances of a class;

- the implementation (the __dict__ attribute of modules, classes);

etc. Now clearly a class is not the same thing as the class __dict__, and a
module is not the same as a class, and neither modules nor classes are the
same as a C++ namespace. Doesn't mean that classes aren't valid namespaces,
just that their semantics, use-cases and behaviour are different to those
of modules.



> 1/ classes do not have to be instantiated.

That's a bit of a sore point to me.

Some years ago I wrote here to ask what name is given to a class that is not
instantiated before being used. Singleton classes get instantiated once,
allowing a single instance. What if you had a class that didn't need
instantiating at all, so that the class itself was *effectively* the
singleton? What should that be called?


Instead of this:

class SingletonClass:
...

singleton = SingletonClass()
singleton.method()


what if we had this instead?

class singleton:
...

singleton.method()


I was roundly told that this was crazy talk, that the whole point of classes
was that they must be instantiated to use them, that code like the second
example would be confusing and very possibly bring about the fall of
Western Civilisation. The idea that this might be a legitimate alternative
to the singleton design pattern was dismissed.

(The Python community is terribly conservative when it comes to code.)

And, in a sense, they were right: there are two common ways to get
singleton-like behaviour in general, and in Python specifically:

- use class that allows only a single instance;

- use a module.

Using the class itself is unusual and surprising (especially to Java
programmers, where classes aren't even first-class values), and more so,
it's *inconvenient*.

To write a class which is used without instantiation, you should raise an
error on instantiation, decorate every method using classmethod or
staticmethod, and have methods have to call each other using the dotted
name:

class Example:
var = 999

def __init__(self):
raise TypeError('do not instantiate this class')

@classmethod
def spam(cls, arg):
return cls.eggs(arg) + cls.var

@classmethod
def eggs(cls, arg):
return arg*2


*** IF *** you are willing to push the code out into its own separate .py
file, you can use a module and write your code in a more natural form:


# module example.py
var = 999

def spam(arg):
return eggs(arg) + var

def eggs(arg):
return arg*2


What I'm calling a "namespace" is just a module object that lives inside
another module, without requiring a separate .py file. It only uses
the "class" statement for pragmatic reasons: there's no other statement
available that will do the job.


> 2/ the fact that classes are more than a namespace is not an argument.
> Almost any object in python is able to do more than what you are
> actually using.

There's one aspect of classes that is a deliberate design feature, but goes
against what I'm after: the fact that the class namespace itself is NOT
part of the method name resolution rules (except during class
construction). Try this:

x = 999

class Example:
x = 1
print(x)  # called during class construction
@classmethod
def test(cls):
print(x)


Example.test()



This will print 1, then 999. We quite often get people complaining about
this. I'm not one of them. I want classes to keep the current rules. But it
shows that a class is not the right answer for a module-inside-a-module
object.


> 3/ Classes are used as much as 'is-a' than 'has-a', class instances
> *have* a state usually described by attributes

Instances have state, of course, but the relationship I'm talking about is
instance to class.

class Dog:
...

lassie = Dog()

Lassie is a dog, not "Lassie has a dog".

Lassie has a tail, not "Lassie is a tail".


That's why we have IS_instance and HAS_attr builtins.

The expectation is that a class represents a model of a physical kind of
thing, whether that's a Dog or a HTTPSe

Re: Namespaces are one honking great idea

2016-07-04 Thread Chris Angelico
On Tue, Jul 5, 2016 at 12:34 PM, Steven D'Aprano  wrote:
> *** IF *** you are willing to push the code out into its own separate .py
> file, you can use a module and write your code in a more natural form:
>
>
> # module example.py
> var = 999
>
> def spam(arg):
> return eggs(arg) + var
>
> def eggs(arg):
> return arg*2
>
>
> What I'm calling a "namespace" is just a module object that lives inside
> another module, without requiring a separate .py file. It only uses
> the "class" statement for pragmatic reasons: there's no other statement
> available that will do the job.

If you push your code into a separate .py file, you can reference the
original module by importing it. Is that also the normal way to use
"outer" functions etc from inside a namespace?

# demo.py
pi = 3.14
def stupidfib(x):
if x < 2: return x
return stupidfib(x-1) + stupidfib(x-2)


Namespace asdf: # (or class, however it's done)
def foo(x):
return stupidfib(x * pi) / pi

How should foo reference those "even more global" names? "from .
import pi, stupidfib" would work if you converted the module into a
package ("mv demo.py demo/__init__.py"), and "from demo import pi,
stupidfib" would work if you converted the namespace into a peer
module. Either could make sense.

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


Nested class doesn't see class scope

2016-07-04 Thread Steven D'Aprano
I got this in Python 3.6:


py> class A:
... var = 999
... print(var)  # succeeds
... class B:
... x = var
...
999
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in A
  File "", line 4, in B
NameError: name 'var' is not defined


I expected that `var` would be available during the construction of B, just
as it was available inside A, but not to methods inside B. Obviously my
expectations are invalid. Can anyone explain the actual behaviour?



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Namespaces are one honking great idea

2016-07-04 Thread Steven D'Aprano
On Tue, 5 Jul 2016 12:58 pm, Chris Angelico wrote:

> On Tue, Jul 5, 2016 at 12:34 PM, Steven D'Aprano 
> wrote:
>> *** IF *** you are willing to push the code out into its own separate .py
>> file, you can use a module and write your code in a more natural form:
>>
>>
>> # module example.py
>> var = 999
>>
>> def spam(arg):
>> return eggs(arg) + var
>>
>> def eggs(arg):
>> return arg*2
>>
>>
>> What I'm calling a "namespace" is just a module object that lives inside
>> another module, without requiring a separate .py file. It only uses
>> the "class" statement for pragmatic reasons: there's no other statement
>> available that will do the job.
> 
> If you push your code into a separate .py file, you can reference the
> original module by importing it. Is that also the normal way to use
> "outer" functions etc from inside a namespace?

Good question! 

With the current implementation, importing should work, but it's not
necessary. The surrounding module (the real .py module) is inserted into
the name resolution path of functions:

py> x = 999
py> @namespace.Namespace
... class Test:
... def test():
... print(x)
...
py> Test.test()
999


Of course, the module-global x will be shadowed by any x in the Test
namespace (which is the intent), and you cannot assign to them (also a
feature). A bare `x = 1` inside the function will make x a local, unless
you declare it global first, in which case it should assign to the Test
namespace scope instead.




-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Nested class doesn't see class scope

2016-07-04 Thread Rustom Mody
On Tuesday, July 5, 2016 at 8:50:57 AM UTC+5:30, Steven D'Aprano wrote:
> I got this in Python 3.6:
> 
> 
> py> class A:
> ... var = 999
> ... print(var)  # succeeds
> ... class B:
> ... x = var
> ...
> 999
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in A
>   File "", line 4, in B
> NameError: name 'var' is not defined
> 
> 
> I expected that `var` would be available during the construction of B, just
> as it was available inside A, but not to methods inside B. Obviously my
> expectations are invalid. Can anyone explain the actual behaviour?
> 

Heh!
Nice to see you confused by python's ‘concave’ LEGB rule
One of those thing I never get used to…
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested class doesn't see class scope

2016-07-04 Thread Paul Rubin
Steven D'Aprano  writes:
> ... class B:
> ... x = var

x = A.var
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Namespaces are one honking great idea

2016-07-04 Thread Chris Angelico
On Tue, Jul 5, 2016 at 1:35 PM, Steven D'Aprano  wrote:
>> If you push your code into a separate .py file, you can reference the
>> original module by importing it. Is that also the normal way to use
>> "outer" functions etc from inside a namespace?
>
> Good question!
>
> With the current implementation, importing should work, but it's not
> necessary. The surrounding module (the real .py module) is inserted into
> the name resolution path of functions:
>
> py> x = 999
> py> @namespace.Namespace
> ... class Test:
> ... def test():
> ... print(x)
> ...
> py> Test.test()
> 999

Ah, fascinating. This does break the "just unindent and move to a new
file if you want to break it out" equivalency, but it does make sense
- it's a *nested* namespace, which modules (even in a package) are
not. So you have the outer namespace acting pretty much the way
builtins do. (Do nested namespaces work?)

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


How well do you know Python?

2016-07-04 Thread Chris Angelico
After some discussion with a Ruby on Rails programmer about where Ruby
ends and where Rails begins (and it's definitely not where I'd have
expected... Rails does a ton of monkey-patching, including of built-in
types, to provide functionality that is strangely absent from the core
language), I tried to come up with some somewhat-challenging Python
questions. But to make them hard, I had to go a smidge more esoteric
than the Ruby questions did Anyhow, see how you go. Assume Python
3.x unless stated.

1) Under what circumstances can str.upper() return a string of
different length to its input?
2) What exception do you get when you craft an impossible class hierarchy?
a. ValueError b. TypeError c. types.ClassInheritanceError d. SyntaxError
3) What does `from __future__ import braces` do?
4) Which operator, removed from Python 3.0, can be reinstated with a
'joke' future directive?
5) What is the difference between the `/` and `//` operators in Python
2.7? In Python 3.x?

Got any other tricky questions to add?

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


py2exe crashes on simple program

2016-07-04 Thread John Nagle
  I'm trying to create an executable with py2exe.
The program runs fine in interpretive mode.  But
when I try to build an executable, py2exe crashes with
an assertion error. See below.

  This is an all-Python program; no binary modules
other than ones that come with the Python 3.5.2
distribution. Running "python setup.py bdist"
works, so "setup.py" is sane.  What's giving
py2exe trouble?

U:\>python setup.py py2exe
running py2exe
running build_py
Building shared code archive 'dist\library.zip'.
Traceback (most recent call last):
  File "setup.py", line 14, in 
packages=['baudotrss'],
  File "C:\Program Files\Python35\lib\distutils\core.py", line 148, in setup
dist.run_commands()
  File "C:\Program Files\Python35\lib\distutils\dist.py", line 955, in
run_commands
self.run_command(cmd)
  File "C:\Program Files\Python35\lib\distutils\dist.py", line 974, in
run_command
cmd_obj.run()
  File "C:\Program
Files\Python35\lib\site-packages\py2exe\distutils_buildexe.py", line
188, in run
self._run()
  File "C:\Program
Files\Python35\lib\site-packages\py2exe\distutils_buildexe.py", line
268, in _run
builder.build()
  File "C:\Program Files\Python35\lib\site-packages\py2exe\runtime.py",
line 261, in build
self.build_archive(libpath, delete_existing_resources=True)
  File "C:\Program Files\Python35\lib\site-packages\py2exe\runtime.py",
line 426, in build_archive
assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
AssertionError


Python 3.5.2 / Win7 / AMD64.

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


Re: Nested class doesn't see class scope

2016-07-04 Thread Ian Kelly
On Mon, Jul 4, 2016 at 9:42 PM, Paul Rubin  wrote:
> Steven D'Aprano  writes:
>> ... class B:
>> ... x = var
>
> x = A.var

Nope. A doesn't exist yet at this point.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested class doesn't see class scope

2016-07-04 Thread Ian Kelly
On Mon, Jul 4, 2016 at 9:20 PM, Steven D'Aprano  wrote:
> I got this in Python 3.6:
>
>
> py> class A:
> ... var = 999
> ... print(var)  # succeeds
> ... class B:
> ... x = var
> ...
> 999
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in A
>   File "", line 4, in B
> NameError: name 'var' is not defined
>
>
> I expected that `var` would be available during the construction of B, just
> as it was available inside A, but not to methods inside B. Obviously my
> expectations are invalid. Can anyone explain the actual behaviour?

Class definitions don't create closures like functions do. When Python
executes a class definition, the metaclass creates a dict, and then
the interpreter execs the class body using that dict as the locals.
The body of class A has one locals dict, and the body of class B has a
completely separate locals dict. The only way to share variables
between them (prior to the class objects actually being constructed)
is via globals.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nested class doesn't see class scope

2016-07-04 Thread Ian Kelly
On Mon, Jul 4, 2016 at 10:41 PM, Ian Kelly  wrote:
> On Mon, Jul 4, 2016 at 9:20 PM, Steven D'Aprano  wrote:
>> I got this in Python 3.6:
>>
>>
>> py> class A:
>> ... var = 999
>> ... print(var)  # succeeds
>> ... class B:
>> ... x = var
>> ...
>> 999
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "", line 3, in A
>>   File "", line 4, in B
>> NameError: name 'var' is not defined
>>
>>
>> I expected that `var` would be available during the construction of B, just
>> as it was available inside A, but not to methods inside B. Obviously my
>> expectations are invalid. Can anyone explain the actual behaviour?
>
> Class definitions don't create closures like functions do. When Python
> executes a class definition, the metaclass creates a dict, and then
> the interpreter execs the class body using that dict as the locals.
> The body of class A has one locals dict, and the body of class B has a
> completely separate locals dict. The only way to share variables
> between them (prior to the class objects actually being constructed)
> is via globals.

Or I suppose one could write a metaclass that does something fancy
when creating the dicts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Making Classes Subclassable

2016-07-04 Thread Michael Selik
On Mon, Jul 4, 2016, 4:36 AM Lawrence D’Oliveiro 
wrote:

> On Monday, July 4, 2016 at 7:58:07 PM UTC+12, dieter wrote:
> > --> "type(obj)" or "obj.__class__" (there are small differences)
> > give you the type/class of "obj".
>
> When would it not be the same?
>

Old-style classes.

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


Re: Nested class doesn't see class scope

2016-07-04 Thread Steven D'Aprano
On Tuesday 05 July 2016 14:41, Ian Kelly wrote:

> Class definitions don't create closures like functions do. When Python
> executes a class definition, the metaclass creates a dict, and then
> the interpreter execs the class body using that dict as the locals.
> The body of class A has one locals dict, and the body of class B has a
> completely separate locals dict. The only way to share variables
> between them (prior to the class objects actually being constructed)
> is via globals.


So, like nested functions in Python before "from __future__ import 
nested_scopes".


Okay, that's reasonable.



-- 
Steve

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


Re: How well do you know Python?

2016-07-04 Thread Steven D'Aprano
On Tuesday 05 July 2016 14:02, Chris Angelico wrote:

> After some discussion with a Ruby on Rails programmer about where Ruby
> ends and where Rails begins (and it's definitely not where I'd have
> expected... Rails does a ton of monkey-patching, including of built-in
> types, to provide functionality that is strangely absent from the core
> language), I tried to come up with some somewhat-challenging Python
> questions. But to make them hard, I had to go a smidge more esoteric
> than the Ruby questions did Anyhow, see how you go. Assume Python
> 3.x unless stated.




S
P
O
I
L
E
R
 
S
P
A
C
E



A
N
D
 
A
 
B
I
T
 
M
O
R
E
 


> 1) Under what circumstances can str.upper() return a string of
> different length to its input?

Potentially any string might uppercase to a different length, depending on the 
content of the string and the case conversion rules for letters from that 
script. For Europeans, the simplest example is probably the German eszett, or 
\N{LATIN SMALL LETTER SHARP S}. There's an uppercase version, \N{LATIN CAPITAL 
LETTER SHARP S} but for historical reasons (and the idiosyncrasies of German) 
"ß" uppercases to "SS".


> 2) What exception do you get when you craft an impossible class hierarchy?
> a. ValueError b. TypeError c. types.ClassInheritanceError d. SyntaxError

Without checking, I would expect TypeError (90% confident) or SyntaxError 
(unlikely).


> 3) What does `from __future__ import braces` do?

Report your IP address and username to a secret database of people who will be 
sent to the gulags for re-education when the revolution comes. Or at least, 
they would be, if the Python Secret Underground, which most definitely doesn't 
exist, existed, which it doesn't.

Otherwise it prints the final word on the question of braces in Python.


> 4) Which operator, removed from Python 3.0, can be reinstated with a
> 'joke' future directive?

The <> not-equal operator.


> 5) What is the difference between the `/` and `//` operators in Python
> 2.7? In Python 3.x?

In Python 3, / means "true division" (i.e. what a calculator will do), and // 
means "integer division". E.g. 11/2 gives 5.5, while 11//2 gives 5.

In 2.7, there are two cases: with, or without "from __future__ import 
division". With the __future__ directive, they mean the same as in Python 3. 
Without, // means "integer division", but / depends on its arguments. If both 
arguments are ints, it performs integer division. If at least one is a float, 
it performs "true division" like a calculator.

Although to be pedantic, in all cases it depends on operator overloading :-)



-- 
Steve

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


Re: Namespaces are one honking great idea

2016-07-04 Thread Steven D'Aprano
On Tuesday 05 July 2016 13:47, Chris Angelico wrote:

> On Tue, Jul 5, 2016 at 1:35 PM, Steven D'Aprano  wrote:
>>> If you push your code into a separate .py file, you can reference the
>>> original module by importing it. Is that also the normal way to use
>>> "outer" functions etc from inside a namespace?
>>
>> Good question!
>>
>> With the current implementation, importing should work, but it's not
>> necessary. The surrounding module (the real .py module) is inserted into
>> the name resolution path of functions:
>>
>> py> x = 999
>> py> @namespace.Namespace
>> ... class Test:
>> ... def test():
>> ... print(x)
>> ...
>> py> Test.test()
>> 999
> 
> Ah, fascinating. This does break the "just unindent and move to a new
> file if you want to break it out" equivalency, but it does make sense
> - it's a *nested* namespace, which modules (even in a package) are
> not. So you have the outer namespace acting pretty much the way
> builtins do. (Do nested namespaces work?)

I haven't got that far, but I expect that nested namespaces will be nested in 
name only, like nested functions in Python 1.5.

There's only so far I can go without support from the compiler. If you nest a 
class inside another class, the inner class doesn't see variables in the outer 
class even during construction. So I'm pretty sure my namespace metaclass will 
inherit the same limitation.



-- 
Steve

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


Re: py2exe crashes on simple program

2016-07-04 Thread Steven D'Aprano
On Tuesday 05 July 2016 14:06, John Nagle wrote:

>   I'm trying to create an executable with py2exe.
> The program runs fine in interpretive mode.  But
> when I try to build an executable, py2exe crashes with
> an assertion error. See below.
[...]
> Building shared code archive 'dist\library.zip'.
[...]
> assert mod.__file__.endswith(EXTENSION_SUFFIXES[0])
> AssertionError

To me, that looks like you're trying to build something called "library.zip" 
and .zip isn't an allowed file type extension.

If you change it to "library.exe" does it work?

Also, I consider this a bug in py2exe:

- it's an abuse of assert, using it to check user-supplied input;

- it's a failing assertion, which by definition is a bug.



-- 
Steve

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


Re: How well do you know Python?

2016-07-04 Thread Steven D'Aprano
On Tuesday 05 July 2016 14:02, Chris Angelico wrote:

> After some discussion with a Ruby on Rails programmer about where Ruby
> ends and where Rails begins (and it's definitely not where I'd have
> expected... Rails does a ton of monkey-patching, including of built-in
> types, to provide functionality that is strangely absent from the core
> language), I tried to come up with some somewhat-challenging Python
> questions. But to make them hard, I had to go a smidge more esoteric
[...]
> Got any other tricky questions to add?


Explain metaclasses, descriptors, the mro, multiple inheritance, and the 
interaction between them. Why is the mro needed?

obj.spam is a property. How do you get access to the underlying property object 
itself?

Why doesn't the property decorator work inside a Python 2 classic class?

Explain Python scoping rules, in particular with respect to nested classes and 
nested functions (or even nested classes inside nested functions).

Explain attribute lookup rules. When does an instance attribute take priority 
over a class attribute?

When is locals() writable? When is locals() writable, AND the effect shows up 
in the local scope? Explain how exec works inside a function, and the 
interaction with locals().

Name all the falsey builtins.

Apart from exceptions, list the builtins, from memory. You can list the 
exceptions as well.

An easy one: list the Python keywords.

What happens in this code snippet?

L = [1]
t = (L,)
t[0] += 1

Explain what value t has, and why.

Explain what "yield from it" does and how it is different from:

for item in it:
yield item




-- 
Steve

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


Re: How well do you know Python?

2016-07-04 Thread Chris Angelico
On Tue, Jul 5, 2016 at 4:33 PM, Steven D'Aprano
 wrote:
> What happens in this code snippet?
>
> L = [1]
> t = (L,)
> t[0] += 1
>
> Explain what value t has, and why.

Not sure you have that question right, because it simply gives a
TypeError. You can't add an integer to a list.

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