Re: "Natural" use of cmp= in sort

2014-11-12 Thread Paddy
On Tuesday, 11 November 2014 18:07:27 UTC, Ian  wrote:
> The example that I posted is one that I recall being brought up on
> this list in the past, but I don't have a link for you.

THanks Ian for your help in this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Terry Reedy

On 11/11/2014 5:52 PM, Ben Finney wrote:

Terry Reedy  writes:


We love 'assert' so much that we have 20-30 'assertXYZ' variations in
unittest.


A function will not be disabled by a run-time option to the Python
interpreter.


The statement 'assert expression' is almost equivalent to

if not expression: raise AssertionError('expression')


With the important difference that this will be active no matter what
options Python's interpreter is run with. That makes it quite a
different proposition from using ‘assert’ statements.


Which importand difference I pointed out (and you snipped) as a reason 
to seldom use bare assert.


--
Terry Jan Reedy


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


Re: Advice

2014-11-12 Thread Joel Goldstick
On Tue, Nov 11, 2014 at 11:53 AM, Mary-Frances McNamee <
[email protected]> wrote:

>  To whom it may concern,
>
>
>
> I am currently working on a bit of coding for a raspberry pi, I was
> wondering maybe I could get some advice? I want my program to run for a
> certain time, for example 7am-2.30am everyday. Is this possible?
>
>
>
> I would appreciate any help. Thank you for your time.
>
>
>
>
>
> Regards
>
> Mary-Frances
>
>
>
> [image: cid:[email protected]]
>
> *Environmental Products & Services Ltd*
>
> Email: [email protected]
>
> Tel: +44 (0) 28 30833081 Fax: +44 (0) 28 30257556
>
> Address: 5 Shepherd’s Drive, Carnbane Industrial Estate, Newry, Co. Down
> N. Ireland BT35 6JQ
>
> Website  | Brochure (PDF)
>  | Videos
>  | Product Pack
> 
>
> Company Registration No. N.I.34654
> All Incoming and Outgoing emails are scanned using Sophos Anti-Virus – Ver
> 10.2
>
>
>
> [image: cid:[email protected]]
>
>
>
You may get more specific advice in a RPi mailing list, but you can start
your program with a cron job (google that), and check the time in your code
so as to exit at the required time

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


-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-12 Thread Clayton Kirkwood


>-Original Message-
>From: Python-list [mailto:python-list-
>[email protected]] On Behalf Of Chris Angelico
>Sent: Tuesday, November 11, 2014 12:36 AM
>Cc: [email protected]
>Subject: Re: I don't read docs and don't know how to use Google. What
>does the print function do?
>
>On Tue, Nov 11, 2014 at 10:21 AM, Clayton Kirkwood 
>wrote:
>> Uh, how are you going to maintain a programming job if you don't know
>> how to program? I don't want to act but I know Brad Pitt makes lots of
>> money doing it, so I want to be Brad Pitt. Not! Not going to happen.
>> Although I suspect for a price you could bring all of your
>> professional programming jobs to somebody here, but I think you would
>pay out more than you would make.
>>
>
>I'm not entirely sure how it works, but it does happen. I've been
>writing code for over two decades, and trying to earn a living at it for
>one and a bit, and in all that time, I have *never even once* found a
>job by applying in the classic way and sending in a resume.
>There are blog posts out there about how large proportions of applicants
>can't even write simple code on command... and I've taken the questions
>and shown them to my siblings (who protest that they're definitely not
>programmers), proving that a basic smattering of mathematical nous puts
>you above people who are trying to earn money from coding.
>
>It's like a carpenter, looking for a skilled assistant, and getting
>people who don't know which end of a saw to hold.
>
>It's like a prospective accountant not knowing the words "credit" and
>"debit".
>
>It's like someone trying to rule a country just on the basis of looking
>good on television... okay, so maybe there's one other "industry" where
>the incompetent have a shot at it.
>
>But fortunately, it's not everyone. There are the "bad eggs" who waste
>everyone's time, but there are plenty of truly competent people too.
>It's just a matter of figuring out which are the "will-be-competent"
>and which are the "totally lazy and not going anywhere", and there's not
>always a lot to distinguish them by.
>
>ChrisA

Chris, you're kidding, right? People get programming jobs without the
knowledge? How do they keep them? Don't hiring people look at code examples,
or previous employment? Ask relevant questions? My wife works for the county
district attorney's office, and she tells me a lot about the incompetence of
her co-workers and how they just kind of don't do their job, the petty
personalities. My daughter works for AAA and tells how little co-workers
know and are not willing to learn anything, but expect raises, etc. It's
really hard for me to believe. I've worked in professional environs like
Intel and Lockheed. You didn't keep a job long if you screwed around, and
except for one person, everyone worked hard and earned their living,
learning as much as they could, and generally got along. Some were great
work groups that were incredibly rewarding and enjoyable. I have trouble
believing the work ethics and behavior my family tells me about. Totally
foreign to me.

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



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


Re: html page mail link to webmail program

2014-11-12 Thread alister
On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote:

> On 11/11/2014 05:08 PM, Ben Finney wrote:
>> Ethan Furman  writes:
>>
>>> My wife (using a Win7 machine) will be on a web page that has a link
>>> to mail somebody.  She clicks on it, and it opens the currently
>>> installed but unused Thunderbird.
>>>
>>> Ideally, what would happen is a new window/tab would open to gmail
>>> with a new compose window with the email address in place and the
>>> cursor in the subject line.
>>
>> What is the Python question? I can't see anywhere that you would be
>> using Python code to address this.
> 
> Really?  Huh.
> 
> Okay, the explicit Python question:  Clicking on a mail link in a web
> browser can start an external program.  I would like that external
> program to be a Python script that: opens a new tab in the currently
> running browser (or a new default browser window), loads up the default
> web mail client (or one specified if there is no way to know/have a
> default), navigates to the compose pane (or starts there if possible),
> enters in the email address from the link that was passed to it, and, if
> not too much more, move the cursor to the subject field.
> 
> Surely this can be done in Python.

any chance you could fix your broken news reader?



-- 
Life is to you a dashing and bold adventure.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: html page mail link to webmail program

2014-11-12 Thread alister
On Wed, 12 Nov 2014 08:56:07 +, alister wrote:

> On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote:
> 
>> On 11/11/2014 05:08 PM, Ben Finney wrote:
>>> Ethan Furman  writes:
>>>
 My wife (using a Win7 machine) will be on a web page that has a link
 to mail somebody.  She clicks on it, and it opens the currently
 installed but unused Thunderbird.

 Ideally, what would happen is a new window/tab would open to gmail
 with a new compose window with the email address in place and the
 cursor in the subject line.
>>>
>>> What is the Python question? I can't see anywhere that you would be
>>> using Python code to address this.
>> 
>> Really?  Huh.
>> 
>> Okay, the explicit Python question:  Clicking on a mail link in a web
>> browser can start an external program.  I would like that external
>> program to be a Python script that: opens a new tab in the currently
>> running browser (or a new default browser window), loads up the default
>> web mail client (or one specified if there is no way to know/have a
>> default), navigates to the compose pane (or starts there if possible),
>> enters in the email address from the link that was passed to it, and,
>> if not too much more, move the cursor to the subject field.
>> 
>> Surely this can be done in Python.
> 
> any chance you could fix your broken news reader?

Apologies, all posts seem broken today. I am not sure of the cause yet



-- 
Boren's Laws:
(1) When in charge, ponder.
(2) When in trouble, delegate.
(3) When in doubt, mumble.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I don't read docs and don't know how to use Google. What does the print function do?

2014-11-12 Thread Chris Angelico
On Wed, Nov 12, 2014 at 4:39 PM, Clayton Kirkwood  wrote:
> Chris, you're kidding, right? People get programming jobs without the
> knowledge? How do they keep them? Don't hiring people look at code examples,
> or previous employment? Ask relevant questions?

Oh, I didn't say they *keep* the jobs, nor necessarily even get them!
(Although that can happen too - check out http://thedailywtf.com/ and
some of the stories of what former employees' code can look like.) I'm
talking about them applying, and then the potential employers have to
weed through the utter incompetents to find the few who actually know
what they're talking about. If the employer is himself/herself a
programmer, this is a huge waste of a skilled person's time; if not,
the short-listing of applicants will be highly flawed. Hence the
problem: it's so hard to pick the right applicants that the right
applicants end up not being picked - and so jobs remain unfilled (as I
can attest to - the same job postings keep coming up in my RSS feeds),
or incompetents get jobs and then get moved on.

Sure, you could figure out whether one person is worth hiring or not.
But when you have two hundred applications, can you afford to talk to
every single one of them? I doubt it. And that's the problem.

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


Re: ssl error with the python mac binary

2014-11-12 Thread Paul Wiseman
On 10 November 2014 22:51, Ned Deily  wrote:
> In article
> ,
>  Paul Wiseman  wrote:
>> I've been using the latest mac ppc/i386 binaries from python.org
>> (https://www.python.org/ftp/python/2.7.8/python-2.7.8-macosx10.5.dmg).
>> From what I can tell this version is linked against a pretty old
>> version of OpenSSL (OpenSSL 0.9.7l 28 Sep 2006) which doesn't seem to
>> be able to handle new sha-256 certificates.
>>
>> For example I'm unable to use pip (I guess the certificate was updated
>> recently)
>
> Yes, the current python.org certificate does seem to cause problems for
> that version of OpenSSL, unfortunately.
>
>> Am I right in thinking this is an issue with the build of python
>> itself? Is there a way I can upgrade the version of OpenSSL linked
>> with python- or force the python build to look elsewhere for the
>> library? Or will I have to build my own from source?
>
> In the Pythons from the python.org OS X installers, the Python _ssl and
> _hashlib extension modules are dynamically linked with the
> system-supplied OpenSSL libraries.  If actually running on OS X 10.5,
> one would have to rebuild _ssl.so and _hashlib.so, linking them with a
> locally-supplied version of a newer OpenSSL, since different versions of
> OpenSSL are not ABI-compatible, e.g. 0.9.7 vs 0.9.8 vs 1.0.1.  If
> running on OS X 10.6 or later, another option might be to install from
> the 64-bit/32-bit installer which is a good idea to do anyway.

I'm currently using the installer with py2app to make a distributable
app that targets 10.5+ (including ppc). To save having more than one
build I use this for all downloads. Although I'm starting to consider
making a second 32/64 distributable. Are there many major drawbacks
for distributing this i386/ppc binary for all versions of OSX up 10.9
and 10.10?

> For pip
> usage, a workaround would be to manually download distributions from
> PyPI (or elsewhere) using a web browser and then use pip to install from
> the downloaded file.   The next version of pip is expected to have a
> --no-check-certificate option that bypasses the certificate check at the
> cost of reduced security.

Unfortunately the app is contacting a service which I'm unable to
contact via plain http, which also happens to have the same type of
certificate resulting in the same ssl error. (I have been going
directly to pypi though :)

> For the upcoming Python 2.7.9 release
> (planned for early December), I intend to have the Pythons in the
> python.org OS X installers use their own versions of OpenSSL and thus no
> longer depend on the now-deprecated system OpenSSL.
>

That's great news! Thanks for this! I've always found building things
on mac a huge pain and wasn't much looking forward to the prospect of
trying to build a 32/ppc python build on a 64 bit 10.10 machine (would
that even be possible?).

> --
>  Ned Deily,
>  [email protected]
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: html page mail link to webmail program

2014-11-12 Thread Joel Goldstick
On Wed, Nov 12, 2014 at 3:58 AM, alister
 wrote:
> On Wed, 12 Nov 2014 08:56:07 +, alister wrote:
>
>> On Tue, 11 Nov 2014 17:35:11 -0800, Ethan Furman wrote:
>>
>>> On 11/11/2014 05:08 PM, Ben Finney wrote:
 Ethan Furman  writes:

> My wife (using a Win7 machine) will be on a web page that has a link
> to mail somebody.  She clicks on it, and it opens the currently
> installed but unused Thunderbird.
>
> Ideally, what would happen is a new window/tab would open to gmail
> with a new compose window with the email address in place and the
> cursor in the subject line.

There are plugins on chrome to make gmail the mail client.  Firefox I
think has a setting to do the same.  You should look into the
browser/OS settings before rolling your own, since using python means
setting up a web site.. all this to pick the default mail client?

 What is the Python question? I can't see anywhere that you would be
 using Python code to address this.
>>>
>>> Really?  Huh.
>>>
>>> Okay, the explicit Python question:  Clicking on a mail link in a web
>>> browser can start an external program.  I would like that external
>>> program to be a Python script that: opens a new tab in the currently
>>> running browser (or a new default browser window), loads up the default
>>> web mail client (or one specified if there is no way to know/have a
>>> default), navigates to the compose pane (or starts there if possible),
>>> enters in the email address from the link that was passed to it, and,
>>> if not too much more, move the cursor to the subject field.
>>>
>>> Surely this can be done in Python.
>>
>> any chance you could fix your broken news reader?
>
> Apologies, all posts seem broken today. I am not sure of the cause yet
>
>
>
> --
> Boren's Laws:
> (1) When in charge, ponder.
> (2) When in trouble, delegate.
> (3) When in doubt, mumble.
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Curious function argument

2014-11-12 Thread ast

Hello

I saw in a code from a previous message in this forum
a curious function argument.

def test(x=[0]):
  print(x[0])   ## Poor man's object
  x[0] += 1


test()

0

test()

1

test()

2




I understand that the author wants to implement a global
variable x . It would be better to write 'global x' inside the
function.

At first test() function call, it prints 0, that's OK.
But at the second call, since we dont pass any argument to test(),
x should be equal to its default value [0] (a single item list). But
it seems that Python keeps the original object whose content has
been changed to 1.

Is it a usual way to implement a global variable ?

thx





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


Re: Curious function argument

2014-11-12 Thread Denis McMahon
On Wed, 12 Nov 2014 14:07:14 +0100, ast wrote:

[function def with mutable default parameter]

> I understand that the author wants to implement a global variable x . It
> would be better to write 'global x' inside the function.

It may not be the case that the purpose was to implement a global 
variable, but rather to illustrate what happens when you use a mutable 
default parameter.

> At first test() function call, it prints 0, that's OK.
> But at the second call, since we dont pass any argument to test(), x
> should be equal to its default value [0] (a single item list). But it
> seems that Python keeps the original object whose content has been
> changed to 1.

This is explained in the docs:

https://docs.python.org/3/reference/compound_stmts.html#function-
definitions

Default parameter values are evaluated from left to right *when the 
function definition is executed*[1]. This means that the expression is 
evaluated once, when the function is defined, and that the same “pre-
computed” value is used for each call. This is especially important to 
understand when a default parameter is a mutable object, such as a list 
or a dictionary: if the function modifies the object (e.g. by appending 
an item to a list), the default value is in effect modified.

[1] ie when the function is 'compiled', not each time it executes.

-- 
Denis McMahon, [email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Grant Edwards
On 2014-11-12, Ben Finney  wrote:
> Chris Angelico  writes:
>
>> On Wed, Nov 12, 2014 at 7:03 AM, Ben Finney  
>> wrote:
>> > An ‘assert’ statement in the code will sometimes be active, and
>> > sometimes be a no-op, for *exactly* the same code under different
>> > circumstances. That's a trap for the reader, and I'd rather not set
>> > it.
>>
>> This is no worse than other forms of preprocessor magic.
>
> That other languages do it doesn't argue in favour of it. It argues,
> rather, that we should be glad not to have it in our Python code.

Technically it's not an argument for assert, but I think it is a
refutation of one of your arguments against assert. It refutes your
statement that the fact that asserts may not always be active is a
suprise to people and therefore acts as a "trap".

-- 
Grant Edwards   grant.b.edwardsYow! Is it clean in other
  at   dimensions?
  gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: __missing__ for the top-level Python script

2014-11-12 Thread Chris Angelico
On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico  wrote:
> So the semantics should be: If NameError would be raised (not
> including UnboundLocalError, which still represents an error), attempt
> to import the absent name. If successful, continue as if it had
> already been done. If ImportError is raised, suppress it and let the
> original NameError happen.

No bites? I'd have thought there'd be a few crazy ideas thrown out in
answer to this.

What if it's worded as a feature for interactive Python? Save you the
trouble of explicitly importing modules, by auto-importing them in
response to usage. In theory, it's as simple as adding __missing__ to
globals(), but I don't know of a way to do that for the main module.

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Ethan Furman

On 11/12/2014 06:37 AM, Chris Angelico wrote:

On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico  wrote:

So the semantics should be: If NameError would be raised (not
including UnboundLocalError, which still represents an error), attempt
to import the absent name. If successful, continue as if it had
already been done. If ImportError is raised, suppress it and let the
original NameError happen.


No bites? I'd have thought there'd be a few crazy ideas thrown out in
answer to this.

What if it's worded as a feature for interactive Python? Save you the
trouble of explicitly importing modules, by auto-importing them in
response to usage. In theory, it's as simple as adding __missing__ to
globals(), but I don't know of a way to do that for the main module.


You might check out https://docs.python.org/3/library/sys.html#sys.excepthook

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Skip Montanaro
> No bites? I'd have thought there'd be a few crazy ideas thrown out in
> answer to this.

I was on vacation for a few days, so haven't been all that attentive
to my mail. I have an autoload module which does something similar
(note the Python 2.x syntax):

import sys, inspect, traceback, re

def autoload_exc(ty, va, tb):
mat = re.search("name '([^']*)' is not defined", va.args[0])
if mat is not None:
modulename = mat.group(1)
print >> sys.stderr, "autoloading", modulename
f_locals = tb.tb_frame.f_locals
f_globals = tb.tb_frame.f_globals

exec "import " + modulename in f_locals, f_globals
exec tb.tb_frame.f_code in f_locals, f_globals
else:
traceback.print_exception(ty, va, tb)

sys.excepthook = autoload_exc

which works about as you'd expect:

>>> sys.excepthook

>>> math.sin(42)
autoloading math
-0.9165215479156338
>>> string.uppercase
autoloading string
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

I can't see a lot of people wanting this (I normally have its import
commented out in my PYTHONSTARTUP file), and I think it would probably
be bad practice for new users of the language.

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Dave Angel
Chris Angelico  Wrote in message:
> On Mon, Nov 10, 2014 at 10:31 AM, Chris Angelico  wrote:
>> So the semantics should be: If NameError would be raised (not
>> including UnboundLocalError, which still represents an error), attempt
>> to import the absent name. If successful, continue as if it had
>> already been done. If ImportError is raised, suppress it and let the
>> original NameError happen.
> 
> No bites? I'd have thought there'd be a few crazy ideas thrown out in
> answer to this.
> 
> What if it's worded as a feature for interactive Python? Save you the
> trouble of explicitly importing modules, by auto-importing them in
> response to usage. In theory, it's as simple as adding __missing__ to
> globals(), but I don't know of a way to do that for the main module.
> 
> ChrisA
> 

I gave it a short whirl, just trying to make __missing__ work.

The type of globals () is a dict. I was able to add a
 __missing__:myfunct to the instance but in order to work, the
 __missing__ must be added as a class attribute,  a method. And
 dict, being implemented in C, doesn't let you add class
 attributes. Presumably the C code does the equivalent of
 slots.

So the next thing to try would be to try to force the module
 dictionary to be a userdict without slots. Then we could add the
 necessary method. But that would be changing the python source. I
 wasn't sure that was within the challenge constraints.

-- 
DaveA

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


Re: [Python-Dev] Dinamically set __call__ method

2014-11-12 Thread Fabio Zadrozny
On Tue, Nov 11, 2014 at 5:43 AM, Ian Kelly  wrote:

> On Sat, Nov 8, 2014 at 3:31 PM, Gregory Ewing
>  wrote:
> > (BTW, I'm actually surprised that this technique makes c callable.
> > There must be more going on that just "look up __call__ in the class
> > object", because evaluating C.__call__ just returns the descriptor
> > and doesn't invoking the descriptor mechanism.)
>
> But of course it doesn't just lookup C.__call__, because it has to
> bind the method to the instance before calling it, which means
> invoking the descriptor protocol. The actual lookup is more like:
>
> type(a).__dict__['__call__'].__get__(a, type(a))
> --
> https://mail.python.org/mailman/listinfo/python-list
>


As a reference, I recently found a blog post related to that:
http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/ (the
Slots part comments on that).

It does seem a bit counter-intuitive that this happens the way it does
though, so, can someone from python-dev give some background of why that's
the way it is? i.e.: instead of the approach which would seem simpler which
would do getattr(a, '__call__') instead of
type(a).__dict__['__call__'].__get__(a, type(a)) -- it seems to me it's
mostly because of historical reasons, but I'm really curious why is it so
(and if maybe it's something which python-dev would consider worth changing
in the future -- not sure how much could break because of that though).

Thanks and Best Regards,

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


Re: html page mail link to webmail program

2014-11-12 Thread Jerry Hill
On Tue, Nov 11, 2014 at 8:04 PM, Ethan Furman  wrote:
> My wife (using a Win7 machine) will be on a web page that has a link to mail
> somebody.  She clicks on it, and it opens the currently installed but unused
> Thunderbird.

As others have mentioned, this is more a question of configuring your
browser than anything involving python.

That said, those links on a web page that open an email window are
called "mailto" links.  A google search for "open mailto links in
gmail" (without the quotes) gets a bunch of general information, and
if you add your wife's browser of choice to the search terms, you
should get some explicit instructions for setting everything up
properly.

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-12 Thread Larry Martell
On Tue, Nov 11, 2014 at 10:48 AM, Larry Martell  wrote:
> I have a PHP app that I want to convert to django. But I want to do it
> stages. All the heavy lifting is in the PHP code, so first, I want to
> just use templates and views to generate the HTML, but still call the
> PHP code. Then later convert the PHP to python.
>
> My issue is that the PHP code expects to get all it's input from the
> REQUEST object and I've consumed that in the view. Is there any way I
> can somehow supply that to the PHP code?
>
> Is there some way python can communicate like curl ... it needs to
> send the request string in the body of a POST request to the URL that
> will route to the PHP script and get the output back.

We were all making this much harder than it is. I ended up doing this:

wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode())
pw = wp.read()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-12 Thread Michael Torrie
On 11/11/2014 10:30 AM, Larry Martell wrote:
> They are technically savvy. They are a 100% PHP shop. They have a big,
> complicated app that they've been working on for 10 years. No one
> there knows python or django. They want to put some new frontends on
> their app. I was bought in for another project (involving Google Tag
> Manager and Google Analytics), which I completed. Then they asked me
> about this project. I told them they should redo their app in Flask or
> Django.

Hmm, this is a red flag to me (unlike the other red flags others have
seen!).  If the shop is entire a PHP shop, and no one knows python, then
rewriting things in Python and Django is a really bad idea.  Who is
going to maintain the code after you're gone?  PHP might be a horrible
and insecure language, but at least they have a whole team of folks who
can hack on it.  With Python it seems like you are the only one.  In
this case, I'd say Python and Django, however superior, are not
appropriate.  I've worked in shops before where one person comes in with
a new language, writes some code, then leaves, leaving us stranded as it
were.  I'd say the same thing about Linux in an all-Windows shop.

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 1:56 AM, Skip Montanaro
 wrote:
> sys.excepthook = autoload_exc
>
> I can't see a lot of people wanting this (I normally have its import
> commented out in my PYTHONSTARTUP file), and I think it would probably
> be bad practice for new users of the language.

Interesting data point there - that you actually have it handy and
choose not to use it. It's clearly designed for interactive mode, as
it assumes that it can restart entire blocks of code:

>>> for x in (1,2,3):
...  print x
...  if x==2: print os.pathsep
...
1
2
autoloading os
1
2
:
3

But that's about as good a "now go try this again" as will ever be
achieved with sys.excepthook, I expect.

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 2:16 AM, Dave Angel  wrote:
> I gave it a short whirl, just trying to make __missing__ work.
>
> The type of globals () is a dict. I was able to add a
>  __missing__:myfunct to the instance but in order to work, the
>  __missing__ must be added as a class attribute,  a method. And
>  dict, being implemented in C, doesn't let you add class
>  attributes. Presumably the C code does the equivalent of
>  slots.

Yeah, I tried doing some of that kind of work and failed. Was hoping
someone with more knowledge of internals could pull it off.

> So the next thing to try would be to try to force the module
>  dictionary to be a userdict without slots. Then we could add the
>  necessary method. But that would be changing the python source. I
>  wasn't sure that was within the challenge constraints.

Haha! Well, unless we can convince people that this would really be a
good feature (which, somehow, I doubt...), not really. Though if it
can be enabled with a tiny patch to Python and then most of the magic
worked in PYTHONSTARTUP, that might do... but I suspect it'd need to
be fairly specifically coded.

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


Converting a PHP app to Python + Django (was: Communicating with a PHP script (and pretending I'm a browser))

2014-11-12 Thread Ben Finney
Michael Torrie  writes:

> If the shop is entire a PHP shop, and no one knows python, then
> rewriting things in Python and Django is a really bad idea.

It can be done well; see “Transitioning from PHP to Django on the sly”
http://pyvideo.org/video/2233/transitioning-from-php-to-django-on-the-sly>.

The presenter emphasises that one of the more important requirements is
to convince everyone: the management, the developers, even stakeholder
customers/users.

> I've worked in shops before where one person comes in with a new
> language, writes some code, then leaves, leaving us stranded as it
> were.

Right. On the other hand, I've worked in shops where the big PHP code
base is seen by all as a legacy code base, and the stakeholders were
quite open to being convinced to migrate — provided a clear migration
path.

That's what the above presentation goes into. I recommend it.

-- 
 \ “The double standard that exempts religious activities from |
  `\   almost all standards of accountability should be dismantled |
_o__)   once and for all.” —Daniel Dennett, 2010-01-12 |
Ben Finney

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Skip Montanaro
On Wed, Nov 12, 2014 at 12:49 PM, Chris Angelico  wrote:
> Interesting data point there - that you actually have it handy and
> choose not to use it.

And, I believe I wrote it. Can't have a worse recommendation than
that. A cook who doesn't eat his own cooking. :-) I think I disabled
its import sometime in the distant past when it interacted badly with
something else, but for the life of me, I can't remember the details
anymore.

I will occasionally paste functions from Python source files into the
interactive interpreter. This autoload functionality can be kind of
handy there so you don't have to go back and also grab the imports
from the top of the source file.

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


Re: __missing__ for the top-level Python script

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 5:09 AM, Skip Montanaro
 wrote:
> On Wed, Nov 12, 2014 at 12:49 PM, Chris Angelico  wrote:
>> Interesting data point there - that you actually have it handy and
>> choose not to use it.
>
> And, I believe I wrote it. Can't have a worse recommendation than
> that. A cook who doesn't eat his own cooking. :-) I think I disabled
> its import sometime in the distant past when it interacted badly with
> something else, but for the life of me, I can't remember the details
> anymore.

It doesn't ideally handle loops, as it'll go back to the top of the
loop - that was my first thought. As it has to go and exec stuff all
over again, it's entirely possible it'll have other issues.

> I will occasionally paste functions from Python source files into the
> interactive interpreter. This autoload functionality can be kind of
> handy there so you don't have to go back and also grab the imports
> from the top of the source file.

Yeah, that does help. Of course, it can't handle a from import, but I
wouldn't expect anything to catch those.

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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-12 Thread Marko Rauhamaa
Michael Torrie :

> I've worked in shops before where one person comes in with a new
> language, writes some code, then leaves, leaving us stranded as it
> were.

Programming languages come and go. If you can handle a Philips
screwdriver, you should be able to learn the use of a Torq screwdriver
within a few weeks of open-minded study.


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


Re: [Python-Dev] Dinamically set __call__ method

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 8:33 AM, Fabio Zadrozny  wrote:
> As a reference, I recently found a blog post related to that:
> http://lucumr.pocoo.org/2014/8/16/the-python-i-would-like-to-see/ (the Slots
> part comments on that).
>
> It does seem a bit counter-intuitive that this happens the way it does
> though, so, can someone from python-dev give some background of why that's
> the way it is? i.e.: instead of the approach which would seem simpler which
> would do getattr(a, '__call__') instead of
> type(a).__dict__['__call__'].__get__(a, type(a)) -- it seems to me it's
> mostly because of historical reasons, but I'm really curious why is it so
> (and if maybe it's something which python-dev would consider worth changing
> in the future -- not sure how much could break because of that though).

I'm not "someone from python-dev", but I think it's done to keep the
look-up logic predictable and avoid having to call __getattribute__
and __getattr__ when looking up magic methods. For at least
__getattribute__ and __getattr__ themselves we *can't* invoke those
methods while trying to look them up, so there's a case to be made for
consistency in that this way we don't have to remember which magic
methods use __getattribute__ and which ones don't. Performance is also
part of it, since these methods tend to be invoked frequently.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Converting a PHP app to Python + Django (was: Communicating with a PHP script (and pretending I'm a browser))

2014-11-12 Thread Larry Martell
On Wed, Nov 12, 2014 at 12:54 PM, Ben Finney  wrote:
> Michael Torrie  writes:
>
>> If the shop is entire a PHP shop, and no one knows python, then
>> rewriting things in Python and Django is a really bad idea.
>
> It can be done well; see “Transitioning from PHP to Django on the sly”
> http://pyvideo.org/video/2233/transitioning-from-php-to-django-on-the-sly>.
>
> The presenter emphasises that one of the more important requirements is
> to convince everyone: the management, the developers, even stakeholder
> customers/users.
>
>> I've worked in shops before where one person comes in with a new
>> language, writes some code, then leaves, leaving us stranded as it
>> were.
>
> Right. On the other hand, I've worked in shops where the big PHP code
> base is seen by all as a legacy code base, and the stakeholders were
> quite open to being convinced to migrate — provided a clear migration
> path.
>
> That's what the above presentation goes into. I recommend it.

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


Re: ssl error with the python mac binary

2014-11-12 Thread Ned Deily
In article 
,
 Paul Wiseman  wrote:
> I'm currently using the installer with py2app to make a distributable
> app that targets 10.5+ (including ppc). To save having more than one
> build I use this for all downloads. Although I'm starting to consider
> making a second 32/64 distributable. Are there many major drawbacks
> for distributing this i386/ppc binary for all versions of OSX up 10.9
> and 10.10?

For a standalone app, not really.  The main difference is that, by using 
the older 10.5 ABI, a few functions in the os module are not available 
(if they were implemented first in OS X 10.6 or later) and/or they may 
work a little differently.  AFAIK, the most impactful difference, by 
far, is the OpenSSL version difference you have run into.  Up to now, I 
don't recall any compatibility problems with 10.5 ABI programs running 
on later versions of OS X or, for the most part, mixing extension 
modules compiled to later ABIs with a 10.5 Python, although there might 
be issues with mixing versions of C++ modules (Python and its standard 
library do not use C++ themselves).  But, of course, there's no 
guarantee that something won't break in a future release of OS X.  So 
far, so good.

> That's great news! Thanks for this! I've always found building things
> on mac a huge pain and wasn't much looking forward to the prospect of
> trying to build a 32/ppc python build on a 64 bit 10.10 machine (would
> that even be possible?).

It's possible: I do it.  But I cheat a bit: I have 10.5 running in a 
virtual machine on a 10.10 host.  In theory, it's possible to build 
natively on 10.10.  The trick is getting a version of Xcode 3 installed 
on 10.10 since support for building ppc archs was removed in Xcode 4.  I 
also cheat a bit there: I happen to still have copies of Xcode 3.1.4 and 
3.2.6 installed on 10.10 because I made sure to preserve them through 
upgrades from 10.6 days.  IIRC, directly installing the necessary 
components from 3.2.6 on newer systems would require some hacking.  Then 
you have to be really vigilant that the build never strays from the old 
SDK and tools, which is not something we claim to support at the moment.  
The VM approach is quite safe and reliable.

-- 
 Ned Deily,
 [email protected]

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


Re: Moving a window on the screen

2014-11-12 Thread Terry Reedy

On 11/8/2014 3:31 PM, Akira Li wrote:

Terry Reedy  writes:



On my Win7 machine, your complicated code is much worse as it causes
the window to jump about every half second


After cutting and pasting again, I do not see the jumps. I do not have 
the code I ran before to compare.  I do remember that I deleted, added 
back, and re-deleted the phase correction, and ran a couple of times 
each, to be sure that the aberrant behavior was reproducible in general 
effect.


--
Terry Jan Reedy

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


Re: Python Style Question

2014-11-12 Thread Anton
On Thursday, October 30, 2014 4:10:23 AM UTC-7, Steven D'Aprano wrote:
> I don't particularly like either version. I prefer this:
> 
> def load_int(obj):
> if isinstance(obj, int):
> # Case 1), an int, e.g. 7
> return obj

> elif isinstance(obj, str):
> # Case 2) and 3), a str or JSON serialised int.
> # E.g. '7' or '"7"'.
> try:
> return int(obj)
> except ValueError:
> return int(json.loads(obj))
> raise TypeError('require int or str, got %s' % type(obj).__name__)

This will definitely work, but then I don't see a benefit of EAFP and 
duck-typing: 
Let's say I have a class 
class FakeInt(object):
   def __int__(self):
  return 42

In this case:
>>> fi = FakeInt()
>>> isinstance(fi, int)
False
>>> int(fi)
42

So probably I need to rephrase 1) something, that I can cast to int.

Same for 
> elif isinstance(obj, str):
As long as it behaves like string (can be some sort if bytearray). For 
particularly this case, it will probably won't happen, but again, it looks like 
an overloaded function with strongly typed argument.

or a functional form:

> def tolerant_load_int(obj, default=None):
> try:
> return load_int(obj)
> except (ValueError, TypeError):
> return default

> values = [n for n in map(tolerant_load_int, l) if n is not None]

> # alternative to using map
> values = [n for n in (tolerant_load_int(obj) for obj in l) if n is not None] 

I like the idea of wrapping it up in a function and being able to use it in 
these functional forms.

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


Re: I love assert

2014-11-12 Thread Anton
On Tuesday, November 11, 2014 11:41:06 AM UTC-8, Peter Cacioppi wrote:
> I get the impression that most Pythonistas aren't as habituated with assert 
> statements as I am. Is that just a misimpression on my part? If not, is there 
> a good reason to assert less with Python than other languages?
> 
> As far as I can tell, Python supports assert perfectly well. When run with 
> the optimization flagging, the asserts are truly removed.
> 
> I think one needs to take care with some basic assert coding - it's not a 
> substitute for unit tests, it doesn't absolve you of normal exception 
> responsibilities, and, most of all, it should be used for passive inspection 
> and not action. But given these guidelines, I still find it very useful as 
> "active comments".

I am not sure how and when you use assert, but something that stops me from 
using assert is that in many cases I would use them to 
1) Check type of an incoming argument/returned value
2) Check value of an incoming argument/returned value
But the issues I can see here is that assert throws AssertError, while there is 
a specialized error for each of the case: 1) TypeError 2) ValueError.
Moreover for the 1) case it makes it impossible to dynamically substitute an 
object with another object that implements the same interface.
-- 
https://mail.python.org/mailman/listinfo/python-list


How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread John Ladasky
I have taught Python to several students over the past few years.  As I have 
worked with my students, I find myself bothered by the programming idiom that 
we use to determine whether a module is being executed or merely imported:

  "if __name__ == '__main__':"

The use of two dunder tokens -- one as a name in a namespace, and the other as 
a string, is intimidating.  It exposes too much of Python's guts.  As such, I 
think that it is less Pythonic than we might want.  Myself, I've been 
programming in Python for a decade, and I still haven't dug very deeply into 
what exactly __name__ means or does.

I would like to start a discussion about whether Python should include a 
function which executes this evaluation, and hides all of the unfriendly 
dunderish details.  And if that's a good idea, I would invite a discussion of 
how, exactly, it should be implemented.  I'm nowhere near proposing a PEP, but 
that may come later.

Thanks for your thoughts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Joel Goldstick
On Wed, Nov 12, 2014 at 4:02 PM, John Ladasky
 wrote:
> I have taught Python to several students over the past few years.  As I have 
> worked with my students, I find myself bothered by the programming idiom that 
> we use to determine whether a module is being executed or merely imported:
>
>   "if __name__ == '__main__':"
>
> The use of two dunder tokens -- one as a name in a namespace, and the other 
> as a string, is intimidating.  It exposes too much of Python's guts.  As 
> such, I think that it is less Pythonic than we might want.  Myself, I've been 
> programming in Python for a decade, and I still haven't dug very deeply into 
> what exactly __name__ means or does.
>
> I would like to start a discussion about whether Python should include a 
> function which executes this evaluation, and hides all of the unfriendly 
> dunderish details.  And if that's a good idea, I would invite a discussion of 
> how, exactly, it should be implemented.  I'm nowhere near proposing a PEP, 
> but that may come later.
>
> Thanks for your thoughts.
> --
> https://mail.python.org/mailman/listinfo/python-list

How about a decorator?

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread John Ladasky
It appears that I'm not the first person to have thoughts along these lines.  
Here's a relevant article:

http://aliles.tumblr.com/post/7455032885/sugar-for-pythons-main
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Ethan Furman

On 11/12/2014 01:02 PM, John Ladasky wrote:


I would like to start a discussion about whether Python should include
 a function which executes this evaluation, and hides all of the unfriendly
 dunderish details.  And if that's a good idea, I would invite a discussion
 of how, exactly, it should be implemented.  I'm nowhere near proposing a
 PEP, but that may come later.


I believe this has come up before.  You might check the Python-Ideas list to see.  If you do, please write up a summary 
of the past discussions so we can move forward instead of rehashing the same things as before.


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


Re: Communicating with a PHP script (and pretending I'm a browser)

2014-11-12 Thread Michael Torrie
On 11/12/2014 11:37 AM, Marko Rauhamaa wrote:
> Michael Torrie :
> 
>> I've worked in shops before where one person comes in with a new
>> language, writes some code, then leaves, leaving us stranded as it
>> were.
> 
> Programming languages come and go. If you can handle a Philips
> screwdriver, you should be able to learn the use of a Torq screwdriver
> within a few weeks of open-minded study.

Sure, but that's not a good enough reason to switch to Python, as
excellent as it is.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Chris Kaynor
On Wed, Nov 12, 2014 at 1:07 PM, Joel Goldstick 
wrote:

> On Wed, Nov 12, 2014 at 4:02 PM, John Ladasky
>  wrote:
> > I have taught Python to several students over the past few years.  As I
> have worked with my students, I find myself bothered by the programming
> idiom that we use to determine whether a module is being executed or merely
> imported:
> >
> >   "if __name__ == '__main__':"
> >
> > The use of two dunder tokens -- one as a name in a namespace, and the
> other as a string, is intimidating.  It exposes too much of Python's guts.
> As such, I think that it is less Pythonic than we might want.  Myself, I've
> been programming in Python for a decade, and I still haven't dug very
> deeply into what exactly __name__ means or does.
> >
> > I would like to start a discussion about whether Python should include a
> function which executes this evaluation, and hides all of the unfriendly
> dunderish details.  And if that's a good idea, I would invite a discussion
> of how, exactly, it should be implemented.  I'm nowhere near proposing a
> PEP, but that may come later.
> >
> > Thanks for your thoughts.
>
> How about a decorator?
>

A decorator is an interesting idea, and should be easy to implement (only
lightly tested):

def main(func):
if func.__module__ == "__main__":
func()
return func # The return could be omitted to block the function from
being manually called after import.

Just decorate the "main" function of the script with that, and it will be
automatically called when ran as a script, but not when imported as a
module.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Anton :

> I am not sure how and when you use assert, but something that stops me
> from using assert is that in many cases I would use them to
> 1) Check type of an incoming argument/returned value
> 2) Check value of an incoming argument/returned value

You use asserts to boldly state that the asserted condition never fails.
If it should fail anyway, the world could come tumbling down and you
would hang your head in shame.

Asserts help the reader of the code understand why some possibilities
are not considered by the code. They are not considered because the
writer of the code asserts they are not really possible.

Asserts help not only lay the blame to the writer of the code but might
also make it easier to troubleshoot failures.

I use asserts sparingly, just like comments (which asserts are). I use
them to communicate nonobvious truths to the future maintainer of the
code.

For example, instead of

 # never reached

I will write

 assert False


Or I might indicate the exhaustion of possibilities:

 if status == OK:
 ...
 elif status == ERROR:
 ...
 else:
 assert status == WARNING
 ...


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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor  wrote:
> A decorator is an interesting idea, and should be easy to implement (only
> lightly tested):
>
> def main(func):
> if func.__module__ == "__main__":
> func()
> return func # The return could be omitted to block the function from
> being manually called after import.
>
> Just decorate the "main" function of the script with that, and it will be
> automatically called when ran as a script, but not when imported as a
> module.

This calls it at the wrong time, though. Typically the way this idiom
is used is that you define everything you need (functions, classes,
etc.) within the main script, and then you call the main function.
This would call the main function at the time it's defined, when other
things in the main script may not have been defined yet. One could
place the main function last, but it would be preferable not to be
forced.

This also calls the function before it's been assigned to the global,
which would prevent recursive calls of the main function.

Instead of a decorator, I'd prefer to just have this:

def main(func, *args, **kwargs):
if func.__module__ == '__main__':
func(*args, **kwargs)

And then I can easily invoke it wherever I want in the main script.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Ethan Furman

On 11/12/2014 01:41 PM, Marko Rauhamaa wrote:


Or I might indicate the exhaustion of possibilities:

  if status == OK:
  ...
  elif status == ERROR:
  ...
  else:
  assert status == WARNING
  ...


And here's a nice example of what one should NOT do.  Imagine that a new status, CONFUSED is added, the above code is 
not modified to handle it, and for whatever reason the program is being run optimized -- the assert is not there, and 
CONFUSED is treated the same as WARNING.


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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Marko Rauhamaa
John Ladasky :

> I find myself bothered by the programming idiom that we use to
> determine whether a module is being executed or merely imported:
>
>   "if __name__ == '__main__':"

I find the idiom cute and loveably silly. A typing tongue twister of
sorts. That boilerplate is far less cumbersome than, say, in Java.

> Myself, I've been programming in Python for a decade, and I still
> haven't dug very deeply into what exactly __name__ means or does.

The idiom allows you to include a main function in auxiliary modules.
When imported, the module acts as a library. When executed, it acts as a
command. I have done this a couple of times IRL.

> I would like to start a discussion about whether Python should include
> a function which executes this evaluation, and hides all of the
> unfriendly dunderish details.

Probably not. Idioms are important in that they are immediately spotted
by a casual reader of the code. However ugly you consider those two
lines, it will not waste a measurable amount of your precious time to
begin your brand new project by typing:

   import sys

   def main():
   pass

   if __name__ == "__main__":
   main()


Yes, I always type those in again. I don't copy them over as I do, say,
Java main programs or static HTML pages.


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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Skip Montanaro
> def main(func):
> if func.__module__ == "__main__":
> func()
> return func # The return could be omitted to block the function from
> being manually called after import.
>
> Just decorate the "main" function of the script with that, and it will be
> automatically called when ran as a script, but not when imported as a
> module.

This won't work (I don't think) if you want to call the "main"
function from another place (like the interpreter prompt).

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


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Ethan Furman :

> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote:
>>
>> Or I might indicate the exhaustion of possibilities:
>>
>>   if status == OK:
>>   ...
>>   elif status == ERROR:
>>   ...
>>   else:
>>   assert status == WARNING
>>   ...
>
> And here's a nice example of what one should NOT do. Imagine that a
> new status, CONFUSED is added, the above code is not modified to
> handle it, and for whatever reason the program is being run optimized
> -- the assert is not there, and CONFUSED is treated the same as
> WARNING.

How would it be better if you removed the assert then?


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


Re: I love assert

2014-11-12 Thread Anton
On Wednesday, November 12, 2014 2:00:35 PM UTC-8, Anton wrote:
> On Wednesday, November 12, 2014 1:41:20 PM UTC-8, Marko Rauhamaa wrote:
> > Asserts help the reader of the code understand why some possibilities
> > are not considered by the code. They are not considered because the
> > writer of the code asserts they are not really possible.
> I can see how assert statement can point out what should not happen, can you 
> give an example. 

I messed up, meant to say:
I can see how assert statement can point out what should not happen, can you 
give an example when a single assert statement would explain why it should 
never happen?



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


Re: I love assert

2014-11-12 Thread Anton
On Wednesday, November 12, 2014 1:41:20 PM UTC-8, Marko Rauhamaa wrote:
> Asserts help the reader of the code understand why some possibilities
> are not considered by the code. They are not considered because the
> writer of the code asserts they are not really possible.
I can see how assert statement can point out what should not happen, can you 
give an example. 

> I use asserts sparingly, just like comments (which asserts are). I use
> them to communicate nonobvious truths to the future maintainer of the
> code.
> 
> Or I might indicate the exhaustion of possibilities:
> 
>  if status == OK:
>  ...
>  elif status == ERROR:
>  ...
>  else:
>  assert status == WARNING
>  ...
Could you elaborate your example here? Basically, this type of error checking 
does not look familiar to me in Python code. In C when one works with 
descriptors and has to check status codes after every call it looks natural. 
Maybe I just haven't used it this way, so I'd really appreciate a more specific 
use case.

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


Re: I love assert

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa  wrote:
> Ethan Furman :
>
>> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote:
>>>
>>> Or I might indicate the exhaustion of possibilities:
>>>
>>>   if status == OK:
>>>   ...
>>>   elif status == ERROR:
>>>   ...
>>>   else:
>>>   assert status == WARNING
>>>   ...
>>
>> And here's a nice example of what one should NOT do. Imagine that a
>> new status, CONFUSED is added, the above code is not modified to
>> handle it, and for whatever reason the program is being run optimized
>> -- the assert is not there, and CONFUSED is treated the same as
>> WARNING.
>
> How would it be better if you removed the assert then?

You don't need to remove it. Just reorganize it to make sure it
indicates actual exhaustion of possibilities. E.g. using the "assert
False" pattern from your post:

if status == OK:
...
elif status == ERROR:
...
elif status == WARNING:
...
else:
assert False
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Chris Kaynor
On Wed, Nov 12, 2014 at 1:51 PM, Ian Kelly  wrote:

> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor 
> wrote:
> > A decorator is an interesting idea, and should be easy to implement (only
> > lightly tested):
> >
> > def main(func):
> > if func.__module__ == "__main__":
> > func()
> > return func # The return could be omitted to block the function from
> > being manually called after import.
> >
> > Just decorate the "main" function of the script with that, and it will be
> > automatically called when ran as a script, but not when imported as a
> > module.
>
> This calls it at the wrong time, though. Typically the way this idiom
> is used is that you define everything you need (functions, classes,
> etc.) within the main script, and then you call the main function.
> This would call the main function at the time it's defined, when other
> things in the main script may not have been defined yet. One could
> place the main function last, but it would be preferable not to be
> forced.
>
>
I was thinking along the lines of replacing:

if __name__ == "__main__":
<<>>

with

@main
def myFunction()
<<<>

Both blocks of code will be called at the same time.


> This also calls the function before it's been assigned to the global,
> which would prevent recursive calls of the main function.
>
> Instead of a decorator, I'd prefer to just have this:
>
> def main(func, *args, **kwargs):
> if func.__module__ == '__main__':
> func(*args, **kwargs)
>
> And then I can easily invoke it wherever I want in the main script.



> On Wed, Nov 12, 2014 at 1:55 PM, Skip Montanaro 
 wrote:
>
> This won't work (I don't think) if you want to call the "main"

function from another place (like the interpreter prompt).


With the plain if block, you absolutely cannot call it elsewhere, without
wrapping it in a function anyways.

There is the issue, as mentioned by Ian, that the function will not be in
the module namespace at the time it is called. That does block it, however
it is also easy to work around: make the main function extremely simple,
such as just calling another function.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 3:04 PM, Ian Kelly  wrote:
> On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa  wrote:
>> How would it be better if you removed the assert then?
>
> You don't need to remove it. Just reorganize it to make sure it
> indicates actual exhaustion of possibilities. E.g. using the "assert
> False" pattern from your post:
>
> if status == OK:
> ...
> elif status == ERROR:
> ...
> elif status == WARNING:
> ...
> else:
> assert False

Although to be honest I'd rather use something like "raise
RuntimeError('Unreachable code reached')" than "assert False" here. If
the expectation is that the code will never be executed, then there's
no reason to ever optimize it out.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Anton
On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote:
> On Wed, Nov 12, 2014 at 2:56 PM, Marko Rauhamaa wrote:
> > Ethan Furman:
> >
> >> On 11/12/2014 01:41 PM, Marko Rauhamaa wrote:
> >>>
> >>> Or I might indicate the exhaustion of possibilities:
> >>>
> >>>   if status == OK:
> >>>   ...
> >>>   elif status == ERROR:
> >>>   ...
> >>>   else:
> >>>   assert status == WARNING
> >>>   ...
> >>
> >> And here's a nice example of what one should NOT do. Imagine that a
> >> new status, CONFUSED is added, the above code is not modified to
> >> handle it, and for whatever reason the program is being run optimized
> >> -- the assert is not there, and CONFUSED is treated the same as
> >> WARNING.
> >
> > How would it be better if you removed the assert then?
> 
> You don't need to remove it. Just reorganize it to make sure it
> indicates actual exhaustion of possibilities. E.g. using the "assert
> False" pattern from your post:
> 
> if status == OK:
> ...
> elif status == ERROR:
> ...
> elif status == WARNING:
> ...
> else:
> assert False

If the code is run optimized and asserts are ignore CONFUSED statement would 
still not be handled and you will not know about it.
I would do something like:

if status == OK:
...
elif status == ERROR:
...
elif status == WARNING:
...
else:
raise RuntimeError("Unknown errorno")

Or if it is at the end of the function, then:

if status == OK:
...
elif status == ERROR:
...
elif status == WARNING:
...

raise RuntimeError("Unknown errorno")

unless there is a customer exception type I can use for this situation.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 3:09 PM, Chris Kaynor  wrote:
> I was thinking along the lines of replacing:
>
> if __name__ == "__main__":
> <<>>
>
> with
>
> @main
> def myFunction()
> <<<>
>
> Both blocks of code will be called at the same time.

99% of the time the content of <<>> is just "main()",
so then you're proposing replacing this:

if __name__ == "__main__":
main()

with this:

@main
def myFunction():
my_main()

Which feels redundant to me. Why have a function here that does
nothing but call another function?

I think if this is the goal then a simple predicate would be clearer:

if is_main_module():
main()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Anton :

> I can see how assert statement can point out what should not happen,
> can you give an example when a single assert statement would explain
> why it should never happen?

Asserts don't communicate justifications. They simply assert something
to be the case, period. Any other elaborations must go in comments.


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


Re: I love assert

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 3:13 PM, Anton  wrote:
> On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote:
>> You don't need to remove it. Just reorganize it to make sure it
>> indicates actual exhaustion of possibilities. E.g. using the "assert
>> False" pattern from your post:
>>
>> if status == OK:
>> ...
>> elif status == ERROR:
>> ...
>> elif status == WARNING:
>> ...
>> else:
>> assert False
>
> If the code is run optimized and asserts are ignore CONFUSED statement would 
> still not be handled and you will not know about it.
> I would do something like:

There's no way to make the CONFUSED status be handled without actually
changing the code. The difference is that this version will not
incorrectly treat CONFUSED as WARNING; it just won't do anything at
all if the code is optimized.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 7:53 AM, Anton  wrote:
> I am not sure how and when you use assert, but something that stops me from 
> using assert is that in many cases I would use them to
> 1) Check type of an incoming argument/returned value
> 2) Check value of an incoming argument/returned value
> But the issues I can see here is that assert throws AssertError, while there 
> is a specialized error for each of the case: 1) TypeError 2) ValueError.
> Moreover for the 1) case it makes it impossible to dynamically substitute an 
> object with another object that implements the same interface.

The fact that there's a better exception type that's obviously more
correct is a strong hint that you shouldn't use assert for these two
cases. And your "Moreover" concern is a strong hint that you shouldn't
be checking at all :)

If you need to check this sort of thing, an explicit "if condition:
raise SomeError('message')" construct is a lot more useful. Otherwise,
there's no reason to have the line of code at all.

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


Re: I love assert

2014-11-12 Thread Ethan Furman

On 11/12/2014 02:41 PM, Ian Kelly wrote:

On Wed, Nov 12, 2014 at 3:13 PM, Anton  wrote:

On Wednesday, November 12, 2014 2:05:17 PM UTC-8, Ian wrote:

You don't need to remove it. Just reorganize it to make sure it
indicates actual exhaustion of possibilities. E.g. using the "assert
False" pattern from your post:

if status == OK:
 ...
elif status == ERROR:
 ...
elif status == WARNING:
 ...
else:
 assert False


If the code is run optimized and asserts are ignore CONFUSED statement would 
still not be handled and you will not know about it.
I would do something like:


There's no way to make the CONFUSED status be handled without actually
changing the code. The difference is that this version will not
incorrectly treat CONFUSED as WARNING; it just won't do anything at
all if the code is optimized.


So, a different wrong thing, but still a wrong thing.  ;)

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


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Ian Kelly :

> Although to be honest I'd rather use something like "raise
> RuntimeError('Unreachable code reached')" than "assert False" here. If
> the expectation is that the code will never be executed, then there's
> no reason to ever optimize it out.

Asserts have nothing to do with them being optimized out. Asserts are
communication.

Apart from idiomatic style, there is no difference between

# never reached

assert False

raise RuntimeError('Unreachable code reached')

1 / 0

print("Hello world")

since, after all, that line is never reached!

Out of these variants, I find

assert False

to be the most tasteful. It is concise, to the point and provided by the
core language. If it didn't exist, I'd have to resort to one of the
other alternatives.


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


Re: I love assert

2014-11-12 Thread Anton
On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote:
> On Wed, Nov 12, 2014 at 3:13 PM, Anton  wrote:
> > If the code is run optimized and asserts are ignore CONFUSED statement 
> > would still not be handled and you will not know about it.
> > I would do something like:
> 
> There's no way to make the CONFUSED status be handled without actually
> changing the code. The difference is that this version will not
> incorrectly treat CONFUSED as WARNING; it just won't do anything at
> all if the code is optimized.

Right, but the goal is not to make the CONFUSED status be handled without 
coding, but to be notified about an unknown status code and act accordingly.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Ethan Furman

On 11/12/2014 02:47 PM, Marko Rauhamaa wrote:

Ian Kelly :


Although to be honest I'd rather use something like "raise
RuntimeError('Unreachable code reached')" than "assert False" here. If
the expectation is that the code will never be executed, then there's
no reason to ever optimize it out.


Asserts have nothing to do with them being optimized out. Asserts are
communication.


Asserts are code that can stop your program.  That's a bit more than just communication.  And your example of how you 
use asserts shows a bad way to use them, which has been explained.  Apparently you refuse to learn from that, but 
hopefully somebody else will.


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


Re: I love assert

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 9:47 AM, Marko Rauhamaa  wrote:
> Apart from idiomatic style, there is no difference between
>
> # never reached
>
> assert False
>
> raise RuntimeError('Unreachable code reached')
>
> 1 / 0
>
> print("Hello world")
>
> since, after all, that line is never reached!

If it truly is never reached, there's no difference between any of the
above and "pass". (With the possible exception of 1/0, which might
plausibly be optimized to a constant, which would mean it'd throw an
error at compile time.) But what if, one day, it is reached? What
should happen? RuntimeError implies that there's an error that
couldn't be detected until run time. AssertionError might not get
raised. Printing "Hello world" to standard out will almost certainly
be misinterpreted. ZeroDivisionError makes almost no sense for
"shouldn't happen". Think about what your code ought to do *if it is
reached*, because if you really don't care about that case, you won't
have a line of code at all.

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


Re: I love assert

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 3:48 PM, Anton  wrote:
> On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote:
>> On Wed, Nov 12, 2014 at 3:13 PM, Anton  wrote:
>> > If the code is run optimized and asserts are ignore CONFUSED statement 
>> > would still not be handled and you will not know about it.
>> > I would do something like:
>>
>> There's no way to make the CONFUSED status be handled without actually
>> changing the code. The difference is that this version will not
>> incorrectly treat CONFUSED as WARNING; it just won't do anything at
>> all if the code is optimized.
>
> Right, but the goal is not to make the CONFUSED status be handled without 
> coding, but to be notified about an unknown status code and act accordingly.

Sure, which is why you and I have both suggested raising a RuntimeError instead.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Anton :

> Right, but the goal is not to make the CONFUSED status be handled
> without coding, but to be notified about an unknown status code and
> act accordingly.

Asserts are not about notification, checking or optimization. They are
about communicating what's going on in the programmer's mind. They are
comments.

So why use asserts instead of comments?

Asserts *could* help in fixing bugs:

  1. An assertion failure immediately, unambiguously, declares even to
 customer service representatives that this is a terrible bug and
 should be brought to R&D's attention instead of hazing the poor
 customer with standard questions ("have you updated?", "have you
 rebooted?").

  2. An assertion failure probably gives the developer an very good clue
 as to what has gone wrong. There is a good chance of quickly
 finding an accurate analysis and fix to the bug.


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


Re: I love assert

2014-11-12 Thread Ian Kelly
On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa  wrote:
> Ian Kelly :
>
>> Although to be honest I'd rather use something like "raise
>> RuntimeError('Unreachable code reached')" than "assert False" here. If
>> the expectation is that the code will never be executed, then there's
>> no reason to ever optimize it out.
>
> Asserts have nothing to do with them being optimized out. Asserts are
> communication.
>
> Apart from idiomatic style, there is no difference between
>
> # never reached
>
> assert False
>
> raise RuntimeError('Unreachable code reached')

If the purpose is communication, then the comment is most effective,
as it can easily convey anything you want. If the purpose is to detect
programming errors, then the RuntimeError is most effective, as it
will always raise an error in the event it is reached.

assert False is a strange hybrid of the two that is less effective at
both purposes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I love assert

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 10:02 AM, Ian Kelly  wrote:
> On Wed, Nov 12, 2014 at 3:48 PM, Anton  wrote:
>> On Wednesday, November 12, 2014 2:42:19 PM UTC-8, Ian wrote:
>>> On Wed, Nov 12, 2014 at 3:13 PM, Anton  wrote:
>>> > If the code is run optimized and asserts are ignore CONFUSED statement 
>>> > would still not be handled and you will not know about it.
>>> > I would do something like:
>>>
>>> There's no way to make the CONFUSED status be handled without actually
>>> changing the code. The difference is that this version will not
>>> incorrectly treat CONFUSED as WARNING; it just won't do anything at
>>> all if the code is optimized.
>>
>> Right, but the goal is not to make the CONFUSED status be handled without 
>> coding, but to be notified about an unknown status code and act accordingly.
>
> Sure, which is why you and I have both suggested raising a RuntimeError 
> instead.

Or, in as many cases as possible, raise an implicit KeyError and save
yourself a lot of typing. Any time these kinds of elif trees can be
turned into dict lookups, you get non-assert error checking for free.

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


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Ian Kelly :

> On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa  wrote:
>> Asserts have nothing to do with them being optimized out. Asserts are
>> communication.
>>
>> Apart from idiomatic style, there is no difference between
>>
>> # never reached
>>
>> assert False
>>
>> raise RuntimeError('Unreachable code reached')
>
> If the purpose is communication, then the comment is most effective,
> as it can easily convey anything you want. If the purpose is to detect
> programming errors, then the RuntimeError is most effective, as it
> will always raise an error in the event it is reached.
>
> assert False is a strange hybrid of the two that is less effective at
> both purposes.

If assert weren't there, I would likely choose one of those two
alternatives. But assert is there so there's no reason to avoid it.


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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Terry Reedy

On 11/12/2014 4:02 PM, John Ladasky wrote:

I have taught Python to several students over the past few years.  As
I have worked with my students, I find myself bothered by the
programming idiom that we use to determine whether a module is being
executed or merely imported:

"if __name__ == '__main__':"

The use of two dunder tokens -- one as a name in a namespace, and the
other as a string, is intimidating.  It exposes too much of Python's
guts.  As such, I think that it is less Pythonic than we might want.
Myself, I've been programming in Python for a decade, and I still
haven't dug very deeply into what exactly __name__ means or does.

I would like to start a discussion about whether Python should
include a function which executes this evaluation, and hides all of
the unfriendly dunderish details.  And if that's a good idea, I would
invite a discussion of how, exactly, it should be implemented.  I'm
nowhere near proposing a PEP, but that may come later.


Functions have an implicit 'return None' at the end (which, in CPython, 
become an explicit pair of bytecodes, even when the function already 
ends with return something'.  The simplest proposal is that modules have 
an implicit "if __name__ == '__main__': main()" at the end.  I think 
this would not have to be added to the bytecode.


This magical invocation mimics C and some other languages, and I think 
it works well.


--
Terry Jan Reedy

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


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Chris Angelico :

> Or, in as many cases as possible, raise an implicit KeyError and save
> yourself a lot of typing. Any time these kinds of elif trees can be
> turned into dict lookups, you get non-assert error checking for free.

I agree that you shouldn't sprinkle asserts around the code. But
consider this example:

 count = next_size / len(choices)

The casual reader of the code might be left wondering if "choices" could
be zero-length and if the programmer had overlooked the possibility,
leading to a lengthy analysis and bewilderment.

However, the programmer could have played this frustration out already
in his head and written:

 assert len(choices) > 0
 count = next_size / len(choices)

or, equivalently:

 # here len(choices) > 0
 count = next_size / len(choices)

and the casual maintainer would be able to read on.


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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 10:19 AM, Terry Reedy  wrote:
> Functions have an implicit 'return None' at the end (which, in CPython,
> become an explicit pair of bytecodes, even when the function already ends
> with return something'.  The simplest proposal is that modules have an
> implicit "if __name__ == '__main__': main()" at the end.  I think this would
> not have to be added to the bytecode.
>
> This magical invocation mimics C and some other languages, and I think it
> works well.

Yes, but it conflicts with the existing and common usage of having
that explicitly in the code. Safer - and more in line with the way
other such functions are written - would be a dunder function:

if __name__ == '__main__': __main__()

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


Re: I love assert

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 10:23 AM, Marko Rauhamaa  wrote:
> However, the programmer could have played this frustration out already
> in his head and written:
>
>  assert len(choices) > 0
>  count = next_size / len(choices)

assert choices
count = next_size / len(choices)

Or even just:

count = next_size / len(choices) # choices won't be empty

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


Re: I love assert

2014-11-12 Thread Marko Rauhamaa
Chris Angelico :

> On Thu, Nov 13, 2014 at 10:23 AM, Marko Rauhamaa  wrote:
>> However, the programmer could have played this frustration out already
>> in his head and written:
>>
>>  assert len(choices) > 0
>>  count = next_size / len(choices)
>
> assert choices
> count = next_size / len(choices)
>
> Or even just:
>
> count = next_size / len(choices) # choices won't be empty

Precisely.


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


Re: I love assert

2014-11-12 Thread Anton
On Wednesday, November 12, 2014 3:03:18 PM UTC-8, Ian wrote:
> On Wed, Nov 12, 2014 at 3:48 PM, Anton  wrote:
> Sure, which is why you and I have both suggested raising a RuntimeError 
> instead.
Yeah, I actually read it after sending my response :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Terry Reedy

On 11/12/2014 6:26 PM, Chris Angelico wrote:

On Thu, Nov 13, 2014 at 10:19 AM, Terry Reedy  wrote:

Functions have an implicit 'return None' at the end (which, in CPython,
become an explicit pair of bytecodes, even when the function already ends
with return something'.  The simplest proposal is that modules have an
implicit "if __name__ == '__main__': main()" at the end.  I think this would
not have to be added to the bytecode.

This magical invocation mimics C and some other languages, and I think it
works well.


Yes, but it conflicts with the existing and common usage of having
that explicitly in the code.


Yeh, calling main twice could be a problem.


Safer - and more in line with the way
other such functions are written - would be a dunder function:

if __name__ == '__main__': __main__()


I presume you mean that calling __main__ implicitly would be both 
consistent and safer.  No code should be using that now.



--
Terry Jan Reedy

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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Chris Angelico
On Thu, Nov 13, 2014 at 11:35 AM, Terry Reedy  wrote:
>> Safer - and more in line with the way
>> other such functions are written - would be a dunder function:
>>
>> if __name__ == '__main__': __main__()
>
>
> I presume you mean that calling __main__ implicitly would be both consistent
> and safer.  No code should be using that now.

That's what I mean. Like changing iter.next() to iter.__next__() in
Py3, it'd be using a name that emphasizes that the interpreter, not
userland code, should be calling this function.

Of course, it'd still be optional. Top-level code would be executed
top-down, same as it now is.

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


Re: [Python-Dev] Dinamically set __call__ method

2014-11-12 Thread Gregory Ewing

Fabio Zadrozny wrote:
can someone from python-dev give some background of why 
that's the way it is?


It's because, with new-style classes, a class is also an
instance (of class "type" or a subclass thereof). So
without that rule, it would be ambiguous whether a dunder
method applied to instances of a class or to the class
itself.

> and if maybe it's something which python-dev would consider worth
changing in the future -- not sure how much could break because of that 
though


Something fairly fundamental that would break is classs
instantiation! You instantiate a class by calling it, so if
a(x) were implemented as a.__call__(x), and class C had
a __call__ method, then C() would invoke that method
instead of instantiating C.

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


SSLsocket.getpeercert - request to return ALL the fields of the certificate.

2014-11-12 Thread John Nagle
  In each revision of "getpeercert", a few more fields are returned.
Python 3.2 added "issuer" and "notBefore".  Python 3.4 added
"crlDistributionPoints", "caIssuers", and OCSP URLS. But some fields
still aren't returned.  I happen to need CertificatePolicies, which
is how you distinguish DV, OV, and EV certs.

   Here's what you get now:

{'OCSP': ('http://EVSecure-ocsp.verisign.com',),
 'caIssuers': ('http://EVSecure-aia.verisign.com/EVSecure2006.cer',),
 'crlDistributionPoints':
('http://EVSecure-crl.verisign.com/EVSecure2006.crl',),
 'issuer': ((('countryName', 'US'),),
(('organizationName', 'VeriSign, Inc.'),),
(('organizationalUnitName', 'VeriSign Trust Network'),),
(('organizationalUnitName',
  'Terms of use at https://www.verisign.com/rpa (c)06'),),
(('commonName', 'VeriSign Class 3 Extended Validation SSL
CA'),)),
 'notAfter': 'Mar 22 23:59:59 2015 GMT',
 'notBefore': 'Feb 20 00:00:00 2014 GMT',
 'serialNumber': '69A7BC85C106DDE1CF4FA47D5ED813DC',
 'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
 (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
 (('businessCategory', 'Private Organization'),),
 (('serialNumber', '2927442'),),
 (('countryName', 'US'),),
 (('postalCode', '60603'),),
 (('stateOrProvinceName', 'Illinois'),),
 (('localityName', 'Chicago'),),
 (('streetAddress', '135 S La Salle St'),),
 (('organizationName', 'Bank of America Corporation'),),
 (('organizationalUnitName', 'Network Infrastructure'),),
 (('commonName', 'www.bankofamerica.com'),)),
 'subjectAltName': (('DNS', 'mobile.bankofamerica.com'),
('DNS', 'www.bankofamerica.com')),
 'version': 3}

   How about just returning ALL the remaining fields and finishing
the job?  Thanks.

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


Re: SSLsocket.getpeercert - request to return ALL the fields of the certificate.

2014-11-12 Thread Ethan Furman

On 11/12/2014 08:39 PM, John Nagle wrote:

   In each revision of "getpeercert", a few more fields are returned.
Python 3.2 added "issuer" and "notBefore".  Python 3.4 added
"crlDistributionPoints", "caIssuers", and OCSP URLS. But some fields
still aren't returned.  I happen to need CertificatePolicies, which
is how you distinguish DV, OV, and EV certs.

Here's what you get now:

{'OCSP': ('http://EVSecure-ocsp.verisign.com',),
  'caIssuers': ('http://EVSecure-aia.verisign.com/EVSecure2006.cer',),
  'crlDistributionPoints':
('http://EVSecure-crl.verisign.com/EVSecure2006.crl',),
  'issuer': ((('countryName', 'US'),),
 (('organizationName', 'VeriSign, Inc.'),),
 (('organizationalUnitName', 'VeriSign Trust Network'),),
 (('organizationalUnitName',
   'Terms of use at https://www.verisign.com/rpa (c)06'),),
 (('commonName', 'VeriSign Class 3 Extended Validation SSL
CA'),)),
  'notAfter': 'Mar 22 23:59:59 2015 GMT',
  'notBefore': 'Feb 20 00:00:00 2014 GMT',
  'serialNumber': '69A7BC85C106DDE1CF4FA47D5ED813DC',
  'subject': ((('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
  (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
  (('businessCategory', 'Private Organization'),),
  (('serialNumber', '2927442'),),
  (('countryName', 'US'),),
  (('postalCode', '60603'),),
  (('stateOrProvinceName', 'Illinois'),),
  (('localityName', 'Chicago'),),
  (('streetAddress', '135 S La Salle St'),),
  (('organizationName', 'Bank of America Corporation'),),
  (('organizationalUnitName', 'Network Infrastructure'),),
  (('commonName', 'www.bankofamerica.com'),)),
  'subjectAltName': (('DNS', 'mobile.bankofamerica.com'),
 ('DNS', 'www.bankofamerica.com')),
  'version': 3}

How about just returning ALL the remaining fields and finishing
the job?  Thanks.


This would be much better on the issue tracker:  https://bugs.python.org

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


Re: How about some syntactic sugar for " __name__ == '__main__' "?

2014-11-12 Thread Cameron Simpson

On 12Nov2014 14:51, Ian Kelly  wrote:

On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor  wrote:

A decorator is an interesting idea, and should be easy to implement (only
lightly tested): [...]
Just decorate the "main" function of the script with that, and it will be
automatically called when ran as a script, but not when imported as a
module.


This calls it at the wrong time, though. [...]
This would call the main function at the time it's defined, when other
things in the main script may not have been defined yet. One could
place the main function last, but it would be preferable not to be
forced.


Indeed. This aspect is a deal breaker for me; I'd never use it.

I make a point of putting the module's main function right up the top, 
immediately after the imports and any "constants" (let's not dither over that 
term). I _want_ the main function to in the reader's face when they visit the 
module code. All the cogs come later.


And lots of my modules have "main" functions. Terribly useful.

Cheers,
Cameron Simpson 

We're in the business of putting goo on a substrate.
- overhead by WIRED at the Intelligent Printing conference Oct2006
--
https://mail.python.org/mailman/listinfo/python-list