Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Steven D'Aprano wrote:

> and your code will break. Better and safer is:
> 
> 
> def main():  # parse the args and call whatever function was selected
> args = parser.parse_args(sys.argv[1:])
> try:
> func = args.func
> except AttributeError as err:
> parser.print_help()
> else:
> func(vars(args))

I don't think this is any better. You are reponding on a programming error 
in the script as if the user had provided erroneous input. Very confusing.
Just

args.func(vars(args))

will produce a traceback if the programmer made an error and a help message 
if the user provides arguments that are not recognized. 

That's how it should be.

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ian Kelly
On Dec 1, 2015 1:36 PM, "Rick Johnson"  wrote:

>

> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:

> > Python was never intended to be "merely" a teaching language. I think

> > Guido's original vision was for it to be a glue language between C

> > libraries, and a scripting language.

>

> It's a well know fact that GvR was inspired to create Python from his
experiences working with a language called ABC -- and ABC was designed
*EXCLUSIVELY* to be a beginners language.

Which is exactly what made ABC itself unsuitable for Guido's purpose, which
was to create an *applications* language with better productivity than C to
support users of Amoeba, the OS that he was working on at the time.

> I am not arguing that "abstractions are evil", no, my position is that
abstractions must be constructed in a manner that provides a clear trail of
bread crumbs which lead to the underlying processes. With print, not only
is the engine in another dimension, but the hood is as well! How is a noob
to discover the engine when he cannot find the hood?

>

> Ponder the following example code (as a noob!):

>

>  stdout.write("Dude, i found my car, the hood, and the effing engine!!!")

>

> Even a noob can intuit what is going on here. First we have an *OBJECT*
named "stdout, and we can extrapolate that stdout is an abbreviation for
StandardOutput. Next, we see a method called "write", and, if our IQ is
above room temperature, then we can extrapolate what that method will do.

This is absurd. You postulate a beginner so rank that they can't understand
what "print" means, yet you expect them to intuitively know:

1) what an object is;

2) what a method is;

3) that a method is identified by placing a period between the object and
the name of the method;

4) what "output" is in the context of programming;

5) and not be confused about what makes the output "standard".

> Now ponder this code (as a noob!):

>

>  print("Dude, where's the intuitiveness?")

>

> What the heck does print do? Where will the string go after i execute
this line of code? Should i turn my printer on? Should i check my ink
levels? And what OEM drivers are required?

You're describing this as if your hypothetical beginner were learning
Python in a vacuum. In reality, people learn from a teacher, or a book, or
at minimum a tutorial.

Here's how you teach somebody what "print" does: instruct them to type
print("hello world") at the interactive prompt. Note that Python writes
"hello world" as a result. If they really want, they can check their
printer and see that nothing came out. That's it. The student now
understands what "print" means.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python response slow when running external DLL

2015-12-01 Thread jfong
Peter Otten at 2015/12/1  UTC+8 7:01:55PM wrote:
> While the var_status.set() invoked from the second thread modifies some 
> internal data the main thread could kick in and modify (parts of) that same 
> data, thus bringing tkinter into an broken state. A simple example that 
> demonstrates the problem:
> 
> import random
> import threading
> import time
> 
> account = 70
> 
> def withdraw(delay, amount):
> global account
> if account >= amount:
> print("withdrawing", amount)
> account -= amount
> else:
> print("failed to withdraw", amount)
> 
> threads = []
> for i in range(10):
> t = threading.Thread(
> target=withdraw,
> kwargs=dict(delay=.1,
> amount=random.randrange(1, 20)))
> threads.append(t)
> t.start()
> 
> for t in threads:
> t.join()

It's a simple and vivid example. You must be in the banking business:-)

In this exercise, I can just use update_idletasks() method to solve the 
deferred display problem of tkinter, and forget all about thread. But what if I 
really want to use thread for the long-running DLL function in the download 
hander? I didn't figure out a correct way of doing it at this moment. Maybe 
queue is the answer but I am not familiar with it yet.

def download():
var_status.set(...)  #showing a start-up message
result = SayHello()  #this is a long-running function
if result#according to the result, display more messages

> 
> Before every withdrawal there seems to be a check that ensures that there is 
> enough money left, but when you run the script a few times you will still 
> sometimes end with a negative balance. That happens when thread A finds 
> enough money, then execution switches to thread B which also finds enough 
> money, then both threads perform a withdrawal -- oops there wasn't enough 
> money for both.
>  
> >> Another complication that inevitably comes with concurrency: what if the
> >> user triggers another download while one download is already running? If
> >> you don't keep track of all downloads the message will already switch to
> >> "Download OK" while one download is still running.
> > 
> > Hummm...this thought never comes to my mind. After take a quick test I
> > found, you are right, a second "download" was triggered immediately.
> > That's a shock to me. I suppose the same event shouldn't be triggered
> > again, or at least not triggered immediately, before its previous handler
> > was completed. ...I will take a check later on Borland C++ builder to see
> > how it reacts!
> > 
> > Anyway to prevent this happens? if Python didn't take care it for us.
> 
> A simple measure would be to disable the button until the download has 
> ended.

Good! simple and work.

I shouldn't say "Python should take care of it", but "tk" should do. It's 
annoying the widget's command was re-triggered before it was finished. (my 
personal opinion:-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread boB Stepp
On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano  wrote:

>
> Either way, vars() doesn't solve the problem. What problem does it solve?
>

I'm way out of my depth here (I normally post on Tutor, as Steve
knows), but when I looked vars() up in Lutz's "Python Pocket
Reference, 5th ed.", he ended his description of it with:  "... Hint:
useful for referring to variables in string formatting."  This is
probably something obvious to you, but I thought I'd throw it out
there in case it's of any value, since I did not see this mentioned
elsewhere in this thread.  Just trying to learn more ...


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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Ben Finney
Steven D'Aprano  writes:

> You misunderstand the koan.
>
> "There should be one way to do it" does not prohibit more than one
> way.

Further, that's omitting a very important modifier from the koan.

Even without the parenthetical, the koan reads:

There should be one obvious way to do it.

So yes, there can certainly be multiple ways to do it. But it's very
important that there be one *obvious* way.

In other words: Don't present the user with a multitude of options with
no *obvious* choice for those who don't care (yet) to learn about the
choice. Make one of them *obvious* so that's the usually-correct choice.

> (Although having multiple redundant ways is discouraged.) The koan
> exists to encourage the existence of *at least* one (but preferably
> only one) way to do it.

And the Pythonic approach is to make an *obvious* way to do it. As you
say, ‘print’ is that one obvious way for emitting simple text output.

-- 
 \ “What's another word for Thesaurus?” —Steven Wright |
  `\   |
_o__)  |
Ben Finney

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


Re: static variables

2015-12-01 Thread Steven D'Aprano
On Wed, 2 Dec 2015 12:16 pm, Erik wrote:

> On 02/12/15 01:02, Steven D'Aprano wrote:
>> On Tue, 1 Dec 2015 08:15 pm, Grobu wrote:
>>> # -
>>>   >>> def test(arg=[0]):
>>> ... print arg[0]
>>> ... arg[0] += 1
>> Awesome!
> 
> Hideous!
> 
>> using a mutable default as static storage.
> 
> Exposing something a caller can override as a local, static, supposedly
> "private" value is IMHO a tad ... ugly? (*)


Heh, I agree, and as I suggested, it might be good to have an actual
mechanism for static locals. But using a class is no better: your "static
storage" is exposed as an instance attribute, and even if you flag it
private, *somebody* is going to mess with it.

A closure works, but that obfuscates the code:

def make_test():
arg = [0]
def test():
print arg[0]
arg[0] += 1
return test

test = make_test()

Or in Python 3:

def make_test():
arg = 0
def test():
nonlocal arg
print arg
arg += 1
return test

test = make_test()


Python has three not-entirely-awful solutions to the problem of static
locals, but no really great or obvious one.



-- 
Steven

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


Re: static variables

2015-12-01 Thread Erik

On 02/12/15 01:02, Steven D'Aprano wrote:

On Tue, 1 Dec 2015 08:15 pm, Grobu wrote:

# -
  >>> def test(arg=[0]):
... print arg[0]
... arg[0] += 1

Awesome!


Hideous!


using a mutable default as static storage.


Exposing something a caller can override as a local, static, supposedly 
"private" value is IMHO a tad ... ugly? (*)


E.

(*) No I don't want to resurrect that thread.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tue, 1 Dec 2015 07:44 pm, Manolo Martínez wrote:

> On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
>> I'm trying to understand why vars() exists. Does anyone use it?
> 
> Well, I have this little podcast aggregator
> (https://github.com/manolomartinez/greg) that I and a bunch of other
> people use. I started writing it some years ago, and the code is a bit
> of a palimpsest, newer functionality reflecting my (somewhat) better
> understanding of the language. One of the oldest bits is this main()
> function:
> 
> def main():  # parse the args and call whatever function was selected
> try:
> args = parser.parse_args(sys.argv[1:])
> args.func(vars(args)) 
> except AttributeError as err:
> if str(err) == "\'Namespace\' object has no attribute \'func\'":
> parser.print_help()
> else:
> print("Something has gone wrong: {}".format(err), 
>   file = sys.stderr, flush = True)
> 
> 
> To judge by this thread, this is probably wrong/noobish?

I've seen worse :-)

Checking the error message in that way is risky. As an absolute last resort,
I guess it works, but it's hack-ish (not in a good way) and fragile. The
problem is, error messages are not part of the Python API and are subject
to change without warning.

(Aside: when I design my language, I'm going to ensure that error messages
vary from one exception to the next, specifically to discourage this :-)

Today, you get an error message 

"'Namespace' object has no attribute 'func'"

(note that there is no need to escape the single quotes) but there's no
guarantee that this will always be the same. Tomorrow it could silently
change to:

'"Namespace" instance does not have a "func" attribute.'

and your code will break. Better and safer is:


def main():  # parse the args and call whatever function was selected
args = parser.parse_args(sys.argv[1:])
try:
func = args.func
except AttributeError as err:
parser.print_help()
else:
func(vars(args))



-- 
Steven

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


Re: static variables

2015-12-01 Thread Steven D'Aprano
On Tue, 1 Dec 2015 08:15 pm, Grobu wrote:

> Perhaps you could use a parameter's default value to implement your
> static variable?
> 
> Like :
> # -
>  >>> def test(arg=[0]):
> ... print arg[0]
> ... arg[0] += 1
> ...


Awesome!

I'm not being sarcastic, I'm serious. Thank you Grobu, for demonstrating the
existence of something we debated a few days ago.

In another *painfully* long thread about mutable default arguments, I
suggested the same idea: using a mutable default as static storage. It is
very gratifying to see that other people have independently come up with
the same idea.




-- 
Steven

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Wed, 2 Dec 2015 07:33 am, Rick Johnson wrote:

> On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:
>> Python was never intended to be "merely" a teaching language. I think
>> Guido's original vision was for it to be a glue language between C
>> libraries, and a scripting language.
> 
> It's a well know fact that GvR was inspired to create Python from his
> experiences working with a language called ABC -- and ABC was designed
> *EXCLUSIVELY* to be a beginners language. 

Certainly. But do you have any evidence that *Python* was designed to be
exclusively a beginner's language?

It is possible to be inspired by a teaching language without aiming to be
limited to the functionality of a teaching language.


>> > Rick said:
>> > (1) How do you output a message without the print function?
>> 
> Steven said:
>> *scratches head*
>> 
>> Why would you want to do that? print is clearly the "one obvious way" to
>> output a message.
> 
> Well of course the answers are *OBVIOUS* when you already *KNOW* them
> Steven! Climb down off your high horse for a moment, and take yourself
> back to a time *BEFORE* you had any knowledge of output streams.

What's an output stream?

All I know is that if you want to print a message, calling "print" is the
obvious way to do it. Using the word "print" for writing text on the screen
is very common, although not ubiquitous. Rosetta Code includes over 300
examples of the "Hello World" program, and a quick glance at the page shows
that (apart from deliberately obfuscatory languages and assembly
languages), print is one of the more common functions used:

http://rosettacode.org/wiki/Hello_world/Text

Others include:

echo
puts
write
writeln
printf
println
display
console.log
cout
say
System.Console.WriteLine

which vary in their obviousness.



[...]
> Ponder the following example code (as a noob!):
> 
>  stdout.write("Dude, i found my car, the hood, and the effing engine!!!")
> 
> Even a noob can intuit what is going on here. First we have an *OBJECT*
> named "stdout, and we can extrapolate that stdout is an abbreviation for
> StandardOutput. Next, we see a method called "write", and, if our IQ is
> above room temperature, then we can extrapolate what that method will do.

Are you serious? You think that a complete beginner to programming is going
to have an intuitive grasp of stdout? What did you say earlier about
putting aside my knowledge of output streams?


> Now ponder this code (as a noob!):
> 
>  print("Dude, where's the intuitiveness?")
> 
> What the heck does print do? 

It's a standard English word, and has been since at least 1469, and possibly
as long ago as 1150. As a native English speaker, I'm surprised that your
vocabulary is so lacking that you need help with that, especially as an
American. Didn't they teach you "printing" (block letters) and "cursive"
(joined up letters) handwriting when you were at school?



> Where will the string go after i execute this 
> line of code? Should i turn my printer on? Should i check my ink levels?
> And what OEM drivers are required?

That's an interesting point. In, oh, a dozen or more years of dealing with
Python beginners, I have come across *exactly one* beginner who assumed
that print would send output to the printer. 

Where there's one, there are probably more, but I think it is fair to say
that the idea of *printing to the screen* is commonplace, and these days
probably even more common than the idea of printing to paper. I expect that
kids learning BASIC in the 1970s probably had more difficulty with the
concept, but even then, that difficulty would extend to as long as it takes
somebody to say "it prints the message to the screen".


> Not only is "print" un-intuitive (by nature of it's naming), it is
> obfuscating the path to the underlying process of "sending data to an
> output stream".

A wise man once said to me, "take yourself back to a time *BEFORE* you had
any knowledge of output streams". Although I suspect perhaps he was more of
a wise guy than a wise man.



-- 
Steven

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


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Skybuck Flying

It's not YOU doing it.

Since you obviously don't understand that it's not worth reading anything 
else you wrote LOL.


Bye,
 Skybuck. 


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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Gregory Ewing

Rick Johnson wrote:

the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY TO DO
IT!".


You're misquoting the Zen. It says there should be one
*obvious* way to do it.

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


Re: "Downloading"

2015-12-01 Thread Chris Angelico
On Wed, Dec 2, 2015 at 10:46 AM, Steven D'Aprano  wrote:
> On Wed, 2 Dec 2015 06:05 am, Random832 wrote:
>
>> On 2015-12-01, Steve Hayes  wrote:
>>> You download things FROM a computer, you upload them TO a computer.
>>
>> I'm a little bit confused as to what kinds of file transfers
>> you think don't have at least two endpoints.
>
> If you have a computer with two network connections, plug a cable from one
> to the other, and now you can download stuff from yourself in half the time
> it would take to download from the Cloud.

If you have a computer with both wired and wireless network, plug half
a cable into the wired network, and download stuff from yourself over
401.5½!

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


Re: "Downloading"

2015-12-01 Thread Steven D'Aprano
On Wed, 2 Dec 2015 06:05 am, Random832 wrote:

> On 2015-12-01, Steve Hayes  wrote:
>> You download things FROM a computer, you upload them TO a computer.
> 
> I'm a little bit confused as to what kinds of file transfers
> you think don't have at least two endpoints.

If you have a computer with two network connections, plug a cable from one
to the other, and now you can download stuff from yourself in half the time
it would take to download from the Cloud.




-- 
Steven

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


Re: python domain in China. This showed up on Python list

2015-12-01 Thread Steven D'Aprano
On Tue, 1 Dec 2015 10:49 pm, Laura Creighton wrote:

> In a message of Tue, 01 Dec 2015 02:51:21 -0800, Chris Rebert writes:
>>I hate to break it to you, but this seems to be just another of those
>>come-ons spammed out by various scummy businesses that trawl WHOIS
>>databases for people to scam into buying extra/unnecessary domain
>>names. Google "chinese domain scam" for more info. I've received
>>similar spams after having registered some .com domains that no
>>corporation could possibly legitimately want the .cn equivalents of.
> 
> Ah...  Thank you Chris.  Sure fooled me.


You're not the only one. At my day job, we get dozens of these, about one or
two a month, and the first time it happened, I responded, at which point
they told us that if we paid $MANY we could register the domain .cn before somebody else did.

At that point, we lost interest, as we have no business interests in China.
If somebody wants to register our name in China, let them.



-- 
Steven

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


Re: "Downloading"

2015-12-01 Thread Erik

On 01/12/15 23:28, Ian Kelly wrote:

What about transfers that are initiated by neither?

scp remote_host1:path/to/file remote_host2:path/to/destination


Regardless of how the transfer is invoked, in traditional parlance the 
source uploads, the target downloads.


Why is this on the Python list? ;)

E.

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


Re: "Downloading"

2015-12-01 Thread Chris Angelico
On Wed, Dec 2, 2015 at 10:28 AM, Ian Kelly  wrote:
> On Tue, Dec 1, 2015 at 5:05 PM, Chris Angelico  wrote:
>> On Wed, Dec 2, 2015 at 6:05 AM, Random832  wrote:
>>> On 2015-12-01, Steve Hayes  wrote:
 You download things FROM a computer, you upload them TO a computer.
>>>
>>> I'm a little bit confused as to what kinds of file transfers
>>> you think don't have at least two endpoints.
>>
>> From some other computer to the one you're controlling it from. A
>> download is initiated by the recipient; an upload is initiated by the
>> sender.
>
> What about transfers that are initiated by neither?
>
> scp remote_host1:path/to/file remote_host2:path/to/destination

I'd punt and call it a "transfer", same as you just did :)

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


Re: "Downloading"

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 5:05 PM, Chris Angelico  wrote:
> On Wed, Dec 2, 2015 at 6:05 AM, Random832  wrote:
>> On 2015-12-01, Steve Hayes  wrote:
>>> You download things FROM a computer, you upload them TO a computer.
>>
>> I'm a little bit confused as to what kinds of file transfers
>> you think don't have at least two endpoints.
>
> From some other computer to the one you're controlling it from. A
> download is initiated by the recipient; an upload is initiated by the
> sender.

What about transfers that are initiated by neither?

scp remote_host1:path/to/file remote_host2:path/to/destination
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Downloading"

2015-12-01 Thread Chris Angelico
On Wed, Dec 2, 2015 at 6:05 AM, Random832  wrote:
> On 2015-12-01, Steve Hayes  wrote:
>> You download things FROM a computer, you upload them TO a computer.
>
> I'm a little bit confused as to what kinds of file transfers
> you think don't have at least two endpoints.

>From some other computer to the one you're controlling it from. A
download is initiated by the recipient; an upload is initiated by the
sender.

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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Erik

Apologies for self-replying,

On 01/12/15 22:34, Erik wrote:

 what you're asking for is that
the *container* object whose element is being assigned to is first
queried as to whether it will accept a mutated element being assigned to
it before that element is mutated.


What I said above is rubbish. The situation is approximately similar to:

a = [4, 5, 6]
t = ([1, 2, 4], a)
a.append(7)
a.append(8)
a.append(9)

The point is, you're mutating something that an immutable object 
contains. In the example you give, that's caught because of the 
subsequent explicit assignment.


In the example above, it's not caught. But it's the same thing.

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Manolo Martínez wrote:

> Peter, thanks for taking the time to look into my code.
> 
> On 12/01/15 at 11:40am, Peter Otten wrote:
>> Manolo Martínez wrote:
>> > def main():  # parse the args and call whatever function was
>> selected
>> > try:
>> > args = parser.parse_args(sys.argv[1:])
>> > args.func(vars(args))
>> > except AttributeError as err:
>> > if str(err) == "\'Namespace\' object has no
>> attribute \'func\'":
>> > parser.print_help()
>> > else:
>> > print("Something has gone wrong:
>> {}".format(err), file = sys.stderr, flush = True)
>> 
>> What probably is typical for a beginner in that snippet is that you don't
>> trust the exception system and handle exceptions that will never occur
>> once the script is debugged. Just write
>> 
>> args = parser.parse_args()
>> args.func(vars(args))
> 
> Well, one fully possible situation is for the user to mistype a
> subcommand. In that case, the script outputs the help provided by
> argparse, so that they know what is and isn't meaningful. That is what
> the "if str(err)..." is doing.
> 
> The else clause is there to output the traceback (in full trust of the
> exception system ;) in case the error was not due to the user mistyping.
> 
> Is there a better way to do this?

As far as I can see in a correctly written script the AttributeError cannot 
be triggered by the user as argparse handles this case automatically by 
showing the help. For example:

$ cat subparsers.py
#!/usr/bin/env python3
import argparse


def foo(args):
print(args)


def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

foo_parser = subparsers.add_parser("foo")
foo_parser.set_defaults(func=foo)

bar_parser = subparsers.add_parser("bar")
# programming error --> missing func attribute

args = parser.parse_args()
args.func(args)


main()
$ ./subparsers.py foo
Namespace(func=)
$ ./subparsers.py bar
Traceback (most recent call last):
  File "./subparsers.py", line 23, in 
main()
  File "./subparsers.py", line 20, in main
args.func(args)
AttributeError: 'Namespace' object has no attribute 'func'
$ ./subparsers.py baz # erroneous user input
usage: subparsers.py [-h] {foo,bar} ...
subparsers.py: error: invalid choice: 'baz' (choose from 'foo', 'bar')

The traceback may be a bit intimidating, but with your error handling the 
user will get

$ cat subparsers2.py
#!/usr/bin/env python3
import argparse


def foo(args):
print(args)


def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

foo_parser = subparsers.add_parser("foo")
foo_parser.set_defaults(func=foo)

bar_parser = subparsers.add_parser("bar")
# programming error --> missing func attribute


try:
args = parser.parse_args()
args.func(args)
except AttributeError as err:
if str(err) == "\'Namespace\' object has no attribute \'func\'":
print("WE ARE HERE")
parser.print_help()
else:
print("Something has gone wrong: {}".format(err), file = 
sys.stderr, flush = True)

main()
$ ./subparsers2.py foo
Namespace(func=)
$ ./subparsers2.py baz # erroneous user input does not trigger your error 
handling
usage: subparsers2.py [-h] {foo,bar} ...
subparsers2.py: error: invalid choice: 'baz' (choose from 'foo', 'bar')
$ ./subparsers2.py bar # but an error in your script does
WE ARE HERE
usage: subparsers2.py [-h] {foo,bar} ...

positional arguments:
  {foo,bar}

optional arguments:
  -h, --help  show this help message and exit

which is very confusing. Again, don't replace the traceback unless you are 
absolutely sure you can do better than the Python interpreter.

By the way, I recommend coverage.py to find dead code. I have not used it 
for too long, and I regret it ;)



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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Terry Reedy

On 12/1/2015 4:36 PM, Denis McMahon wrote:

On Tue, 01 Dec 2015 16:18:49 -0500, Terry Reedy wrote:


On 12/1/2015 3:32 PM, Denis McMahon wrote:

On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:


In the case of:

   tup[1] += [6, 7]

what it's trying to do is:

   tup[1] = tup[1].__iadd__([6, 7])

tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
then Python tries to put the result that the method returns into
tup[1].
That fails because tup itself is a tuple, which is immutable.


I think I might have found a bug:


What you found is an specific example of what MRAB said in general
above.


$ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
for more information.

tup = [1,2,3],[4,5,6]
tup

([1, 2, 3], [4, 5, 6])

tup[1]

[4, 5, 6]

tup[1] += [7,8,9]

Traceback (most recent call last):
File "", line 1, in 
TypeError: 'tuple' object does not support item assignment


The bug is trying to replace a member of a tuple.  The correct code, to
avoid the exception while extending the list, is

tup[1].extend([7,8,9])


tup[1]

[4, 5, 6, 7, 8, 9]


You snipped the important bit of my original post, which was the state of
tup after the TypeError occurred.


No I did not.  The change to tup[1] right there above, after giving the 
correct way to make the change.



After the error,



tup[1]

[4, 5, 6, 7, 8, 9]


This is exactly what I posted.


tup

([1, 2, 3], [4, 5, 6, 7, 8, 9])


This is a repeat of the same thing and adds no new info.


The "bug" I refer to is that despite giving the TypeError, the tuple
allowed the assignment of the mutated list to replace the original list.


No it did not.  As MRAB noted, the list is mutated and the attempted 
assignment causes an exeption. This has been discussed before more than 
once ever since augmented *assignment* was introduced.


>>> tup = ([],[])
>>> id(tup[1])
711662188872

>>> tup[1] += [1]
Traceback (most recent call last):
  File "", line 1, in 
tup[1] += [1]
TypeError: 'tuple' object does not support item assignment
>>> tup[1]
[1]
>>> id(tup[1])
711662188872

>>> tup[1] = tup[1].extend([2])
Traceback (most recent call last):
  File "", line 1, in 
tup[1] = tup[1].extend([2])
TypeError: 'tuple' object does not support item assignment
>>> tup[1]
[1, 2]
>>> id(tup[1])
711662188872

Reading the augmented assignment doc carefully should make it clear that 
"tup[1] += [1]" is the same as "tup[1] = tup[1].extend([2])" except that 
evaluation of "tup[1]" happens just once instead of twice.


--
Terry Jan Reedy

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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Erik

On 01/12/15 21:37, Denis McMahon wrote:

The assignment succeeds. That's imo a bug. If it's a TypeError to try and
assign a value to tup[1], then tup[1] should not allow the mutated list
to be assigned.


Nothing got assigned.

That original list object remains in that slot. However, it has been 
mutated since it was originally assigned.


But I can see what you're getting at - what you're asking for is that 
the *container* object whose element is being assigned to is first 
queried as to whether it will accept a mutated element being assigned to 
it before that element is mutated.


This looks to be a fundamental issue with the augmented assignment 
mechanism.


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


Re: Pylint 1.5.0 / Astroid 1.4.1 released

2015-12-01 Thread Omar Abou Mrad
On Tue, Dec 1, 2015 at 1:42 AM, Claudiu Popa  wrote:

> Hello,
>
>
> I'm happy to announce you the release of Pylint 1.5.0,
> respectively Astroid 1.4.1.
>
> 
>
> Claudiu
> --
> https://mail.python.org/mailman/listinfo/python-list
>

Awesome! Congrats!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 14:44:38 -0600, Ian Kelly wrote:

> On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon 
> wrote:
>> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>>
>>> In the case of:
>>>
>>>  tup[1] += [6, 7]
>>>
>>> what it's trying to do is:
>>>
>>>  tup[1] = tup[1].__iadd__([6, 7])
>>>
>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>>> then Python tries to put the result that the method returns into
>>> tup[1].
>>> That fails because tup itself is a tuple, which is immutable.
>>
>> I think I might have found a bug:
>>
>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
>> for more information.
> tup = [1,2,3],[4,5,6]
> tup
>> ([1, 2, 3], [4, 5, 6])
> tup[1]
>> [4, 5, 6]
> tup[1] += [7,8,9]
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> TypeError: 'tuple' object does not support item assignment
> tup[1]
>> [4, 5, 6, 7, 8, 9]
> tup
>> ([1, 2, 3], [4, 5, 6, 7, 8, 9])
> quit()
> 
> No, that's the expected result. As MRAB wrote, the list *is* mutated
> when its __iadd__ method is called. The TypeError happens afterward when
> the assignment is attempted.

The assignment succeeds. That's imo a bug. If it's a TypeError to try and 
assign a value to tup[1], then tup[1] should not allow the mutated list 
to be assigned.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Manolo Martínez
Peter, thanks for taking the time to look into my code.

On 12/01/15 at 11:40am, Peter Otten wrote:
> Manolo Martínez wrote:
> > def main():  # parse the args and call whatever function was 
> selected
> > try:
> > args = parser.parse_args(sys.argv[1:])
> > args.func(vars(args))
> > except AttributeError as err:
> > if str(err) == "\'Namespace\' object has no 
> attribute \'func\'":
> > parser.print_help()
> > else:
> > print("Something has gone wrong: 
> {}".format(err), file = sys.stderr, flush = True)
> 
> What probably is typical for a beginner in that snippet is that you don't 
> trust the exception system and handle exceptions that will never occur once 
> the script is debugged. Just write
> 
> args = parser.parse_args()
> args.func(vars(args))

Well, one fully possible situation is for the user to mistype a
subcommand. In that case, the script outputs the help provided by
argparse, so that they know what is and isn't meaningful. That is what
the "if str(err)..." is doing.

The else clause is there to output the traceback (in full trust of the
exception system ;) in case the error was not due to the user mistyping.

Is there a better way to do this?

> Now vars(). I see nothing wrong with it, but when I look into one of your 
> func implementations
> 
> > def info(args):  # Provides information of a number of feeds
> > session = Session(args)
> > if "all" in args["names"]:
> > feeds = session.list_feeds()
> > else:
> > feeds = args["names"]
> > for feed in feeds:
> > pretty_print(session, feed)
> 
> I come to the conclusion that passing args directly could make your life 
> easier:
> 
> def info(args):  
> """Provides information of a number of feeds"""
> session = Session(args)
> if "all" in args.names:
> feeds = session.list_feeds()
> else:
> feeds = args.names
> for feed in feeds:
> pretty_print(session, feed)
> 
> As far as I can see there is only one place where the key is not a constant, 
> and you can rewrite that from 
> 
> > try:
> > if args[value]:
> > return args[value]
> > except KeyError:
> > pass
> 
> to
> 
> try:
> answer = getattr(args, value)
> if answer: 
> return answer
> except AttributeError:
> pass
> 

This is very helpful, thanks a lot! 

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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 16:18:49 -0500, Terry Reedy wrote:

> On 12/1/2015 3:32 PM, Denis McMahon wrote:
>> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>>
>>> In the case of:
>>>
>>>   tup[1] += [6, 7]
>>>
>>> what it's trying to do is:
>>>
>>>   tup[1] = tup[1].__iadd__([6, 7])
>>>
>>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>>> then Python tries to put the result that the method returns into
>>> tup[1].
>>> That fails because tup itself is a tuple, which is immutable.
>>
>> I think I might have found a bug:
> 
> What you found is an specific example of what MRAB said in general
> above.
> 
>> $ python Python 2.7.3 (default, Jun 22 2015, 19:33:41)
>> [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license"
>> for more information.
> tup = [1,2,3],[4,5,6]
> tup
>> ([1, 2, 3], [4, 5, 6])
> tup[1]
>> [4, 5, 6]
> tup[1] += [7,8,9]
>> Traceback (most recent call last):
>>File "", line 1, in 
>> TypeError: 'tuple' object does not support item assignment
> 
> The bug is trying to replace a member of a tuple.  The correct code, to
> avoid the exception while extending the list, is
> 
> tup[1].extend([7,8,9])
> 
> tup[1]
>> [4, 5, 6, 7, 8, 9]

You snipped the important bit of my original post, which was the state of 
tup after the TypeError occurred.

After the error, 

>>> tup[1]
[4, 5, 6, 7, 8, 9]
>>> tup
([1, 2, 3], [4, 5, 6, 7, 8, 9])

The "bug" I refer to is that despite giving the TypeError, the tuple 
allowed the assignment of the mutated list to replace the original list.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: I can't understand re.sub

2015-12-01 Thread Erik

On 01/12/15 05:28, Jussi Piitulainen wrote:

A real solution should be aware of the actual structure of those lines,
assuming they follow some defined syntax.


I think that we are in violent agreement on this ;)

E.

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Rick Johnson
On Tuesday, December 1, 2015 at 10:56:27 AM UTC-6, John Gordon wrote:
> Rick Johnson writes:
> > Your lament does remind me of a pet peeve i have concerning Python, and
> > that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE)
> > WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to
> > achieve the same output.=20
> 
> The koan reads:
> 
> There should be one-- and preferably only one --obvious way to do it.
> 
> You left out the rather important word "obvious".

Indeed you are correct about the wording, but your interpretation is wrong. In 
fact, adding the word "obvious" only adds more truth to my argument. The word 
"obvious" does not imply that the choose method is "one *OBVIOUS* choice in a 
set of many choices", no, the word obvious merely implies intuitiveness. Let's 
dissect the "koan" component by component:

  "There should be one"

This component is less of a request, and more of a demand. It seems the author 
wishes to stress that whatever follows, there should only be one of them.
 
  "and preferably only one"

Interesting. Utilizing his advanced intellect, the author realizes that 
confining any set of choices to a length of one is not always possible, 
however, he *AGAIN* stresses the importance of length one! I'm beginning to see 
a common and obvious theme here, do you?

  "obvious way to do it"

And finally we encounter the obviousness of the one chosen way!  

The three components can be summarized as follows: First he demands a length of 
one, then he allows for exceptions while again stressing the importance of 
"one", and finally he stresses the importance of intuitiveness by using the 
word "obvious". 

In *NONE* of these components does the author *ENCOURAGE* a set of choices, no, 
he consistently stresses the importance of "one". And although it seems he has 
lost his will within the middle component (by entertaining the "unpreferred" 
possibility of more than one choice) he did not do so because his argument for 
"one" is weak, rather because, he knows that conflict and contrarianism is 
inevitable in a world that is ruled by selfish hairless apes! He has both 
demanded, and made an impassioned plea for, the "one obvious way" to do it. Any 
other interpretation is pure emotional projection.

PS: Now that I've defeated the claim that "the koan is encouraging more than 
one way", as a last resort, they will dismiss the koan as unimportant. This is 
not my first experience here folks!!!

PPS: Koan must be word of the day.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Terry Reedy

On 12/1/2015 3:32 PM, Denis McMahon wrote:

On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:


In the case of:

  tup[1] += [6, 7]

what it's trying to do is:

  tup[1] = tup[1].__iadd__([6, 7])

tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
then Python tries to put the result that the method returns into tup[1].
That fails because tup itself is a tuple, which is immutable.


I think I might have found a bug:


What you found is an specific example of what MRAB said in general above.


$ python
Python 2.7.3 (default, Jun 22 2015, 19:33:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

tup = [1,2,3],[4,5,6]
tup

([1, 2, 3], [4, 5, 6])

tup[1]

[4, 5, 6]

tup[1] += [7,8,9]

Traceback (most recent call last):
   File "", line 1, in 
TypeError: 'tuple' object does not support item assignment


The bug is trying to replace a member of a tuple.  The correct code, to 
avoid the exception while extending the list, is


tup[1].extend([7,8,9])


tup[1]

[4, 5, 6, 7, 8, 9]


--
Terry Jan Reedy

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


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 2:32 PM, Denis McMahon  wrote:
> On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:
>
>> In the case of:
>>
>>  tup[1] += [6, 7]
>>
>> what it's trying to do is:
>>
>>  tup[1] = tup[1].__iadd__([6, 7])
>>
>> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
>> then Python tries to put the result that the method returns into tup[1].
>> That fails because tup itself is a tuple, which is immutable.
>
> I think I might have found a bug:
>
> $ python
> Python 2.7.3 (default, Jun 22 2015, 19:33:41)
> [GCC 4.6.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 tup = [1,2,3],[4,5,6]
 tup
> ([1, 2, 3], [4, 5, 6])
 tup[1]
> [4, 5, 6]
 tup[1] += [7,8,9]
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
 tup[1]
> [4, 5, 6, 7, 8, 9]
 tup
> ([1, 2, 3], [4, 5, 6, 7, 8, 9])
 quit()

No, that's the expected result. As MRAB wrote, the list *is* mutated
when its __iadd__ method is called. The TypeError happens afterward
when the assignment is attempted.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Could you explain this rebinding (or some other action) on "nums = nums"?

2015-12-01 Thread Denis McMahon
On Tue, 01 Dec 2015 03:32:31 +, MRAB wrote:

> In the case of:
> 
>  tup[1] += [6, 7]
> 
> what it's trying to do is:
> 
>  tup[1] = tup[1].__iadd__([6, 7])
> 
> tup[1] refers to a list, and the __iadd__ method _does_ mutate it, but
> then Python tries to put the result that the method returns into tup[1].
> That fails because tup itself is a tuple, which is immutable.

I think I might have found a bug:

$ python
Python 2.7.3 (default, Jun 22 2015, 19:33:41) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> tup = [1,2,3],[4,5,6]
>>> tup
([1, 2, 3], [4, 5, 6])
>>> tup[1]
[4, 5, 6]
>>> tup[1] += [7,8,9]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> tup[1]
[4, 5, 6, 7, 8, 9]
>>> tup
([1, 2, 3], [4, 5, 6, 7, 8, 9])
>>> quit()

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Rick Johnson
On Tuesday, December 1, 2015 at 1:55:59 AM UTC-6, Steven D'Aprano wrote:
> Python was never intended to be "merely" a teaching language. I think 
> Guido's original vision was for it to be a glue language between C 
> libraries, and a scripting language.

It's a well know fact that GvR was inspired to create Python from his 
experiences working with a language called ABC -- and ABC was designed 
*EXCLUSIVELY* to be a beginners language. GvR has even written that one of his 
objections to ABC's design was it's tendency to create new jargon-isms to 
replace old jargon-isms. The language designers "thought" they could ease the 
learning curve simply thru virtue of symbols, but all they did was to further 
confuse noobs. GvR saw the folly of this, and set out to prevent such design 
flaws in his language, however, i argue that interfaces like the "print 
function" are making the same mistakes. The linking of abstraction layers  is 
even *MORE* important than intuitive naming conventions. But sometimes the name 
is the only path by which you can provide the link. As is the case with the 
print function.

> > Rick said:
> > (1) How do you output a message without the print function?
> 
Steven said:
> *scratches head*
> 
> Why would you want to do that? print is clearly the "one obvious way" to 
> output a message.

Well of course the answers are *OBVIOUS* when you already *KNOW* them Steven! 
Climb down off your high horse for a moment, and take yourself back to a time 
*BEFORE* you had any knowledge of output streams. 

I am not arguing that "abstractions are evil", no, my position is that 
abstractions must be constructed in a manner that provides a clear trail of 
bread crumbs which lead to the underlying processes. With print, not only is 
the engine in another dimension, but the hood is as well! How is a noob to 
discover the engine when he cannot find the hood?

Ponder the following example code (as a noob!):

 stdout.write("Dude, i found my car, the hood, and the effing engine!!!")

Even a noob can intuit what is going on here. First we have an *OBJECT* named 
"stdout, and we can extrapolate that stdout is an abbreviation for 
StandardOutput. Next, we see a method called "write", and, if our IQ is above 
room temperature, then we can extrapolate what that method will do.

Now ponder this code (as a noob!):

 print("Dude, where's the intuitiveness?")

What the heck does print do? Where will the string go after i execute this line 
of code? Should i turn my printer on? Should i check my ink levels? And what 
OEM drivers are required?

Not only is "print" un-intuitive (by nature of it's naming), it is obfuscating 
the path to the underlying process of "sending data to an output stream".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Ian Kelly
On Tue, Dec 1, 2015 at 12:49 PM, Steve Hayes  wrote:
> On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying"
>  wrote:
>
>>Hello,
>>
>>The question is:
>>
>>Is Microsoft Windows secretly downloading childporn to your computer ?!
>
> You download things FROM a computer, you upload them TO a computer.

You download things FROM one computer to another. You upload things
from one computer TO another. The only semantic difference is in which
end of the transfer is "local". Otherwise, it's like saying "up the
street" versus "down the street", so what difference does it make?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Keith Thompson
Steve Hayes  writes:
> On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying"
>  wrote:
>>The question is:
>>
>>Is Microsoft
[snip]
>
> You download things FROM a computer, you upload them TO a computer.
>
> Since you don't even know that much about computers, anything else you
> say is obviously not worth readin. 

Nor is it worth replying to.  *Please* don't feed the troll.

(Followups set.)

-- 
Keith Thompson (The_Other_Keith) ks...@mib.org  
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Downloading"

2015-12-01 Thread Random832
On 2015-12-01, Steve Hayes  wrote:
> You download things FROM a computer, you upload them TO a computer.

I'm a little bit confused as to what kinds of file transfers
you think don't have at least two endpoints.

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


activestate recipe for code to source and back fails on 3.3+, core Python bug?

2015-12-01 Thread Mark Lawrence
The recipe in question is here 
http://code.activestate.com/recipes/578353-code-to-source-and-back. 
I've called it c2sab in the test code below.


The problem is that the class name gets dropped during the round trip, 
but only if a list, dict or set comprehension or a generator expression 
is involved, and only from the code.co_consts tuple.  Hopefully the code 
and output that follows makes sense.



import c2sab
import inspect

class Comps():

def listcomp(self):
self.lc = [x for x in range(10)]

def genexpr(self):
self.ge = (x for x in range(10))

def dictcomp(self):
self.dc = {x: x**2 for x in range(10)}

def setcomp(self):
self.sc = {x for x in range(10)}

methods = inspect.getmembers(Comps, inspect.isfunction)
for _, method in methods:
print('Processing', method.__name__)
code = method.__code__
recode = c2sab.recompile(*c2sab.uncompile(code))
for offset, co_consts in enumerate(zip(code.co_consts, 
recode.co_consts)):

old = co_consts[0]
new = co_consts[1]
if old != new:
print('offset {} code |{}| not equal to recode 
|{}|'.format(offset, old, new))

print()



Processing dictcomp
offset 2 code |Comps.dictcomp..| not equal to recode 
|dictcomp..|


Processing genexpr
offset 2 code |Comps.genexpr..| not equal to recode 
|genexpr..|


Processing listcomp
offset 2 code |Comps.listcomp..| not equal to recode 
|listcomp..|


Processing setcomp
offset 2 code |Comps.setcomp..| not equal to recode 
|setcomp..|



I can reproduce the above on 3.3 to 3.6 inclusive on Windows 10.  This 
has no impact on 3.2 or lower as the field in question is new in 
co_consts for 3.3.


So is my analysis correct?  If yes I'll be reporting a bug although I've 
no idea what against, if no what have I overlooked?


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Steve Hayes
On Tue, 1 Dec 2015 03:19:39 +0100, "Skybuck Flying"
 wrote:

>Hello,
>
>The question is:
>
>Is Microsoft Windows secretly downloading childporn to your computer ?!

You download things FROM a computer, you upload them TO a computer.

Since you don't even know that much about computers, anything else you
say is obviously not worth readin. 



-- 
Steve Hayes from Tshwane, South Africa
Web:  http://www.khanya.org.za/stevesig.htm
Blog: http://khanya.wordpress.com
E-mail - see web page, or parse: shayes at dunelm full stop org full stop uk
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Mr Zaug
Ye, this does work. Many thanks!

filename = "{NNN}_{BRAND}_farm.any".format(BRAND=brand, NNN=nnn)
with open(filename, "w") as outstream:
outstream.write(data)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: 4D arrays

2015-12-01 Thread Peter Otten
jorge.conr...@cptec.inpe.br wrote:

> I use the IDL but now I'm change to PYTHON. I have a 4D array (time,
> level,lon,lat). I would like to get a 2D array for a specific time
> (time1) and level (level1). In IDL I use: 2Darray =
> 4Darray(time1,level1,*,*). How can I get the 2D array in Python

With numpy you can use slicing.

Create a 4D array with pointless data in it:

>>> import numpy
>>> a = numpy.arange(2*3*4*5).reshape((2, 3, 4, 5))
>>> a
array(  0,   1,   2,   3,   4],
 [  5,   6,   7,   8,   9],
 [ 10,  11,  12,  13,  14],
 [ 15,  16,  17,  18,  19]],

[[ 20,  21,  22,  23,  24],
 [ 25,  26,  27,  28,  29],
 [ 30,  31,  32,  33,  34],
 [ 35,  36,  37,  38,  39]],

[[ 40,  41,  42,  43,  44],
 [ 45,  46,  47,  48,  49],
 [ 50,  51,  52,  53,  54],
 [ 55,  56,  57,  58,  59]]],


   [[[ 60,  61,  62,  63,  64],
 [ 65,  66,  67,  68,  69],
 [ 70,  71,  72,  73,  74],
 [ 75,  76,  77,  78,  79]],

[[ 80,  81,  82,  83,  84],
 [ 85,  86,  87,  88,  89],
 [ 90,  91,  92,  93,  94],
 [ 95,  96,  97,  98,  99]],

[[100, 101, 102, 103, 104],
 [105, 106, 107, 108, 109],
 [110, 111, 112, 113, 114],
 [115, 116, 117, 118, 119)

Extract 2D arrays:

>>> a[:,2,3]
array([[ 55,  56,  57,  58,  59],
   [115, 116, 117, 118, 119]])
>>> a[1,:,2]
array([[ 70,  71,  72,  73,  74],
   [ 90,  91,  92,  93,  94],
   [110, 111, 112, 113, 114]])


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


4D arrays

2015-12-01 Thread jorge . conrado



Hi,

I use the IDL but now I'm change to PYTHON. I have a 4D array (time, 
level,lon,lat). I would like to get a 2D array for a specific time 
(time1) and level (level1). In IDL I use: 2Darray = 
4Darray(time1,level1,*,*). How can I get the 2D array in Python



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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread John Gordon
In <4f0f7fc5-c93a-4223-9c05-e192a8faf...@googlegroups.com> Rick Johnson 
 writes:

> Your lament does remind me of a pet peeve i have concerning Python, and
> that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE)
> WAY TO DO IT!". In fact, in python there is almost always *MANY* ways to
> achieve the same output.=20

The koan reads:

There should be one-- and preferably only one --obvious way to do it.

You left out the rather important word "obvious".

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Question about code writing '% i, callback'

2015-12-01 Thread Ian Kelly
On Mon, Nov 30, 2015 at 7:44 PM, Dennis Lee Bieber
 wrote:
> On Mon, 30 Nov 2015 10:55:23 -0800 (PST), fl  declaimed
> the following:
>
>>Thanks Ian. I created the class because I want to use the original example
>>line
>>
>> UI.Button("button %s" % i, callback)
>>
>>Is there another way to use the above line without my class definition?
>>I do feel that my created class does not match well with the above line
>>because the first item "button %s" does not fit __self__ in the class.
>
> The first item passed to a method call is the instance object... In
> this case, whatever "UI" is bound to.
>
> If it helps, think of
>
> UI.Button("string", callback)
> as
> Button(UI, "string", callback)

This is only correct if "UI" is bound to an instance of a class and
"Button" is a method of that class. If UI is a class itself or a
module, then those are not equivalent.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Peter Otten
Mr Zaug wrote:

> That makes sense.
> 
> So I still can't see how to write the string object to a file whist naming
> the file with whatever values I provided for the NNN and BRAND variables.
> 
> Printing the contents of the string object is working with all the
> expected substitutions. Do I need to convert the string object into a file
> before I write it? Or do I need to open a new file and somehow stuff the
> string object into it?

Yes, open a new file and write the string using the write() method. You can 
use string formatting to build the filename, too:

text = ... # the string you want to write 

nnn = raw_input("What is the serial number of the site? ")
brand = raw_input("What is the brand, or product name? ")

filename = "{NNN}{BRAND}_farm.any".format(BRAND=brand, NNN=nnn)
with open(filename, "w") as outstream:
outstream.write(text)


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


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Mr Zaug
That makes sense. 

So I still can't see how to write the string object to a file whist naming the 
file with whatever values I provided for the NNN and BRAND variables.

Printing the contents of the string object is working with all the expected 
substitutions. Do I need to convert the string object into a file before I 
write it? Or do I need to open a new file and somehow stuff the string object 
into it?

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


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Peter Otten
Mr Zaug wrote:

> Actually, I don't understand what you mean by "all other braces." What
> braces are you talking about? The placeholders in the template file (the
> file being read in) have braces around them but they are not escaped.

The example you provide was

  $include "_dispatcher_publish_filters.any"
  /1000 { /type "allow"  /glob "* /CONTENT_PATH/*.html*" }
  /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }

If you want to use string formatting to replace CONTENT_PATH and DAMPATH in 
the above excerpt you have to change the template to

  $include "_dispatcher_publish_filters.any"
  /1000 {{ /type "allow"  /glob "* /{CONTENT_PATH}/*.html*" }}
  /1001 {{ /type "allow"  /glob "POST /{DAMPATH}/www/*.html *" }}


> Also, do I really need curly braces to tell Python what my placeholders
> are?

Let's take a slightly modified example to answer that one:

  $include "_dispatcher_publish_filters.any"
  /1000 { /type "allow"  /glob "* /CONTENT_PATH/*.html*" }
  /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }
  /1002 { /type "allow"  /glob "* /ALTERNATIVE_CONTENT_PATH/*.html*" }


If you try to fill in the CONTENT_PATH with 

data = data.replace("CONTENT_PATH", "foo")

the result will be

  $include "_dispatcher_publish_filters.any"
  /1000 { /type "allow"  /glob "* /foo/*.html*" }
  /1001 { /type "allow"  /glob "POST /DAMPATH/www/*.html *" }
  /1002 { /type "allow"  /glob "* /ALTERNATIVE_foo/*.html*" }

Look at the butchered line starting with /1002, a problem that MRAB already 
pointed out before. The braces are not necessary if the string you are 
replacing doesn't occur elsewhere in the template, but they make the 
replacement process both flexible and unambiguous.

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


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Mr Zaug
Actually, I don't understand what you mean by "all other braces." What braces 
are you talking about? The placeholders in the template file (the file being 
read in) have braces around them but they are not escaped. 

Also, do I really need curly braces to tell Python what my placeholders are?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Pylint-dev] Pylint 1.5.0 / Astroid 1.4.1 released

2015-12-01 Thread Claudiu Popa
On Tue, Dec 1, 2015 at 11:08 AM, Sylvain Thénault
 wrote:
> On 01 décembre 01:42, Claudiu Popa wrote:
>> Hello,
>
> Hi Claudiu,
>
>> I'm happy to announce you the release of Pylint 1.5.0,
>> respectively Astroid 1.4.1.
>>
>> It's been over a year since the last major release
>> and the amount of changes that were brought into pylint
>> in this time is humongous, with over 30 new checks
>> and tons of bug fixes.
>>
>> I would like to use this occasion for thanking for their contributions
>> the new committers who joined pylint's team in the past months,
>> ceridwen and Dmitry, as well as thanking the
>> contributors that made this release possible.
>
> Excellent! Congrat to this new core team which have realized a tremendous 
> amount
> of work.
>
>
> To be fair, there is also `pylint.extensions.check_elif` extension
> that emit message for 'else: if ' that could be written in 'elif '
>
> Regards,


Oups, sorry about that, it wasn't intentional. It seems it isn't
mentioned in the ChangeLog, which was the basis of my mail.


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


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Mr Zaug
Oh, that's much easier to read. Thanks!


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


Re: Exclude text within quotation marks and words beginning with a capital letter

2015-12-01 Thread Peter Otten
Kevin Glover wrote:

> I am working on a program that is written in Python 2.7 to be compatible
> with the POS tagger that I import from Pattern. The tagger identifies all
> the nouns in a text. I need to exclude from the tagger any text that is
> within quotation marks, and also any word that begins with an upper case
> letter (including words at the beginning of sentences).
> 
> Any advice on coding that would be gratefully received. Thanks.

How about removing them afterwards?

>>> def skip_quoted(pairs):
... quoted = False
... for a, b in pairs:
... if a == '"':
... quoted = not quoted
... elif not quoted:
... yield a, b
... 
>>> from pattern.en import tag
>>> [p for p in skip_quoted(tag('Did you say "Hello world"?')) if not p[0]
[0].isupper()]
[(u'you', u'PRP'), (u'say', u'VB'), (u'?', u'.')]


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


Re: New JSON encoding method proposal for custom objects

2015-12-01 Thread cescus92
> At the same place where you already found python-list, or here:
>  
> https://mail.python.org/mailman/listinfo/python-ideas

Yeah, I've found it after a simple search.. I thought it was like an hidden 
place for just some python's guru lol!

Thank you! :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New JSON encoding method proposal for custom objects

2015-12-01 Thread Peter Otten
cescu...@gmail.com wrote:

>> Go to python-ideas for a lengthy discussion ;)

> Where can I find it?

At the same place where you already found python-list, or here:
 
https://mail.python.org/mailman/listinfo/python-ideas

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


Re: New JSON encoding method proposal for custom objects

2015-12-01 Thread cescus92
Hello Burak, thank you for the reply.

> FWIW, Spyne can to the exact same thing -- i.e. serialize an object
> given its definition to whatever format you want. (currently xml, json,
> yaml and msgpack are supported).
My aim is to propose a built-in method to accomplish this common and simple 
task that, IMHO, shouln't require the use of extra code for legibility's sake.

Anyway the whole Spyne framework is very interesting, thank you for having 
shared that!
Probably it's going to be useful for a project of mine :)

Have a nice day,
Francesco
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-01 Thread Ulli Horlacher
Wolfgang Maier  wrote:

> I'm wondering whether you have a good reason to stick with a function. 

Easy handling, no programming overhead. Clean, orthogonal code.


> What you are trying to achieve seems to be easier and cleaner to 
> implement as a class:
> 
> class Counter (object):
> def __init__ (self, start_value=0):
> self.x = start_value
> 
> def __call__ (self):
> self.x += 1
> 
> 1) solves the renaming problem
> 2) allows you to have several counters around:
> 
> counter1 = Counter()
> counter2 = Counter()
> counter3 = Counter(35)
> counter1()
> counter2()
> counter1()
> print (counter1.x, counter2.x, counter3.x)

Implementing a counter was only an example for a static variable, not the
primary goal.

With a class, I find it irritating the first function call have to be
different than the subsequent ones:


def main():
  a=A(1)
  a(1)
  a(5)
  a(0)
  print(a.n)

class A(object):
  def __init__ (self,*arg):
self.n = 0

  def __call__(self,x):
self.n += 1
print('%d:' % self.n,x)

main()



-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python domain in China. This showed up on Python list

2015-12-01 Thread Laura Creighton
In a message of Tue, 01 Dec 2015 02:51:21 -0800, Chris Rebert writes:
>I hate to break it to you, but this seems to be just another of those
>come-ons spammed out by various scummy businesses that trawl WHOIS
>databases for people to scam into buying extra/unnecessary domain
>names. Google "chinese domain scam" for more info. I've received
>similar spams after having registered some .com domains that no
>corporation could possibly legitimately want the .cn equivalents of.

Ah...  Thank you Chris.  Sure fooled me.

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


Re: New JSON encoding method proposal for custom objects

2015-12-01 Thread Burak Arslan
hey,

On 11/30/15 14:35, cescu...@gmail.com wrote:
>
> Hello everyone and thank you for your interest!
>
> The Peter's code is very similar to what I think the default JSON encoder 
> should be.
>
> The advantage of the method that I propose is that you should not care 
> anymore about which encoder you're going to use even in case of different 
> class instances. Imagine if you could just do
>
>   json.dumps({[1,2,3], Obj(), [DifferentObj()] })
>
>

FWIW, Spyne can to the exact same thing -- i.e. serialize an object
given its definition to whatever format you want. (currently xml, json,
yaml and msgpack are supported). Here's a json example:

>>> from spyne import *
>>> from spyne.util.dictdoc import get_object_as_json, get_json_as_object
>>> get_object_as_json([1,2,3], Array(Integer))
'[1, 2, 3]'
>>>
>>> from datetime import datetime
>>>
>>> class SomeObject(ComplexModel):
... s = Unicode
... i = Integer
... dt = DateTime
...
>>> get_object_as_json(SomeObject(s='str', i=42, dt=datetime.now()),
complex_as=list)
'[42, "str", "2015-12-01T12:57:23.751631"]'
>>>
>>> get_json_as_object('[42, "str", "2015-12-01T12:55:21.777108"]',
SomeObject, complex_as=list)
SomeObject(i=42, s=u'str', dt=datetime.datetime(2015, 12, 1, 12, 55, 21,
777108))
>>>
>>>

More info: http://spyne.io

Best,
Burak

PS: The astute reader will notice that element order in SomeObject could
be totally random.

* In Python 3, we solve that by returning an odict() in the __prepare__
of the ComplexModel metaclass.
* In Python 2, we solve that by somehow getting hold of AST of the class
definition and deducing the order from there. Yes you read that right! I
know, it's horrible! Don't worry, it's turned off by default. We
recommend the workaround in [1] for Python 2. See [2] and [3] to see how
we integrated it.

[1]: http://spyne.io/docs/2.10/manual/03_types.html#complex
[2]: https://github.com/arskom/spyne/pull/313
[3]:
https://github.com/arskom/spyne/blob/2768c7ff0b5f58aa0e47859fcd69e5bb7aa31aba/spyne/util/meta.py

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


Exclude text within quotation marks and words beginning with a capital letter

2015-12-01 Thread Kevin Glover
I am working on a program that is written in Python 2.7 to be compatible with 
the POS tagger that I import from Pattern. The tagger identifies all the nouns 
in a text. I need to exclude from the tagger any text that is within quotation 
marks, and also any word that begins with an upper case letter (including words 
at the beginning of sentences).

Any advice on coding that would be gratefully received. Thanks.

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


Re: python response slow when running external DLL

2015-12-01 Thread Peter Otten
jf...@ms4.hinet.net wrote:

> Peter Otten at 2015/11/28 UTC+8 6:14:09PM wrote:
>> No, the point of both recipes is that tkinter operations are only ever
>> invoked from the main thread. The main thread has polling code that
>> repeatedly looks if there are results from the helper thread. As far I
>> understand the polling method has the structure
>> 
>> f():
>># did we get something back from the other thread?
>># a queue is used to avoid race conditions
>> 
>># if yes react.
>># var_status.set() goes here
>> 
>># reschedule f to run again in a few millisecs;
>># that's what after() does
> 
> Have no idea how the main thread poll on all those events (or it use a
> queue)? All I know now is that the main thread(mainloop()?) can be easily
> blocked by event handlers if the handler didn't run as a separate thread.
> 
>> > .
>> > .
>> > #do the rest
>> > var_status.set('Download...')
>> > _thread.start_new_thread(td_download, ())  #must use threading
>> > 
>> > def td_download():
>> > result = mydll.SayHello()
>> > if result:
>> > var_status.set("Download Fail at %s" % hex(result))
>> > showerror('Romter', 'Download Fail')
>> > else:
>> > var_status.set('Download OK')
>> > showinfo('Romter', 'Download OK')
>> 
>> As td_download() runs in the other thread the var_status.set() methods
>> are problematic.
> 
> No idea what kind of problem it will encounter. Can you explain?

While the var_status.set() invoked from the second thread modifies some 
internal data the main thread could kick in and modify (parts of) that same 
data, thus bringing tkinter into an broken state. A simple example that 
demonstrates the problem:

import random
import threading
import time

account = 70

def withdraw(delay, amount):
global account
if account >= amount:
print("withdrawing", amount)
account -= amount
else:
print("failed to withdraw", amount)

threads = []
for i in range(10):
t = threading.Thread(
target=withdraw,
kwargs=dict(delay=.1,
amount=random.randrange(1, 20)))
threads.append(t)
t.start()

for t in threads:
t.join()

Before every withdrawal there seems to be a check that ensures that there is 
enough money left, but when you run the script a few times you will still 
sometimes end with a negative balance. That happens when thread A finds 
enough money, then execution switches to thread B which also finds enough 
money, then both threads perform a withdrawal -- oops there wasn't enough 
money for both.
 
>> Another complication that inevitably comes with concurrency: what if the
>> user triggers another download while one download is already running? If
>> you don't keep track of all downloads the message will already switch to
>> "Download OK" while one download is still running.
> 
> Hummm...this thought never comes to my mind. After take a quick test I
> found, you are right, a second "download" was triggered immediately.
> That's a shock to me. I suppose the same event shouldn't be triggered
> again, or at least not triggered immediately, before its previous handler
> was completed. ...I will take a check later on Borland C++ builder to see
> how it reacts!
> 
> Anyway to prevent this happens? if Python didn't take care it for us.

A simple measure would be to disable the button until the download has 
ended.

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


Re: python domain in China. This showed up on Python list

2015-12-01 Thread Chris Rebert
On Tue, Dec 1, 2015 at 2:10 AM, Laura Creighton  wrote:
> I think we have just dodged a bullet, let us now go thank the
> nice people who sent us this and figure out how we should
> secure the domain.
>
> Laura
>
>
> --- Forwarded Message
>
> Return-Path: 
> Date: Tue, 1 Dec 2015 15:12:58 +0800
> From: "Ian Liu" 
> To: 
> Subject: python CN domain and keyword


I hate to break it to you, but this seems to be just another of those
come-ons spammed out by various scummy businesses that trawl WHOIS
databases for people to scam into buying extra/unnecessary domain
names. Google "chinese domain scam" for more info. I've received
similar spams after having registered some .com domains that no
corporation could possibly legitimately want the .cn equivalents of.

Additionally, the two most obvious relevant domains were already
registered by non-PSF parties years ago, and aren't set to expire
imminently. Per https://ewhois.cnnic.cn :

Domain Name: python.cn
Registrant: 北京开心杯科技有限公司
Registrant Contact Email: @happylatte.com
Registration Time: 2003-03-17 12:20:05
Expiration Time: 2017-03-17 12:48:36

Domain Name: python.org.cn
Registrant Contact Email: @lxl.cn
Registration Time: 2007-04-12 14:02:16
Expiration Time: 2016-04-12 14:02:16


Regards,
Chris
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Generate config file from template using Python search and replace.

2015-12-01 Thread Peter Otten
Mr Zaug wrote:

> On Monday, November 30, 2015 at 4:14:48 AM UTC-5, Peter Otten wrote:
>> Mr Zaug wrote:
>> 
>> > On Sunday, November 29, 2015 at 5:50:51 PM UTC-5, Peter Otten wrote:
>> >> Mr Zaug wrote:
>> >> 
>> >> > When I run this script on OS X El Capitan, I see,
>> >> >   
>> >> >   # permission sensitive cache
>> >> >   $include "_dispatcher_shared_auth-checker:
>> >> > 
>> >> > Was I supposed to incorporate it into the script I posted?
>> >> 
>> >> Are you referring to my post? I'm sorry, I can't make sense of your
>> >> question.
>> > 
>> > Yes. The snippet you posted went way over my head. When I ran it, it
>> > printed
>> > 
>> > # permission sensitive cache
>> >   $include "_dispatcher_shared_auth-checker:
>> 
>> It's hard to tell from that problem description what might have gone
>> wrong. However:
>> 
>> In your template file you have to enclose all words you want to replace
>> in braces ("you have foo options" becomes "you have {foo} options"), to
>> replace all literal { with {{ and all literal } with }}.
>> 
>> Did you do that?
> 
> Yup, I sure did. So here is my current script. The only remaining task now
> is figuring out how to write the contents to a new file.
> 
> #!/usr/bin/env python
> import os
> import sys
> 
> script, template_file = sys.argv
> print "Opening the template file..."
> 
> print "What is the serial number of the site?",
> nnn = raw_input()

[...]

> with open (template_file, "r") as a_string:
> data=a_string.read().replace('{SERVER_NAME}',
> server_name).replace('{BRAND}', brand).replace('{CONTENT_PATH}',
> content_path).replace('{DAMPATH}', dampath).replace('{ENV}',
> env).replace('{CACHE_DOCROOT}', cache_docroot)

If all other braces are properly escaped you can use format instead of 
replace:

 data = a_string.read().format(
 SERVER_NAME=server_name,
 BRAND=brand,
 CONTENT_PATH=content_path
 DAMPATH=dampath,
 ENV=env,
 CACHE_DOCROOT=cache_doc_root)



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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Peter Otten
Manolo Martínez wrote:

> On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
> > I'm trying to understand why vars() exists. Does anyone use it?
> 
> Well, I have this little podcast aggregator
> (https://github.com/manolomartinez/greg) that I and a bunch of other
> people use. I started writing it some years ago, and the code is a bit
> of a palimpsest, newer functionality reflecting my (somewhat) better
> understanding of the language. One of the oldest bits is this main()
> function:
> 
> def main():  # parse the args and call whatever function was 
selected
> try:
> args = parser.parse_args(sys.argv[1:])
> args.func(vars(args))
> except AttributeError as err:
> if str(err) == "\'Namespace\' object has no 
attribute \'func\'":
> parser.print_help()
> else:
> print("Something has gone wrong: 
{}".format(err), file = sys.stderr, flush = True)
>  
> 
> To judge by this thread, this is probably wrong/noobish?

What probably is typical for a beginner in that snippet is that you don't 
trust the exception system and handle exceptions that will never occur once 
the script is debugged. Just write

args = parser.parse_args()
args.func(vars(args))

Now vars(). I see nothing wrong with it, but when I look into one of your 
func implementations

> def info(args):  # Provides information of a number of feeds
> session = Session(args)
> if "all" in args["names"]:
> feeds = session.list_feeds()
> else:
> feeds = args["names"]
> for feed in feeds:
> pretty_print(session, feed)

I come to the conclusion that passing args directly could make your life 
easier:

def info(args):  
"""Provides information of a number of feeds"""
session = Session(args)
if "all" in args.names:
feeds = session.list_feeds()
else:
feeds = args.names
for feed in feeds:
pretty_print(session, feed)

As far as I can see there is only one place where the key is not a constant, 
and you can rewrite that from 

> try:
> if args[value]:
> return args[value]
> except KeyError:
> pass

to

try:
answer = getattr(args, value)
if answer: 
return answer
except AttributeError:
pass


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


Re: python domain in China. This showed up on Python list

2015-12-01 Thread Michiel Overtoom

Hi,

> On 01 Dec 2015, at 11:10, Laura Creighton  wrote:
> 
> I think we have just dodged a bullet, let us now go thank the
> nice people who sent us this and figure out how we should
> secure the domain.

I received exactly the same email a while ago, claiming that someone was 
registering the name 'Michiel' in China as 'internet keyword' (whatever that 
may be), and whether I knew them. I responded 'no', and have never since heard 
from them.

Greetings,

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


python domain in China. This showed up on Python list

2015-12-01 Thread Laura Creighton
I think we have just dodged a bullet, let us now go thank the
nice people who sent us this and figure out how we should
secure the domain.

Laura


--- Forwarded Message

Return-Path: 
Date: Tue, 1 Dec 2015 15:12:58 +0800
From: "Ian Liu" 
To: 
Subject: python CN domain and keyword
Message-ID: <20151201151310456...@chinaregistry.org.cn>
X-mailer: Foxmail 6, 13, 102, 15 [cn]
Mime-Version: 1.0

(Please forward this to your CEO, because this is urgent. Thanks)


We are a Network Service Company which is the domain name registration
center in Shanghai, China. On Nov 30, 2015, we received an application
from Huasu Holdings Ltd requested "python" as their internet keyword
and China (CN) domain names. But after checking it, we find this name
conflict with your company name or trademark. In order to deal with
this matter better, it's necessary to send email to you and confirm
whether this company is your distributor or business partner in China?

Kind regards


Ian Liu
General Manager 
China Registry (Headquarters)
8052, Douhai Building, No. 59 Baolian Road, 
Shanghai, China
Tel: +86 21 6191 8696
Mobile: +86 138 1642 8671
Fax: +86 21 6191 8697
Web: www.chinaregistry.org.cn
- -- 
https://mail.python.org/mailman/listinfo/python-list

--- End of Forwarded Message
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-01 Thread Wolfgang Maier

On 01.12.2015 09:26, Ulli Horlacher wrote:

Steven D'Aprano  wrote:


A better and more general test is:

if hasattr(a, 'x'): print('attribute of a')


Fine!

I have now:

def a(x=None):
   if not hasattr(a,'x'): a.x = 0
   a.x += 1
   print('%d:' % a.x,x)

This simply counts the calls of a()

But, when I rename the function I have to rename the attribute also.
Is it possible to refer the attribute automatically to its function?
Something like:

def a(x=None):
   if not hasattr(_function_,'x'): _function_.x = 0
   _function_.x += 1
   print('%d:' % _function_.x,x)





I'm wondering whether you have a good reason to stick with a function. 
What you are trying to achieve seems to be easier and cleaner to 
implement as a class:


class Counter (object):
def __init__ (self, start_value=0):
self.x = start_value

def __call__ (self):
self.x += 1

1) solves the renaming problem
2) allows you to have several counters around:

counter1 = Counter()
counter2 = Counter()
counter3 = Counter(35)
counter1()
counter2()
counter1()
print (counter1.x, counter2.x, counter3.x)

Cheers,
Wolfgang


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


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread Juha Nieminen
In comp.lang.c++ Skybuck Flying  wrote:
> Is Microsoft Windows secretly downloading childporn to your computer ?!

No, because Microsoft is too smart to commit economical suicide.

If a troyan/virus is doing so, that's not on Microsoft.

--- news://freenews.netfront.net/ - complaints: n...@netfront.net ---
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Pylint-dev] Pylint 1.5.0 / Astroid 1.4.1 released

2015-12-01 Thread Sylvain Thénault
On 01 décembre 01:42, Claudiu Popa wrote:
> Hello,

Hi Claudiu, 

> I'm happy to announce you the release of Pylint 1.5.0,
> respectively Astroid 1.4.1.
> 
> It's been over a year since the last major release
> and the amount of changes that were brought into pylint
> in this time is humongous, with over 30 new checks
> and tons of bug fixes.
> 
> I would like to use this occasion for thanking for their contributions
> the new committers who joined pylint's team in the past months,
> ceridwen and Dmitry, as well as thanking the
> contributors that made this release possible.

Excellent! Congrat to this new core team which have realized a tremendous amount
of work.
 
> Here are some of the major changes of this release:

[...] 

> - We also added a new 'extensions' component, which contains optional
>   checkers that needs to be activated explicitly.
> 
>   These includes 'extensions.check_docs', which verifies a bunch of
>   properties of the docstrings, such as checking that all function,
>   method and constructor parameters are mentioned
>   in the params and types part of the docstring. Also, it checks that
>   there are no naming inconsistencies between the signature and
>   the documentation, i.e. also report documented parameters that are missing
>   in the signature. This is important to find cases where parameters are
>   renamed only in the code, not in the documentation.
> 
>   Activate this checker with:
> 
>   --load-plugins=pylint.extensions.check_docs

To be fair, there is also `pylint.extensions.check_elif` extension
that emit message for 'else: if ' that could be written in 'elif '

Regards,
-- 
Sylvain Thénault, LOGILAB, Paris (01.45.32.03.12) - Toulouse (05.62.17.16.42)
Formations Python, Debian, Méth. Agiles: http://www.logilab.fr/formations
Développement logiciel sur mesure:   http://www.logilab.fr/services
CubicWeb, the semantic web framework:http://www.cubicweb.org
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-01 Thread Grobu
Perhaps you could use a parameter's default value to implement your 
static variable?


Like :
# -
>>> def test(arg=[0]):
... print arg[0]
... arg[0] += 1
...
>>> test()
0
>>> test()
1
# -

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


Re: static variables

2015-12-01 Thread Peter Otten
Ulli Horlacher wrote:

> Steven D'Aprano  wrote:
> 
>> A better and more general test is:
>> 
>> if hasattr(a, 'x'): print('attribute of a')
> 
> Fine!
> 
> I have now:
> 
> def a(x=None):
>   if not hasattr(a,'x'): a.x = 0
>   a.x += 1
>   print('%d:' % a.x,x)
> 
> This simply counts the calls of a()
> 
> But, when I rename the function I have to rename the attribute also.
> Is it possible to refer the attribute automatically to its function?
> Something like:
> 
> def a(x=None):
>   if not hasattr(_function_,'x'): _function_.x = 0
>   _function_.x += 1
>   print('%d:' % _function_.x,x)

Not directly, but there are workarounds:

def with_function(f):
return functools.partial(f, f)

@with_function
def foo(self, x=None):
if not hasattr(self, "x"):
self.x = 0
self.x += 1
print("{} called {} times".format(self.__name__, self.x))


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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Manolo Martínez
On 12/01/15 at 12:00pm, Steven D'Aprano wrote:
> I'm trying to understand why vars() exists. Does anyone use it?

Well, I have this little podcast aggregator
(https://github.com/manolomartinez/greg) that I and a bunch of other
people use. I started writing it some years ago, and the code is a bit
of a palimpsest, newer functionality reflecting my (somewhat) better
understanding of the language. One of the oldest bits is this main()
function:

def main():  # parse the args and call whatever function was selected
try:
args = parser.parse_args(sys.argv[1:])
args.func(vars(args))
except AttributeError as err:
if str(err) == "\'Namespace\' object has no attribute 
\'func\'":
parser.print_help()
else:
print("Something has gone wrong: 
{}".format(err), file = sys.stderr, flush = True)
 

To judge by this thread, this is probably wrong/noobish?

Cheers,
Manolo
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is Microsoft Windows secretly downloading childporn to your computer ?!

2015-12-01 Thread trolling tone

On 01.12.2015 03:19, Skybuck Flying wrote:

Hello,

The question is:

Is Microsoft Windows secretly downloading childporn to your computer ?!

How can you be sure ? It's closed source software.

It's downloading all kinds of crap via Windows Update.

Having childporn on your computer is a crime and can result into jail time.

I think it is safe to say that the era of closed source software is OVER.

You are responsible for what is on your computer !

Bye,
  Skybuck.


User agent Microsoft Windows Live Mail 15.4.3555.308
LOL
--
https://mail.python.org/mailman/listinfo/python-list


Re: static variables

2015-12-01 Thread Ulli Horlacher
Steven D'Aprano  wrote:

> A better and more general test is:
> 
> if hasattr(a, 'x'): print('attribute of a')

Fine!

I have now:

def a(x=None):
  if not hasattr(a,'x'): a.x = 0
  a.x += 1
  print('%d:' % a.x,x)

This simply counts the calls of a()

But, when I rename the function I have to rename the attribute also.
Is it possible to refer the attribute automatically to its function?
Something like:

def a(x=None):
  if not hasattr(_function_,'x'): _function_.x = 0
  _function_.x += 1
  print('%d:' % _function_.x,x)


-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


python CN domain and keyword

2015-12-01 Thread Ian Liu
(Please forward this to your CEO, because this is urgent. Thanks)


We are a Network Service Company which is the domain name registration center 
in Shanghai, China. On Nov 30, 2015, we received an application from Huasu 
Holdings Ltd requested "python" as their internet keyword and China (CN) domain 
names. But after checking it, we find this name conflict with your company name 
or trademark. In order to deal with this matter better, it's necessary to send 
email to you and confirm whether this company is your distributor or business 
partner in China?

Kind regards


Ian Liu
General Manager 
China Registry (Headquarters)
8052, Douhai Building, No. 59 Baolian Road, 
Shanghai, China
Tel: +86 21 6191 8696
Mobile: +86 138 1642 8671
Fax: +86 21 6191 8697
Web: www.chinaregistry.org.cn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tuesday 01 December 2015 18:22, eryk sun wrote:

> On Mon, Nov 30, 2015 at 7:00 PM, Steven D'Aprano 
> wrote:
>> Either way, vars() doesn't solve the problem. What problem does it solve?
> 
> vars() used to be the way to list local variables.

Oh, snap! Nice bit of detective work. So it's basically a left-over from 
when dinosaurs roamed the earth.



-- 
Steve

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


Re: Is vars() the most useless Python built-in ever?

2015-12-01 Thread Steven D'Aprano
On Tuesday 01 December 2015 16:54, Rick Johnson wrote:

> On Monday, November 30, 2015 at 7:01:14 PM UTC-6, Steven D'Aprano wrote:
>> I'm trying to understand why vars() exists. Does anyone use it?
> 
> I think your "mental dilemma" stems from the fact that python was
> originally created to be an easy language for noobs to learn (which it
> still mostly is), 

Python was never intended to be "merely" a teaching language. I think 
Guido's original vision was for it to be a glue language between C 
libraries, and a scripting language.


> however, over the years, feature creep has expanded this
> small general purpose language to include many specific applications. The
> "vars" function is a relic of the early days of Python and has not evolved
> because 99% of Python hackers find it to be useless. I mean, heck, print
> did not evolve until Py3! Outside of a few test sessions in my early days
> with Python, I don't remember ever using the vars function again.
> 
> Your lament does remind me of a pet peeve i have concerning Python, and
> that is, the lie about: "THERE SHOULD BE ONE (AND PREFERABLY ONLY ONE) WAY
> TO DO IT!". In fact, in python there is almost always *MANY* ways to
> achieve the same output.

You misunderstand the koan.

"There should be one way to do it" does not prohibit more than one way. 
(Although having multiple redundant ways is discouraged.) The koan exists to 
encourage the existence of *at least* one (but preferably only one) way to 
do it.

"It", of course, is not defined, as if fitting for a koan. (Koans are meant 
to make you think, and they also act as a way of separating the adults from 
the kiddies -- do you have the experience to grok the meaning of the koan?

For example, some people have been fooled by the apparent similarity of 
globals(), locals(), dir(), __dict__ and vars(), thinking that this is five 
ways to do the same thing, right? But no.

(1) globals() *always* returns the global namespace.

(2) locals() *always* returns the local namespace. It just happens that 
sometimes the local and global namespaces are the same.

(3) dir() is intended as a user-friendly introspection tool at the 
interactive interpreter. As a result, it is permitted to modify the list of 
names returned, and in fact it does, suppressing some names which the core 
developers deem insufficiently "interesting".

(4) __dict__ (in the sense of obj.__dict__) is the implementation, not part 
of Python's high-level interface. Attributes have to be stored somewhere, 
and Python chooses to reveal that in the documentation, nevertheless if you 
find yourself writing "__dict__" in production code, you're probably doing 
something wrong.


These three functions, and one attribute, are clearly related, but they are 
just as clearly solutions to four distinct problems. There may be a little 
overlap, but at their core, the "it" that they are the way to "do it" are 
very different things.

Which brings us to #5, vars():

"What is vars() good for?" is exactly what I'm asking. It seems to be the 
high-level interface to the implementation detail of __dict__, but I'm not 
sure that's needed. When that implementation changes -- classes using 
__slots__ instead of a dictionary -- we should expect that the high-level 
interface should adapt, otherwise what's the point of it? But it doesn't.

vars() also defaults to returning locals() for no good reason I can see. 
Whatever the "it" is that vars() is meant to do is a good question, but it 
clearly isn't the same "it" as that for globals(), locals() and dir().


> We may find this difficult to believe, but many a noob has been stumped by
> the following questions:
> 
> (1) How do you output a message without the print function?

*scratches head*

Why would you want to do that? print is clearly the "one obvious way" to 
output a message.



-- 
Steve

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