Re: [Python-ideas] Allow filter(items)

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 9:23 AM, Serhiy Storchaka  wrote:
> 06.08.13 10:34, Chris Angelico написав(ла):
>
>> Okay. Sounds like there's already an answer to those who want more
>> readability: Just use filter(bool,...). Maybe I'm just not seeing the
>> obvious problem with this version?
>
>
> Are `if bool(...)` or `if bool(...) == True` more readable than `if ...`?

They're more readable than 'if None(...)' is.

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


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Ben Finney wrote:

> Rui Maciel  writes:
> 
>> Is there any pythonic way to perform static typing?
> 
> I think no; static typing is inherently un-Pythonic.
> 
> Python provides strong, dynamic typing. Enjoy it!

Bummer. 


>> Does anyone care to enlighten a newbie?
> 
> Is there some specific problem you think needs static typing? Perhaps
> you could start a new thread, giving an example where you are having
> trouble and you think static typing would help.

It would be nice if some functions threw an error if they were passed a type 
they don't support or weren't designed to handle.  That would avoid having 
to deal with some bugs which otherwise would never happen.  

To avoid this sort of error, I've been testing arguments passed to some 
functions based on their type, and raising TypeError when necessariy, but 
surely there must be a better, more pythonic way to handle this issue.


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Steven D'Aprano wrote:

> On Mon, 05 Aug 2013 21:46:57 +0100, Rui Maciel wrote:
> 
>> Is there any pythonic way to perform static typing?  After searching the
>> web I've stumbled on a significant number of comments that appear to
>> cover static typing as a proof of concept , but in the process I've
>> found no tutorial on how to implement it.
> 
> Try Cobra instead. It's Python-like syntax, but allows static typing.
> 
> http://cobra-language.com/

Thanks for the suggestion, but switching Python for another programming 
language would defeat the purpose of learning Python.


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Reg secure python environment with web terminal emulator

2013-08-06 Thread Lakshmipathi.G
Hi -

We have a server running a web-based terminal emulator (based on shellinabox
for screen-casting  check www.webminal.org) that allows users to learn
simple bash commands. This Linux environment secured by things like quota,
selinux,ulimit  etc

Now some users are requesting python access. How to ensure python is executed
in a restricted environment. I came across
http://docs.python.org/2/library/restricted.html
but it seems like disabled in 2.3. Any thoughts on how we can safely
provide python access
to users.


I hope this is the correct mailing-list, If not please redirect me to
the right one.

Thanks for any help.

-- 

Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Gary Herron wrote:

> The Pythonic way is to *enjoy* the freedom and flexibility and power of
> dynamic typing.  If you are stepping out of a static typing language
> into Python, don't step just half way.  Embrace dynamic typing.  (Like
> any freedom, it can bite you at times, but that's no reason to hobble
> Python with static typing.)


What's the Python way of dealing with objects being passed to a function 
that aren't of a certain type, have specific attributes of a specific type, 
nor support a specific interface?


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Class hierarchy problem

2013-08-06 Thread BrJohan

I'm in need of help to solve this Python (ver. 3.3) problem:

I have a hierarchy of classes (SubA, SubAB, SubB, ..., SubBCA, 
SubC,...), each of which is inheriting from a chain of superclasses with 
a common baseclass(Sup) on top. (So far, no problem)


Now, I want to create instances of the correct subclasstype as decided 
by the common baseclass, like this:


i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)

where i can be of any class except Sup itself (as decided by Sup)

Now, the problem:

How to design the __new__() and __init__() methods for the various 
classes in order to achieve what I want?


(Some ten years I had the same problem (in a different context) and was 
helped by asking in this group. However, the solution has disappeared. 
Maybe the 2.x solution is not the same as in 3.x?)

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


Re: Module for dialoging with intercative programs, sockets, files, etc.

2013-08-06 Thread Ulrich Eckhardt

Am 05.08.2013 21:38, schrieb Olive:

I have found telnetlib which make very easy to interact with a telnet
server, especially the read_until command. I wonder if something
similar exits for other things that a telnet server.


It's not Python and I haven't played with it extensively, but there is a 
tool named "expect": https://en.wikipedia.org/wiki/Expect


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


Re: Newbie: static typing?

2013-08-06 Thread Joshua Landau
On 6 August 2013 10:01, Rui Maciel  wrote:
> Ben Finney wrote:
>
>> Rui Maciel  writes:
>>
>>> Is there any pythonic way to perform static typing?
>>
>> I think no; static typing is inherently un-Pythonic.
>>
>> Python provides strong, dynamic typing. Enjoy it!
>
> Bummer.

It's really not.


>>> Does anyone care to enlighten a newbie?
>>
>> Is there some specific problem you think needs static typing? Perhaps
>> you could start a new thread, giving an example where you are having
>> trouble and you think static typing would help.
>
> It would be nice if some functions threw an error if they were passed a type
> they don't support or weren't designed to handle.  That would avoid having
> to deal with some bugs which otherwise would never happen.
>
> To avoid this sort of error, I've been testing arguments passed to some
> functions based on their type, and raising TypeError when necessariy, but
> surely there must be a better, more pythonic way to handle this issue.

Unless you have a very good reason, don't do this. It's a damn pain
when functions won't accept my custom types with equivalent
functionality -- Python's a duck-typed language and it should behave
like one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 10:01 AM, Rui Maciel  wrote:
> It would be nice if some functions threw an error if they were passed a type
> they don't support or weren't designed to handle.  That would avoid having
> to deal with some bugs which otherwise would never happen.
>
> To avoid this sort of error, I've been testing arguments passed to some
> functions based on their type, and raising TypeError when necessariy, but
> surely there must be a better, more pythonic way to handle this issue.

def add_three_values(x,y,z):
return x+y+z

Do you want to test these values for compatibility? Remember, you
could take a mixture of types, as most of the numeric types can safely
be added. You can also add strings, or lists, but you can't mix them.
And look! It already raises TypeError if it's given something
unsuitable:

>>> add_three_values(1,"foo",[4,6])
Traceback (most recent call last):
  File "", line 1, in 
add_three_values(1,"foo",[4,6])
  File "", line 2, in add_three_values
return x+y+z
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The Pythonic way is to not care what the objects' types are, but to
simply use them.

In C++ and Java, it's usually assumed that the person writing a
function/class is different from the person writing the code that uses
it, and that each needs to be protected from each other. In Python,
it's assumed that either you're writing both halves yourself, or at
least you're happy to be aware of the implementation on the other
side. It saves a HUGE amount of trouble; for instance, abolishing
private members makes everything easier. This philosophical difference
does take some getting used to, but is so freeing. The worst it can do
is give you a longer traceback when a problem is discovered deep in
the call tree, and if your call stack takes more than a page to
display, that's code smell for another reason. (I've seen Ruby
tracebacks that are like that. I guess Ruby programmers get used to
locating the important part.)

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


Re: Newbie: static typing?

2013-08-06 Thread Steven D'Aprano
On Tue, 06 Aug 2013 10:05:57 +0100, Rui Maciel wrote:

> What's the Python way of dealing with objects being passed to a function
> that aren't of a certain type, have specific attributes of a specific
> type, nor support a specific interface?

Raise TypeError, or just let the failure occurs however it occurs, 
depending on how much you care about early failure.

Worst:

if type(obj) is not int:
raise TypeError("obj must be an int")


Better, because it allows subclasses:

if not isinstance(obj, int):
raise TypeError("obj must be an int")


Better still:

import numbers
if not isinstance(obj, numbers.Integer):
raise TypeError("obj must be an integer number")



All of the above is "look before you leap". Under many circumstances, it 
is "better to ask for forgiveness than permission" by just catching the 
exception:

try:
flag = obj & 8
except TypeError:
flag = False


Or just don't do anything:


flag = obj & 8


If obj is the wrong type, you will get a perfectly fine exception at run-
time. Why do extra work do try to detect the failure when Python will do 
it for you?



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


Re: Newbie: static typing?

2013-08-06 Thread Joshua Landau
On 6 August 2013 10:05, Rui Maciel  wrote:
> Gary Herron wrote:
>
>> The Pythonic way is to *enjoy* the freedom and flexibility and power of
>> dynamic typing.  If you are stepping out of a static typing language
>> into Python, don't step just half way.  Embrace dynamic typing.  (Like
>> any freedom, it can bite you at times, but that's no reason to hobble
>> Python with static typing.)
>
> What's the Python way of dealing with objects being passed to a function
> that aren't of a certain type, have specific attributes of a specific type,
> nor support a specific interface?

What's the actual problem you're facing? Where do you feel that you
need to verify types?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class hierarchy problem

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 10:10 AM, BrJohan  wrote:
> Now, I want to create instances of the correct subclasstype as decided by
> the common baseclass, like this:
>
> i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)
>
> where i can be of any class except Sup itself (as decided by Sup)

Can you do this as a factory function instead of the class itself?
Then all you need to do is call the appropriate class.

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


Re: Class hierarchy problem

2013-08-06 Thread Peter Otten
BrJohan wrote:

> I'm in need of help to solve this Python (ver. 3.3) problem:
> 
> I have a hierarchy of classes (SubA, SubAB, SubB, ..., SubBCA,
> SubC,...), each of which is inheriting from a chain of superclasses with
> a common baseclass(Sup) on top. (So far, no problem)
> 
> Now, I want to create instances of the correct subclasstype as decided
> by the common baseclass, like this:
> 
> i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)
> 
> where i can be of any class except Sup itself (as decided by Sup)
> 
> Now, the problem:
> 
> How to design the __new__() and __init__() methods for the various
> classes in order to achieve what I want?
> 
> (Some ten years I had the same problem (in a different context) and was
> helped by asking in this group. However, the solution has disappeared.
> Maybe the 2.x solution is not the same as in 3.x?)

Keep it simple, use a function:

def make(*args):
class_ = deduce_correct_class(*args)
return class_(*args)

That way you won't even need any __new__() methods.

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


Re: Class hierarchy problem

2013-08-06 Thread Steven D'Aprano
On Tue, 06 Aug 2013 11:10:17 +0200, BrJohan wrote:

> I'm in need of help to solve this Python (ver. 3.3) problem:
> 
> I have a hierarchy of classes (SubA, SubAB, SubB, ..., SubBCA,
> SubC,...), each of which is inheriting from a chain of superclasses with
> a common baseclass(Sup) on top. (So far, no problem)


Well, I don't know about that, a deep and complex chain of super- and sub-
classes already sounds like a problem. But putting that aside...


> Now, I want to create instances of the correct subclasstype as decided
> by the common baseclass, like this:
>   
> i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)

Inheritance doesn't, or at least shouldn't, work like that. The 
superclasses shouldn't be expected to know about their subclasses. 
Knowledge goes the other way: each class knows its parents, and so 
recursively can go all the way to the common base class.


> where i can be of any class except Sup itself (as decided by Sup)
> 
> Now, the problem:
> 
> How to design the __new__() and __init__() methods for the various
> classes in order to achieve what I want?

You don't :-)

Instead, have a factory function:

def sup(args):
if args:
return Sup(...)
elif condition():
return SupA(...)
elif condition2() or condition3():
return SupB(...)
...


sort of thing.


Another possibility would be to start with the child class, and give it 
the ability to return an instance of itself, or its direct parent. 
Completely untested:


class SupABC(SupABB):
def __new__(cls, args):
if condition():
# Return an instance of myself.
...
 else:
# Let my parent (maybe) return an instance.
return SupABB(args)


Either way, the design risks becoming a horrible mess, but you might be 
able to use it. Good luck!


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


Re: Source code to identify user through browser?

2013-08-06 Thread Gilles
On Wed, 05 Jun 2013 15:08:54 +0200, Gilles  wrote:
>I was wondering if some Python module were available to identify a
>user through their browser, like it's done on the Panopticlick site:
>
>http://panopticlick.eff.org/

It appears that flash cookies is a better solution to keep most trolls
away from a forum/blog:

www.stackoverflow.com/questions/216542/

Still, I wish there a browser that could run in real incognito mode,
ie. would only send the minimum amount of infos to the server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Joshua Landau wrote:

> Unless you have a very good reason, don't do this. It's a damn pain
> when functions won't accept my custom types with equivalent
> functionality -- Python's a duck-typed language and it should behave
> like one.

In that case what's the pythonic way to deal with standard cases like this 
one?


class SomeModel(object):
def __init__(self):
self.label = "this is a label attribute"

def accept(self, visitor):
visitor.visit(self)
print("visited: ", self.label)


class AbstractVisitor(object):
def visit(self, element):
pass


class ConcreteVisitorA(AbstractVisitor):
def visit(self, element):
element.label = "ConcreteVisitorA operated on this model"

class ConcreteVisitorB(AbstractVisitor):
def visit(self, element):
element.label = "ConcreteVisitorB operated on this model"


model = SomeModel()

operatorA = ConcreteVisitorA()

model.accept(operatorA)

operatorB = ConcreteVisitorB()

model.accept(operatorA)

not_a_valid_type = "foo"

model.accept(not_a_valid_type)



Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Joshua Landau wrote:

> What's the actual problem you're facing? Where do you feel that you
> need to verify types?

A standard case would be when there's a function which is designed expecting 
that all operands support a specific interface or contain specific 
attributes.

In other words, when passing an unsupported type causes problems.


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Rui Maciel
Chris Angelico wrote:

> On Tue, Aug 6, 2013 at 10:01 AM, Rui Maciel  wrote:
>> It would be nice if some functions threw an error if they were passed a
>> type
>> they don't support or weren't designed to handle.  That would avoid
>> having to deal with some bugs which otherwise would never happen.
>>
>> To avoid this sort of error, I've been testing arguments passed to some
>> functions based on their type, and raising TypeError when necessariy, but
>> surely there must be a better, more pythonic way to handle this issue.
> 
> def add_three_values(x,y,z):
> return x+y+z
> 
> Do you want to test these values for compatibility? Remember, you
> could take a mixture of types, as most of the numeric types can safely
> be added. You can also add strings, or lists, but you can't mix them.
> And look! It already raises TypeError if it's given something
> unsuitable:

If the type problems aren't caught right away when the invalid types are 
passed to a function then the problem may only manifest itself in some far 
away point in the code, making this bug needlessly harder to spot and fix, 
and making the whole ordeal needlessly too time consuming.


Rui Maciel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Devyn Collier Johnson


On 08/05/2013 10:19 PM, MRAB wrote:

On 06/08/2013 03:00, Devyn Collier Johnson wrote:

I am wanting to sort a plain text file alphanumerically by the lines. I
have tried this code, but I get an error. I assume this command does not
accept newline characters.


  >>> file = open('/home/collier/pytest/sort.TXT', 'r').read()


That returns the file as a single string.


  >>> print(file)
z
c
w
r
h
s
d


  >>> file.sort() #The first blank line above is from the file. I do not
know where the second comes from.
Traceback (most recent call last):
File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'


Strings don't have a sort method.


I had the parameters (key=str.casefold, reverse=True), but I took those
out to make sure the error was not with my parameters.

Specifically, I need something that will sort the lines. They may
contain one word or one sentence with punctuation. I need to reverse the
sorting ('z' before 'a'). The case does not matter ('a' = 'A').

I have also tried this without success:

  >>> file.sort(key=str.casefold, reverse=True)
Traceback (most recent call last):
File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'


Try this:

lines = open('/home/collier/pytest/sort.TXT', 'r').readlines()
lines.sort()


Actually, a more Pythonic way these days is to use the 'with' statement:

with open('/home/collier/pytest/sort.TXT') as file:
lines = file.readlines()

lines.sort()



Thanks! That works well. After I run your command, I run

print(''.join(lines))

to get the sorted output. Even the parameters work without issues.

lines.sort(reverse=True, key=str.casefold)


Mahalo,

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


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Devyn Collier Johnson


On 08/05/2013 10:19 PM, MRAB wrote:

On 06/08/2013 03:00, Devyn Collier Johnson wrote:

I am wanting to sort a plain text file alphanumerically by the lines. I
have tried this code, but I get an error. I assume this command does not
accept newline characters.


  >>> file = open('/home/collier/pytest/sort.TXT', 'r').read()


That returns the file as a single string.


  >>> print(file)
z
c
w
r
h
s
d


  >>> file.sort() #The first blank line above is from the file. I do not
know where the second comes from.
Traceback (most recent call last):
File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'


Strings don't have a sort method.


I had the parameters (key=str.casefold, reverse=True), but I took those
out to make sure the error was not with my parameters.

Specifically, I need something that will sort the lines. They may
contain one word or one sentence with punctuation. I need to reverse the
sorting ('z' before 'a'). The case does not matter ('a' = 'A').

I have also tried this without success:

  >>> file.sort(key=str.casefold, reverse=True)
Traceback (most recent call last):
File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'


Try this:

lines = open('/home/collier/pytest/sort.TXT', 'r').readlines()
lines.sort()


Actually, a more Pythonic way these days is to use the 'with' statement:

with open('/home/collier/pytest/sort.TXT') as file:
lines = file.readlines()

lines.sort()



Thanks! That works well. After I run your command, I run

print(''.join(lines))

to get the sorted output. Even the parameters work without issues.

lines.sort(reverse=True, key=str.casefold)


Mahalo,

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


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Devyn Collier Johnson


On 08/05/2013 11:49 PM, alex23 wrote:

On 6/08/2013 1:12 PM, Joshua Landau wrote:

Because it's bad to open files without a with unless you know what
you're doing, use a with:

 with open('/home/collier/pytest/__sort.TXT') as file:
 sorted(file, key=str.casefold, reverse=True)


Shouldn't that be:

with open('/home/collier/pytest/__sort.TXT') as file:
data = file.readlines()
sorted(data, key=str.casefold, reverse=True)

I'm tempted to say "HINT #5: don't provide a solution without testing 
it first" but that would be pretty obnoxious.
I tried Joshua's suggestion in Python3.3 and it worked. What version of 
Python are you using?


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


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Devyn Collier Johnson


On 08/05/2013 11:12 PM, Joshua Landau wrote:
On 6 August 2013 03:00, Devyn Collier Johnson > wrote:


I am wanting to sort a plain text file alphanumerically by the
lines. I have tried this code, but I get an error. I assume this
command does not accept newline characters.


HINT #1: Don't assume that without a reason. It's wrong.

>>> file = open('/home/collier/pytest/sort.TXT', 'r').read()


HINT #2: Don't lie. "file" is not a file so you probably shouldn't 
call it one. It's the contents of a file object.


>>> print(file)
z
c
w
r
h
s
d


>>> file.sort() #The first blank line above is from the file. I do
not know where the second comes from.
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'


HINT #3: *Read*. What does it say?

AttributeError: 'str' object has no attribute 'sort'

Probably your problem, then, is that a 'str' object has no attribute 
'sort'. That's what it says.


"file" is a "'str' object". You are accessing the 'sort' attribute 
which it doesn't have.


I had the parameters (key=str.casefold, reverse=True), but I took
those out to make sure the error was not with my parameters.


HINT #4: Don't just guess what the problem is. The answer is in the error.

Specifically, I need something that will sort the lines. They may
contain one word or one sentence with punctuation. I need to
reverse the sorting ('z' before 'a'). The case does not matter
('a' = 'A').

I have also tried this without success:

>>> file.sort(key=str.casefold, reverse=True)
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'str' object has no attribute 'sort'




So you want to sort your string by lines. Rather than trying to abuse 
a .sort attribute that patently doesn't exist, just use sorted OR 
convert to a list first.


sorted(open('/home/collier/pytest/sort.TXT'), key=str.casefold, 
reverse=True)


Because it's bad to open files without a with unless you know what 
you're doing, use a with:


with open('/home/collier/pytest/sort.TXT') as file:
sorted(file, key=str.casefold, reverse=True)


Thanks for the advice Joshua. I find these tips very useful. However, 
how would I close the files, or would they close after the "with" 
construct is complete?


Mahalo,

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


[GUI] Good frameworks for Windows/Mac?

2013-08-06 Thread Gilles
Hello

I need to write a small GUI application that should run on Windows and
Mac.

What open-source framework would you recommend? I just need basic
widgets (button, listbox, etc.) and would rather a solution that can
get me up and running fast.

I know about wxWidgets and Qt: Are there other good options I should
know about?

Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python script as SMTP server for outgoing e-mails?

2013-08-06 Thread Gilles
On Sat, 3 Aug 2013 06:47:07 -0500 (CDT), Wayne Werner
 wrote:
>Have you checked Kenneth Rietz's inbox.py[1]? It's fairly simple to 
>use/extend and might fit your modest needs.
>
>
>-W
>
>[1]:https://crate.io/packages/inbox/

Thanks. I'll check it out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python script as SMTP server for outgoing e-mails?

2013-08-06 Thread Gilles
On Sat, 03 Aug 2013 21:41:16 -0400, Kevin Walzer 
wrote:
>For what it's worth, that hasn't been my experience.

Thanks for the feedback. I'll experiment and see how it goes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 11:28 AM, Rui Maciel  wrote:
> Chris Angelico wrote:
>> def add_three_values(x,y,z):
>> return x+y+z
>>
>> Do you want to test these values for compatibility? Remember, you
>> could take a mixture of types, as most of the numeric types can safely
>> be added. You can also add strings, or lists, but you can't mix them.
>> And look! It already raises TypeError if it's given something
>> unsuitable:
>
> If the type problems aren't caught right away when the invalid types are
> passed to a function then the problem may only manifest itself in some far
> away point in the code, making this bug needlessly harder to spot and fix,
> and making the whole ordeal needlessly too time consuming.

There are two problems that can result from not checking:

1) The traceback will be deeper and may be less clear.

2) Some code will be executed and then an exception thrown.

If #2 is a problem, then you write checks in. (But be aware that
exceptions can be thrown from all sorts of places. It's usually better
to write your code to cope with exceptions than to write it to check
its args.) But that's a highly unusual case. With >99% of Python
scripts, it won't matter; programming errors are corrected by editing
the source and rerunning the program from the top. (There ARE
exceptions to this, but in Python they're relatively rare. In some of
my serverside programming (usually in Pike), I have to code in *much*
better protection than this. But if you're doing that sort of thing,
you'll know.)

So the real problem here is that, when there's a bug, the traceback is
longer and perhaps unclear. This is at times a problem, but it's not
as big a problem as the maintenance burden of all those extra type
checks. You might have a bug that takes you an extra few minutes to
diagnose because it's actually caused half way up the call stack (or,
worse, it doesn't come up in testing at all and it slips through into
production), but you save hours and hours of fiddling with the type
checks, and perhaps outright fighting them when you want to do
something more unusual. Or you write six versions of a function, with
different type checking. Any of these scenarios is, in my opinion, far
worse than the occasional bit of extra debugging work.

Like everything, it's a tradeoff. And if your function signatures are
sufficiently simple, you won't often get the args wrong anyway.

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


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
 wrote:
> with open('/home/collier/pytest/sort.TXT') as file:
> sorted(file, key=str.casefold, reverse=True)
>
>
> Thanks for the advice Joshua. I find these tips very useful. However, how
> would I close the files, or would they close after the "with" construct is
> complete?


That's the whole point of 'with'. It calls open(), then calls
__enter__, and it guarantees to call __exit__ before executing any
code following the with block. With a file object, __exit__ will close
the file.

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


Re: Can someone suggest better resources for learning sqlite3? I wanted to use the Python library but I don't know sql.

2013-08-06 Thread Gilles
On Sat, 3 Aug 2013 10:57:32 -0700 (PDT), Aseem Bansal
 wrote:
>I found Python3's sqlite3 library. I found that I needed sql commands for 
>using it.
>
>I have tried sql.learncodethehardway but it isn't complete yet. I tired 
>looking on stackoverflow's  sql tag also but nothing much there.

It'll be easier to read tutorials specifically meant to use Sqlite
with Python:

www.google.com/search?q=python+sqlite+examples
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a running tally/ definitely new to this

2013-08-06 Thread gratedmedia
Yes I want to store an amount of money which will change from many places 
within the code. Absolutely correct.  I am very "green" to this, if you're 
familiar, with "dopewars" the concept is very similar. 

for my practice trials I used.. selection_b = input()

 and manually input an amount of money, and used a loop of:

loop = 1
while loop < 5: 

just to get a feel of how it would work but, every time I travel to a new 
destination and buy something the amount of money is reset. And I am working to 
prevent this so that I can maintain a running tally until the loop is complete. 
  
> 
> 
> 
> 
> I currently working on a game, where I need to maintain a running tally of 
> money, as the player makes purchases as they navigate thru game.   I not 
> exactly sure how to do this in python.  I know it is a fairly basic step, 
> nonetheless.  Any assistance would be greatly appreciated.
> 
> 
> 
> 
> 
> If I understand correctly you want to store the amount of money in a variable 
> as a number that can be changed from many places within the code.
> 
> 
> Say you have:
> 
> 
> 
> 
>     money = 0
> 
> 
>     def do_some_adventuring():
>         ... # Add some money
> 
> 
> You can "add some money" with:
> 
> 
> 
>         global money # Allow changing money from within the function
> 
>         money += 10 # for example
> 
> 
> Is that it?
> 
> 
> 
> 
> 
> Note that normally you'd have some class of player with a money attribute 
> which can be accessed, but as a guess from the question I'm not sure you know 
> about classes yet.

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


Re: [GUI] Good frameworks for Windows/Mac?

2013-08-06 Thread Vlastimil Brom
2013/8/6 Gilles :
> Hello
>
> I need to write a small GUI application that should run on Windows and
> Mac.
>
> What open-source framework would you recommend? I just need basic
> widgets (button, listbox, etc.) and would rather a solution that can
> get me up and running fast.
>
> I know about wxWidgets and Qt: Are there other good options I should
> know about?
>
> Thank you.
> --
> http://mail.python.org/mailman/listinfo/python-list

Hi,
I mostly use wxPython myself, but if you just need some basic widgets
and not some very complex or non-standard layouts, the tkinter -
available in the standard library - might be perfectly viable.
http://docs.python.org/3.3/library/tk.html
The more recent versions of python also support ttk and Tix which has
further possibilities, styling etc.
There is further e.g. Python GUI
http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

and several others
http://wiki.python.org/moin/GuiProgramming

hth,
  vbr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Joshua Landau
On 6 August 2013 11:52, Chris Angelico  wrote:
> On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
>  wrote:
>> with open('/home/collier/pytest/sort.TXT') as file:
>> sorted(file, key=str.casefold, reverse=True)
>>
>>
>> Thanks for the advice Joshua. I find these tips very useful. However, how
>> would I close the files, or would they close after the "with" construct is
>> complete?
>
>
> That's the whole point of 'with'. It calls open(),

To be pedantic, it does not. open is called by the time the with gets involved.

> then calls
> __enter__, and it guarantees to call __exit__ before executing any
> code following the with block. With a file object, __exit__ will close
> the file.


To make it more obvious for Devyn¹, with is used any time you need a
simple guarantee of when things are "closed", for any particular
meaning. One popular usage, just as a taster, is with changing
directories so that the original directory is restored upon completion
of the sub-tasks.

¹ And so it doesn't look like I wrote a whole post to be pedantic
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Working with XML/XSD

2013-08-06 Thread Verde Denim
On 08/05/2013 06:56 PM, David Barroso wrote:
> Hello,
> I was wondering if someone could point me in the right direction. I
> would like to develop some scripts to manage Cisco routers and
> switches using XML. However, I am not sure where to start. Does
> someone have some experience working with XML, Schemas and things like
> that? Which libraries do you use? Do you know of any good tutorial?
>
> Thanks!
>
> David
>
>
W3C has a decent primer for XML (w3schools.com/xml/). I have a couple of
O'Reilly publications on the topic that are ok as well. There's a site
dedicated to the subject at xmlnews.org, and someone told me about a
course available at xmlmaster.org. I also found a short preso at
oreilly.com called the Eight Minute XML tutorial on automating system
administration so that's probably got some promise in the area you're
looking for.

hth

-- 
Regards

Jack
Boston Tea Party, Coercive Acts, Powder Alarm, Revolution
Lessons (Mistakes) not learned are bound to be repeated.

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


Re: [GUI] Good frameworks for Windows/Mac?

2013-08-06 Thread Jordi Riera
Hey

you can build GUIs with tkinter . Easy
but not as powerful than PyQt can be.
I think it is os agnostic.

Regards,
Jordi


On Tue, Aug 6, 2013 at 12:35 PM, Gilles  wrote:

> Hello
>
> I need to write a small GUI application that should run on Windows and
> Mac.
>
> What open-source framework would you recommend? I just need basic
> widgets (button, listbox, etc.) and would rather a solution that can
> get me up and running fast.
>
> I know about wxWidgets and Qt: Are there other good options I should
> know about?
>
> Thank you.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
- Jordi Riera, Connecting people.
+33 662217507
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone suggest better resources for learning sqlite3? I wanted to use the Python library but I don't know sql.

2013-08-06 Thread Jordi Riera
Hey,

can't you use django to deal with your sqlite?
If so, django modelsare
a smart way to do.

Regards,
Jordi


On Tue, Aug 6, 2013 at 12:51 PM, Gilles  wrote:

> On Sat, 3 Aug 2013 10:57:32 -0700 (PDT), Aseem Bansal
>  wrote:
> >I found Python3's sqlite3 library. I found that I needed sql commands for
> using it.
> >
> >I have tried sql.learncodethehardway but it isn't complete yet. I tired
> looking on stackoverflow's  sql tag also but nothing much there.
>
> It'll be easier to read tutorials specifically meant to use Sqlite
> with Python:
>
> www.google.com/search?q=python+sqlite+examples
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
- Jordi Riera, Connecting people.
+33 662217507
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Devyn Collier Johnson


On 08/06/2013 06:52 AM, Chris Angelico wrote:

On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
 wrote:

 with open('/home/collier/pytest/sort.TXT') as file:
 sorted(file, key=str.casefold, reverse=True)


Thanks for the advice Joshua. I find these tips very useful. However, how
would I close the files, or would they close after the "with" construct is
complete?


That's the whole point of 'with'. It calls open(), then calls
__enter__, and it guarantees to call __exit__ before executing any
code following the with block. With a file object, __exit__ will close
the file.

ChrisA


Thanks! Now I see why using "with" is a better way to write the code.

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


Re: Sort lines in a plain text file alphanumerically

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 12:44 PM, Joshua Landau  wrote:
> On 6 August 2013 11:52, Chris Angelico  wrote:
>> On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
>>  wrote:
>>> with open('/home/collier/pytest/sort.TXT') as file:
>>> sorted(file, key=str.casefold, reverse=True)
>>>
>>>
>>> Thanks for the advice Joshua. I find these tips very useful. However, how
>>> would I close the files, or would they close after the "with" construct is
>>> complete?
>>
>>
>> That's the whole point of 'with'. It calls open(),
>
> To be pedantic, it does not. open is called by the time the with gets 
> involved.
>

The entire statement does. Yes, it's not 'with' that does that, but it
is called. Anyway, that's detaily stuff :)

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


Re: Newbie: static typing?

2013-08-06 Thread Burak Arslan
On 08/06/13 13:12, Rui Maciel wrote:
> Joshua Landau wrote:
>
>> What's the actual problem you're facing? Where do you feel that you
>> need to verify types?
> A standard case would be when there's a function which is designed expecting 
> that all operands support a specific interface or contain specific 
> attributes.
>
> In other words, when passing an unsupported type causes problems.
>

Hi,

First, let's get over the fact that, with dynamic typing, code fails at
runtime. Irrespective of language, you just shouldn't ship untested
code, so I say that's not an argument against dynamic typing.

This behaviour is only a problem when code fails *too late* into the
runtime -- i.e. when you don't see the offending value in the stack trace.

For example, consider you append values to a list and the values in that
list get processed somewhere else. If your code fails because of an
invalid value, your stack trace is useless, because that value should
not be there in the first place. The code should fail when appending to
that list and not when processing it.

The "too late" case is a bit tough to illustrate. This could be a rough
example: https://gist.github.com/plq/6163839 Imagine that the list there
is progressively constructed somewhere else in the code and later
processed by the sq_all function. As you can see, the stack trace is
pretty useless as we don't see how that value got there.

In such cases, you do need manual type checking.

Yet, as someone else noted, naively using isinstance() for type checking
breaks duck typing. So you should read up on abstract base classes:
http://docs.python.org/2/glossary.html#term-abstract-base-class

These said, I've been writing Python for several years now, and I only
needed to resort to this technique only once. (i was working on a
compiler) Most of the time, you'll be just fine without any manual type
checking.

Best regards,
Burak


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


Re: Working with XML/XSD

2013-08-06 Thread Burak Arslan
On 08/06/13 01:56, David Barroso wrote:
> Hello,
> I was wondering if someone could point me in the right direction. I
> would like to develop some scripts to manage Cisco routers and
> switches using XML. However, I am not sure where to start. Does
> someone have some experience working with XML, Schemas and things like
> that? Which libraries do you use? Do you know of any good tutorial?
>

Hi,

I develop Spyne (http://spyne.io), it does let you define Xml Schema
types, generate the Schema documents, (and in the upcoming release,
parse them) and also does both serialization and deserialization of
python objects from and to xml according to definitions in the xml
schema. It also does RPC :)

In case you don't want to use a framework, use lxml, it's a very good
xml manipulation library based on libxml2/libxslt. You can use
lxml.objectify for xml serialization as well.

Best,
Burak

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


Re: Newbie: static typing?

2013-08-06 Thread Antoon Pardon
Op 06-08-13 15:27, Burak Arslan schreef:
> On 08/06/13 13:12, Rui Maciel wrote:
>> Joshua Landau wrote:
>>
>>> What's the actual problem you're facing? Where do you feel that you
>>> need to verify types?
>> A standard case would be when there's a function which is designed expecting 
>> that all operands support a specific interface or contain specific 
>> attributes.
>>
>> In other words, when passing an unsupported type causes problems.
>>
> 
> Hi,
> 
> First, let's get over the fact that, with dynamic typing, code fails at
> runtime. Irrespective of language, you just shouldn't ship untested
> code, so I say that's not an argument against dynamic typing.

Why not? Can ease of development not be a consideration? So if some
kind of faults are easier to detect at compile time if you have static
typing than if you have to design a test for them, I don't see why that
can't be an argument.

-- 
Antoon Pardon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class hierarchy problem

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 2:58 PM, BrJohan  wrote:
> On 06/08/2013 11:30, Chris Angelico wrote:
>>
>> On Tue, Aug 6, 2013 at 10:10 AM, BrJohan  wrote:
>>>
>>> Now, I want to create instances of the correct subclasstype as decided by
>>> the common baseclass, like this:
>>>
>>> i = Sup(args_allowing_the_baseclass_to_deduce_correct_subclass)
>>>
>>> where i can be of any class except Sup itself (as decided by Sup)
>>
>>
>> Can you do this as a factory function instead of the class itself?
>> Then all you need to do is call the appropriate class.
>>
>> ChrisA
>>
>
> My classhierarchy is like a multilevel tree where each non-leaf node (class)
> is given knowledge about its nearest subclasses and their 'capacities'.
>
> So, my idea is to let the 'upper' class recursively choose which of its
> nearest subclasses is the 'correct' one, until approaching a 'leaf' class
> from which the instance should be created. And, given my knowledge that a
> solution along the lines of this idea has been designed and was working, I'm
> still hopeful ... (or I'll have to investigate all those old backup-DVDs)

[ responding on-list - I hope it was mere oversight that had this come
privately to me alone ]

This is code smell; this recursive search for the "right" class seems
likely to be wrong. Can you have the classes perhaps register
themselves in some way? On what basis is a superclass to determine
that one of its subclasses should handle this request?

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


Re: Newbie: static typing?

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 2:57 PM, Antoon Pardon
 wrote:
> Op 06-08-13 15:27, Burak Arslan schreef:
>> On 08/06/13 13:12, Rui Maciel wrote:
>>> Joshua Landau wrote:
>>>
 What's the actual problem you're facing? Where do you feel that you
 need to verify types?
>>> A standard case would be when there's a function which is designed expecting
>>> that all operands support a specific interface or contain specific
>>> attributes.
>>>
>>> In other words, when passing an unsupported type causes problems.
>>>
>>
>> Hi,
>>
>> First, let's get over the fact that, with dynamic typing, code fails at
>> runtime. Irrespective of language, you just shouldn't ship untested
>> code, so I say that's not an argument against dynamic typing.
>
> Why not? Can ease of development not be a consideration? So if some
> kind of faults are easier to detect at compile time if you have static
> typing than if you have to design a test for them, I don't see why that
> can't be an argument.

Sure, which is why I like working in Pike, which does have static type
declarations (when you want them; they can get out the way when you
don't). But there will always be, regardless of your language,
criteria that static typing cannot adequately handle, so just write
your code to cope with exceptions - much easier. If the exception's
never thrown, the bug can't be all that serious; otherwise, just deal
with it when you find it, whether that be in initial testing or years
later in production. There WILL BE such errors - that's a given. Deal
with them, rather than trying to eliminate them.

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


Re: Newbie: static typing?

2013-08-06 Thread Eric S. Johansson
On Tue, 06 Aug 2013 09:27:10 -0400, Burak Arslan  
 wrote:



First, let's get over the fact that, with dynamic typing, code fails at
runtime. Irrespective of language, you just shouldn't ship untested
code, so I say that's not an argument against dynamic typing.


It's not so much shipping untested code as not having or unable to test  
all the pathways in the code shipped. I ran into this problem with a  
server I built. I ended up solving the problem by building a testing  
scaffolding that let me control all inputs. It would've been much easier  
with static typing to make sure all the pieces lined up.


The other technique I've used is a properly set up exception handling  
environment. Do it right and you can log all of the errors so that you  
have useful information. Part of "doing it right" includes a system that  
tells you when exceptions happened right away so the server doesn't run  
for days or more failing at random but nobody notices because your  
exceptions keep the system for failing completely.


I guess this is a long way of saying instrument your software so that it  
can be tested and or give you enough information about the internal state.  
This is sort of like building a specialized integrated circuit. You need  
to design it so it can be tested/observed after it's been embedded in  
epoxy and not just count on being able to probe the wafer in the lab.

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


Pylint 1.0 released

2013-08-06 Thread Sylvain Thénault
Hi there,

at last, Pylint 1.0 is out! See http://www.logilab.org/blogentry/163292
for (much) more info and enjoy!

And many thanks to every one who contributed to this release...
-- 
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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module for dialoging with intercative programs, sockets, files, etc.

2013-08-06 Thread William Ray Wing
On Aug 6, 2013, at 4:44 AM, Ulrich Eckhardt  
wrote:

> Am 05.08.2013 21:38, schrieb Olive:
>> I have found telnetlib which make very easy to interact with a telnet
>> server, especially the read_until command. I wonder if something
>> similar exits for other things that a telnet server.
> 
> It's not Python and I haven't played with it extensively, but there is a tool 
> named "expect": https://en.wikipedia.org/wiki/Expect
> 
> Uli
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Ah, but there _is_ a Python equivalent called pexpect with lots of examples and 
documentation via Google.  You can start here:


http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python/

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


Re: Newbie: static typing?

2013-08-06 Thread Rotwang

On 06/08/2013 11:07, Rui Maciel wrote:

Joshua Landau wrote:


Unless you have a very good reason, don't do this [i.e. checking
arguments for type at runtime and raising TypeError]. It's a damn pain
when functions won't accept my custom types with equivalent
functionality -- Python's a duck-typed language and it should behave
like one.


In that case what's the pythonic way to deal with standard cases like this
one?


class SomeModel(object):
 def __init__(self):
 self.label = "this is a label attribute"

 def accept(self, visitor):
 visitor.visit(self)
 print("visited: ", self.label)


class AbstractVisitor(object):
 def visit(self, element):
 pass


class ConcreteVisitorA(AbstractVisitor):
 def visit(self, element):
 element.label = "ConcreteVisitorA operated on this model"

class ConcreteVisitorB(AbstractVisitor):
 def visit(self, element):
 element.label = "ConcreteVisitorB operated on this model"


model = SomeModel()

operatorA = ConcreteVisitorA()

model.accept(operatorA)

operatorB = ConcreteVisitorB()

model.accept(operatorA)

not_a_valid_type = "foo"

model.accept(not_a_valid_type)



The Pythonic way to deal with it is exactly how you deal with it above. 
When the script attempts to call model.accept(not_a_valid_type) an 
exception is raised, and the exception's traceback will tell you exactly 
what the problem was (namely that not_a_valid_type does not have a 
method called "visit"). In what way would runtime type-checking be any 
better than this? There's an obvious way in which it would be worse, 
namely that it would prevent the user from passing a custom object to 
SomeModel.accept() that has a visit() method but is not one of the types 
for which you thought to check.


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


Re: Newbie: static typing?

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 2:58 PM, Eric S. Johansson  wrote:
> I guess this is a long way of saying instrument your software so that it can
> be tested and or give you enough information about the internal state. This
> is sort of like building a specialized integrated circuit. You need to
> design it so it can be tested/observed after it's been embedded in epoxy and
> not just count on being able to probe the wafer in the lab.

In software, that's easy: just have a way to execute arbitrary code in
the context of the running server. A *hugely* beneficial debugging
tool. Of course, it's also a security concern, so you have to put a
good password [1] on it, or have some other system for guaranteeing
that untrusted persons can't execute arbitrary code.

ChrisA

[1] By which I mean http://xkcd.com/936/ compliant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Grant Edwards
On 2013-08-05, Rui Maciel  wrote:

> Is there any pythonic way to perform static typing?

No.

One of the fundamental characteristics of Python is dynamic typing.

Without dynamic typing, it wouldn't _be_ Python.

-- 
Grant Edwards   grant.b.edwardsYow! I wonder if I ought
  at   to tell them about my
  gmail.comPREVIOUS LIFE as a COMPLETE
   STRANGER?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a running tally/ definitely new to this

2013-08-06 Thread gratedmedia
On Monday, August 5, 2013 10:15:30 PM UTC-4, Dave Angel wrote:
> gratedme...@gmail.com wrote:
> 
> 
> 
> >
> 
> > I currently working on a game, where I need to maintain a running tally of 
> > money, as the player makes purchases as they navigate thru game.   I not 
> > exactly sure how to do this in python.  I know it is a fairly basic step, 
> > nonetheless.  Any assistance would be greatly appreciated.  
> 
> 
> 
> (just to save you the pain later:
> 
>http://wiki.python.org/moin/GoogleGroupsPython
> 
> )
> 
> 
> 
> So what have you written so far?  Is this a homework assignment and
> 
> you've been covering certain parts of Python in a certain order? Is it
> 
> part of learning some tutorial?
> 
> 
> 
> There are so many ways of accomplishing this sort of thing, that without
> 
> some constraints, there are a dozen reasonable responses.  I'll try one:
> 
> 
> 
> in the class Player, you make a pair of methods, purchase() and
> 
> income(), which manipulate the instance attribute assets.   Then you
> 
> make a property that returns the assets.
> 
> 
> 
> 
> 
> 
> 
> Class Player:
> 
>  
> 
>  def purchase(self, amount):
> 
> self.assets -= amount
> 
>  def income(self, amount):
> 
> self.assets += amount
> 
>  def wealth(self):
> 
> return self.assets
> 
> 
> 
> 
> 
> -- 
> 
> DaveA

This a project I am am working on.  I am using "Learn Python the Hard Way". To 
best explain. I'm working on a game with a similar format to John Dell's 
Dopewars, but on Python. SO I've created the several destinations to travel, 
but now maintaining the "running tally (money)" has been my issue. I'm going to 
take your advice and play with code you posted.  Please contact me with any 
more suggestions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class hierarchy problem

2013-08-06 Thread BrJohan

On 06/08/2013 16:02, Chris Angelico wrote:


My classhierarchy is like a multilevel tree where each non-leaf node (class)
is given knowledge about its nearest subclasses and their 'capacities'.

So, my idea is to let the 'upper' class recursively choose which of its
nearest subclasses is the 'correct' one, until approaching a 'leaf' class
from which the instance should be created. And, given my knowledge that a
solution along the lines of this idea has been designed and was working, I'm
still hopeful ... (or I'll have to investigate all those old backup-DVDs)


[ responding on-list - I hope it was mere oversight that had this come
privately to me alone ]

This is code smell; this recursive search for the "right" class seems
likely to be wrong. Can you have the classes perhaps register
themselves in some way? On what basis is a superclass to determine
that one of its subclasses should handle this request?

ChrisA




Consider a botanical classification system (somewhat analogous to my 
'problem' as it effectively is related to classification of entities):


A Domain should know about its Kingdoms,
a Kingdom should know about its Phylums,
...
a Genus should know about its Species.

Of course it is possible to implement such a decision tree as a 
'factory'. However, I would rather prefer to encapsulate those decisions 
at the class level where they 'belong'.


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


pexpect, loading an entry field

2013-08-06 Thread inq1ltd
python help;

I am using pexpect to open my program.
Can someone tell me how to get data to appear in 
an entry field.

After pexpect opens the my program I have tried to use 
send, sendline, and write functions to try to put data into 
the program's entry field.

However, the data is going to the terminal window, 
the window that is used to initiate the call to pexpect 
but not to the entry field in the open program.

I would appreciate suggestions.
jol

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


Re: Simulate `bash` behaviour using Python and named pipes.

2013-08-06 Thread Luca Cerone
> my_thread.join()

Thanks! I managed to make it work using the threading library :)

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


Re: Pylint 1.0 released

2013-08-06 Thread Jordi Riera
Great tool

Thanks!


On Tue, Aug 6, 2013 at 4:12 PM, Sylvain Thénault <
sylvain.thena...@logilab.fr> wrote:

> Hi there,
>
> at last, Pylint 1.0 is out! See http://www.logilab.org/blogentry/163292
> for (much) more info and enjoy!
>
> And many thanks to every one who contributed to this release...
> --
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
- Jordi Riera, Connecting people.
+33 662217507
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Class hierarchy problem

2013-08-06 Thread Joe Junior
On Tue, Aug 6, 2013 at 12:36 PM, BrJohan  wrote:
> On 06/08/2013 16:02, Chris Angelico wrote:
>
>>> My classhierarchy is like a multilevel tree where each non-leaf node
>>> (class)
>>> is given knowledge about its nearest subclasses and their 'capacities'.
>>>
>>> So, my idea is to let the 'upper' class recursively choose which of its
>>> nearest subclasses is the 'correct' one, until approaching a 'leaf' class
>>> from which the instance should be created. And, given my knowledge that a
>>> solution along the lines of this idea has been designed and was working,
>>> I'm
>>> still hopeful ... (or I'll have to investigate all those old backup-DVDs)
>>
>>
>> [ responding on-list - I hope it was mere oversight that had this come
>> privately to me alone ]
>>
>> This is code smell; this recursive search for the "right" class seems
>> likely to be wrong. Can you have the classes perhaps register
>> themselves in some way? On what basis is a superclass to determine
>> that one of its subclasses should handle this request?
>>
>> ChrisA
>>
>
>
> Consider a botanical classification system (somewhat analogous to my
> 'problem' as it effectively is related to classification of entities):
>
> A Domain should know about its Kingdoms,
> a Kingdom should know about its Phylums,
> ...
> a Genus should know about its Species.
>
> Of course it is possible to implement such a decision tree as a 'factory'.
> However, I would rather prefer to encapsulate those decisions at the class
> level where they 'belong'.
>
> BrJohan
> --

I think it's a "has a" vs a "is a" problem. A Domain has a Kingdom, a Kingdom is
not a Domain, so it shouldn't actually inherit Domain. In this case
you should use
composition instead of inheritance.

When you say that a A Domain should know about it's Kingdons note that you're
talking about a specific Domain and it's specific Kingdons, which
means, a Domain
instance and various Kingdom instances.

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


Re: Class hierarchy problem

2013-08-06 Thread Jordi Riera
Are you using a db for that?

Django models would handle that pretty easily:

class Species(models.Model):
 name = models.CharField()

class Genus(models.Model):
name = models.CharField()
species = models.ManyToManyField(
 Species, related_name = 'genus_species'
)

then you can access species from genus by:
Genus.objects.all()[0].species.all()

and genus from species by:
Species.objects.all()[0].genus_species.all()

if you can afford this depends that would solve your issue I think.
more details:
http://stackoverflow.com/questions/9352662/how-to-use-the-reverse-of-a-django-manytomany-relationship

Regards
Jordi


On Tue, Aug 6, 2013 at 5:36 PM, BrJohan  wrote:

> On 06/08/2013 16:02, Chris Angelico wrote:
>
>  My classhierarchy is like a multilevel tree where each non-leaf node
>>> (class)
>>> is given knowledge about its nearest subclasses and their 'capacities'.
>>>
>>> So, my idea is to let the 'upper' class recursively choose which of its
>>> nearest subclasses is the 'correct' one, until approaching a 'leaf' class
>>> from which the instance should be created. And, given my knowledge that a
>>> solution along the lines of this idea has been designed and was working,
>>> I'm
>>> still hopeful ... (or I'll have to investigate all those old backup-DVDs)
>>>
>>
>> [ responding on-list - I hope it was mere oversight that had this come
>> privately to me alone ]
>>
>> This is code smell; this recursive search for the "right" class seems
>> likely to be wrong. Can you have the classes perhaps register
>> themselves in some way? On what basis is a superclass to determine
>> that one of its subclasses should handle this request?
>>
>> ChrisA
>>
>>
>
> Consider a botanical classification system (somewhat analogous to my
> 'problem' as it effectively is related to classification of entities):
>
> A Domain should know about its Kingdoms,
> a Kingdom should know about its Phylums,
> ...
> a Genus should know about its Species.
>
> Of course it is possible to implement such a decision tree as a 'factory'.
> However, I would rather prefer to encapsulate those decisions at the class
> level where they 'belong'.
>
> BrJohan
> --
> http://mail.python.org/**mailman/listinfo/python-list
>



-- 
- Jordi Riera, Connecting people.
+33 662217507
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect, loading an entry field

2013-08-06 Thread Lakshmipathi.G
pexpect looks simple to use. Please check this example
http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python/

-- 

Cheers,
Lakshmipathi.G
FOSS Programmer.
www.giis.co.in

On Tue, Aug 6, 2013 at 8:35 PM, inq1ltd  wrote:
> python help;
>
>
>
> I am using pexpect to open my program.
>
> Can someone tell me how to get data to appear in
>
> an entry field.
>
>
>
> After pexpect opens the my program I have tried to use
>
> send, sendline, and write functions to try to put data into
>
> the program's entry field.
>
>
>
> However, the data is going to the terminal window,
>
> the window that is used to initiate the call to pexpect
>
> but not to the entry field in the open program.
>
>
>
> I would appreciate suggestions.
>
> jol
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-list Digest, Vol 119, Issue 37

2013-08-06 Thread Yimr Wong
>I found Python3's sqlite3 library. I found that I needed sql commands for
using it.
>
>I have tried sql.learncodethehardway but it isn't complete yet. I tired
looking on stackoverflow's  sql tag also but nothing much there.

There is some useful references in the Python's documents. If you want to
connect to the mysql, you should import the packages related.


On Tue, Aug 6, 2013 at 10:11 PM,  wrote:

> Send Python-list mailing list submissions to
> python-list@python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
> http://mail.python.org/mailman/listinfo/python-list
> or, via email, send a message with subject or body 'help' to
> python-list-requ...@python.org
>
> You can reach the person managing the list at
> python-list-ow...@python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Python-list digest..."
>
> Today's Topics:
>
>1. Re: Can someone suggest better resources for learning
>   sqlite3? Iwanted to use the Python library but I don't know
> sql.
>   (Jordi Riera)
>2. Re: Sort lines in a plain text file alphanumerically
>   (Devyn Collier Johnson)
>3. Re: Sort lines in a plain text file alphanumerically
>   (Chris Angelico)
>4. Re: Newbie: static typing? (Burak Arslan)
>5. Re: Working with XML/XSD (Burak Arslan)
>6. Re: Newbie: static typing? (Antoon Pardon)
>7. Re: Class hierarchy problem (Chris Angelico)
>8. Re: Newbie: static typing? (Chris Angelico)
>9. Re: Newbie: static typing? (Eric S. Johansson)
>
>
> -- Forwarded message --
> From: Jordi Riera 
> To: Gilles 
> Cc: python-list@python.org
> Date: Tue, 6 Aug 2013 13:05:02 +0200
> Subject: Re: Can someone suggest better resources for learning sqlite3? I
> wanted to use the Python library but I don't know sql.
> Hey,
>
> can't you use django to deal with your sqlite?
> If so, django 
> modelsare a smart 
> way to do.
>
> Regards,
> Jordi
>
>
> On Tue, Aug 6, 2013 at 12:51 PM, Gilles  wrote:
>
>> On Sat, 3 Aug 2013 10:57:32 -0700 (PDT), Aseem Bansal
>>  wrote:
>> >I found Python3's sqlite3 library. I found that I needed sql commands
>> for using it.
>> >
>> >I have tried sql.learncodethehardway but it isn't complete yet. I tired
>> looking on stackoverflow's  sql tag also but nothing much there.
>>
>> It'll be easier to read tutorials specifically meant to use Sqlite
>> with Python:
>>
>> www.google.com/search?q=python+sqlite+examples
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
>
> --
> - Jordi Riera, Connecting people.
> +33 662217507
>
>
> -- Forwarded message --
> From: Devyn Collier Johnson 
> To: Python Mailing List 
> Cc:
> Date: Tue, 06 Aug 2013 08:29:46 -0400
> Subject: Re: Sort lines in a plain text file alphanumerically
>
> On 08/06/2013 06:52 AM, Chris Angelico wrote:
>
>> On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
>>  wrote:
>>
>>>  with open('/home/collier/pytest/**sort.TXT') as file:
>>>  sorted(file, key=str.casefold, reverse=True)
>>>
>>>
>>> Thanks for the advice Joshua. I find these tips very useful. However, how
>>> would I close the files, or would they close after the "with" construct
>>> is
>>> complete?
>>>
>>
>> That's the whole point of 'with'. It calls open(), then calls
>> __enter__, and it guarantees to call __exit__ before executing any
>> code following the with block. With a file object, __exit__ will close
>> the file.
>>
>> ChrisA
>>
>
> Thanks! Now I see why using "with" is a better way to write the code.
>
> DCJ
>
>
>
> -- Forwarded message --
> From: Chris Angelico 
> To: python-list@python.org
> Cc:
> Date: Tue, 6 Aug 2013 14:15:06 +0100
> Subject: Re: Sort lines in a plain text file alphanumerically
> On Tue, Aug 6, 2013 at 12:44 PM, Joshua Landau  wrote:
> > On 6 August 2013 11:52, Chris Angelico  wrote:
> >> On Tue, Aug 6, 2013 at 11:38 AM, Devyn Collier Johnson
> >>  wrote:
> >>> with open('/home/collier/pytest/sort.TXT') as file:
> >>> sorted(file, key=str.casefold, reverse=True)
> >>>
> >>>
> >>> Thanks for the advice Joshua. I find these tips very useful. However,
> how
> >>> would I close the files, or would they close after the "with"
> construct is
> >>> complete?
> >>
> >>
> >> That's the whole point of 'with'. It calls open(),
> >
> > To be pedantic, it does not. open is called by the time the with gets
> involved.
> >
>
> The entire statement does. Yes, it's not 'with' that does that, but it
> is called. Anyway, that's detaily stuff :)
>
> ChrisA
>
>
>
> -- Forwarded message --
> From: Burak Arslan 
> To: python-list@python.org
> Cc:
> Date: Tue, 06 Aug 2013 16:27:10 +0300
> Subject: Re: Newbie: static typing?
> On 08/06/13 13:12, Rui Maciel wrote:
> > Joshua Landau wrote:
> >
> >> What's the actual problem you're facing? Where do you feel that you
> >> need

Re: Class hierarchy problem

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 4:36 PM, BrJohan  wrote:
> Consider a botanical classification system (somewhat analogous to my
> 'problem' as it effectively is related to classification of entities):
>
> A Domain should know about its Kingdoms,
> a Kingdom should know about its Phylums,
> ...
> a Genus should know about its Species.

I don't believe it's that clear. In some situations it may be best to
work that way; in others, each tier should know only those above it.
Does the generic Widget know about being a PushButton, a ListBox, and
a Slider? No, but the Slider knows what a Widget is.

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


Using Pool map with a method of a class and a list

2013-08-06 Thread Luca Cerone
Hi guys,
I would like to apply the Pool.map method to a member of a class.

Here is a small example that shows what I would like to do:

from multiprocessing import Pool

class A(object):
   def __init__(self,x):
   self.value = x
   def fun(self,x):
   return self.value**x


l = range(10)

p = Pool(4)

op = p.map(A.fun,l)

#using this with the normal map doesn't cause any problem

This fails because it says that the methods can't be pickled.
(I assume it has something to do with the note in the documentation: 
"functionality within this package requires that the __main__ module be 
importable by the children.", which is obscure to me).

I would like to understand two things: why my code fails and when I can expect 
it to fail? what is a possible workaround?

Thanks a lot in advance to everybody for the help!

Cheers,
Luca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Pool map with a method of a class and a list

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 6:12 PM, Luca Cerone  wrote:
> from multiprocessing import Pool
>
> class A(object):
>def __init__(self,x):
>self.value = x
>def fun(self,x):
>return self.value**x
>
>
> l = range(10)
>
> p = Pool(4)
>
> op = p.map(A.fun,l)

Do you ever instantiate any A() objects? You're attempting to call an
unbound method without passing it a 'self'.

You may find the results completely different in Python 2 vs Python 3,
and between bound and unbound methods. In Python 3, an unbound method
is simply a function. In both versions, a bound method carries its
first argument around, so it has to be something different. Play
around with it a bit.

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


Re: pexpect, loading an entry field

2013-08-06 Thread inq1ltd

> pexpect looks simple to use. Please check this example
> http://www.pythonforbeginners.com/systems-programming/how-to-use-the-
pexpect
> -module-in-python/
> > python help;
> > 
> > I am using pexpect to open my program.
> > Can someone tell me how to get data to appear in
> > an entry field.
> > After pexpect opens the my program I have tried to use
> > send, sendline, and write functions to try to put data into
> > the program's entry field.
> > However, the data is going to the terminal window, 
> > the window that is used to initiate the call to pexpect
> > but not to the entry field in the open program. 
> > I would appreciate suggestions.
> > 
> > jol
> > 

Thanks for the response.

I have been there but that site gives me 
the same information that I get from 
noah.org.  I have the pexpect docs and they presume 
that this problem doesn't exist.

None of the information in the NOAH site or the FAQ's 
address this question. 

I'm using suse linux running python 2.7 and pexpect.

The data, when using send() method is going to the terminal window, 
This is the same window that is used to initiate the call to pexpect.

Pexpect opens the program but the send method sends
 data to the terminal window, not the entry field located
in the child spawned by pexpect.

interact works, as does close(), TIMEOUT, EOF, before, after, 
expect_exact and methods.  But the entry field does not 
load.

So my question is;

Why??




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


Re: Using Pool map with a method of a class and a list

2013-08-06 Thread Luca Cerone
On Tuesday, 6 August 2013 18:12:26 UTC+1, Luca Cerone  wrote:
> Hi guys,
> 
> I would like to apply the Pool.map method to a member of a class.
> 
> 
> 
> Here is a small example that shows what I would like to do:
> 
> 
> 
> from multiprocessing import Pool
> 
> 
> 
> class A(object):
> 
>def __init__(self,x):
> 
>self.value = x
> 
>def fun(self,x):
> 
>return self.value**x
> 
> 
> 
> 
> 
> l = range(10)
> 
> 
> 
> p = Pool(4)
> 
> 
> 
> op = p.map(A.fun,l)
> 
> 
> 
> #using this with the normal map doesn't cause any problem
> 
> 
> 
> This fails because it says that the methods can't be pickled.
> 
> (I assume it has something to do with the note in the documentation: 
> "functionality within this package requires that the __main__ module be 
> importable by the children.", which is obscure to me).
> 
> 
> 
> I would like to understand two things: why my code fails and when I can 
> expect it to fail? what is a possible workaround?
> 
> 
> 
> Thanks a lot in advance to everybody for the help!
> 
> 
> 
> Cheers,
> 
> Luca



On Tuesday, 6 August 2013 18:12:26 UTC+1, Luca Cerone  wrote:
> Hi guys,
> 
> I would like to apply the Pool.map method to a member of a class.
> 
> 
> 
> Here is a small example that shows what I would like to do:
> 
> 
> 
> from multiprocessing import Pool
> 
> 
> 
> class A(object):
> 
>def __init__(self,x):
> 
>self.value = x
> 
>def fun(self,x):
> 
>return self.value**x
> 
> 
> 
> 
> 
> l = range(10)
> 
> 
> 
> p = Pool(4)
> 
> 
> 
> op = p.map(A.fun,l)
> 
> 
> 
> #using this with the normal map doesn't cause any problem
> 
> 
> 
> This fails because it says that the methods can't be pickled.
> 
> (I assume it has something to do with the note in the documentation: 
> "functionality within this package requires that the __main__ module be 
> importable by the children.", which is obscure to me).
> 
> 
> 
> I would like to understand two things: why my code fails and when I can 
> expect it to fail? what is a possible workaround?
> 
> 
> 
> Thanks a lot in advance to everybody for the help!
> 
> 
> 
> Cheers,
> 
> Luca
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Pool map with a method of a class and a list

2013-08-06 Thread Luca Cerone
Hi Chris, thanks

> Do you ever instantiate any A() objects? You're attempting to call an
> 
> unbound method without passing it a 'self'.

I have tried a lot of variations, instantiating the object, creating lambda 
functions that use the unbound version of fun (A.fun.__func__) etc etc..
I have played around it quite a bit before posting.

As far as I have understood the problem is due to the fact that Pool pickle the 
function and copy it in the various pools.. 
But since the methods cannot be pickled this fails..

The same example I posted won't run in Python 3.2 neither (I am mostly 
interested in a solution for Python 2.7, sorry I forgot to mention that).

Thanks in any case for the help, hopefully there will be some other advice in 
the ML :)

Cheers,
Luca
-- 
http://mail.python.org/mailman/listinfo/python-list


lxml tostring quoting too much

2013-08-06 Thread andrea crotti
I would really like to do the following:

from lxml import etree as ET
from lxml.builder import E

url = "http://something?x=10&y=20";
l = E.link(url)
ET.tostring(l) -> "http://something?x=10&y=20"

However the lxml tostring always quotes the &, I can't find a way to
tell it to avoid quoting it.
Is it possible?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lxml tostring quoting too much

2013-08-06 Thread Chris Down
On 2013-08-06 18:38, andrea crotti wrote:
> I would really like to do the following:
>
> from lxml import etree as ET
> from lxml.builder import E
>
> url = "http://something?x=10&y=20";
> l = E.link(url)
> ET.tostring(l) -> "http://something?x=10&y=20"
>
> However the lxml tostring always quotes the &, I can't find a way to
> tell it to avoid quoting it.

You're probably aware, but without the escaping, it is no longer well formed
XML. Why do you want to do that? Is there a larger underlying problem that
should be solved instead?

Either way, you can use "unescape" from the xml.sax.saxutils module[0].

Chris

0: http://docs.python.org/2/library/xml.sax.utils.html


pgp5LbtvsyYqj.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Beginner question

2013-08-06 Thread eschneider92
Why won't the 'goodbye' part of this code work right? it prints 'ok' no matter 
what is typed. Much thanks.

def thing():
print('go again?')
goagain=input()
if goagain=='y' or 'yes':
print('ok')
elif goagain!='y' or 'yes':
print('goodbye')
sys.exit()
thing()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-08-06 Thread Dave Angel
eschneide...@comcast.net wrote:

> Why won't the 'goodbye' part of this code work right? it prints 'ok' no 
> matter what is typed. Much thanks.
>
> def thing():
> print('go again?')
> goagain=input()
> if goagain=='y' or 'yes':

This expression doesn't do what you think.  The comparison binds more
tightly, so it first evaluates (goagain=="y").  The results of that are
either True or False.  Then it or's that logical value with 'yes'.  The
result is either True or it's  'yes'.  'yes' is considered truthy, so
the if will always succeed.

What you meant to use was:
   if goagain == "y" or goagain == "yes":

Alternatively, you could use
   if goagain in ("y", "yes"):

> print('ok')
> elif goagain!='y' or 'yes':

Same here.

> print('goodbye')
> sys.exit()
> thing()

-- 
DaveA


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


Re: Beginner question

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 10:35 PM,   wrote:
> Why won't the 'goodbye' part of this code work right? it prints 'ok' no 
> matter what is typed. Much thanks.
>
> def thing():
> print('go again?')
> goagain=input()
> if goagain=='y' or 'yes':
> print('ok')
> elif goagain!='y' or 'yes':
> print('goodbye')
> sys.exit()
> thing()

When you use 'or' in this way, it's not doing what you think it does.
It actually first computes

>>> goagain=='y'

which is either True or False, and then evaluates the next part:

>>> True or 'yes'
>>> False or 'yes'

Try out those two in interactive Python and see what they do. You
probably want to compare in both halves of the test, or possibly use
the 'in' operator:

if goagain in ('y', 'yes'):

Also, you don't need an 'elif' there; just use a plain else. Repeating
the condition just introduces the chance of bugs - for instance, would
you notice the error in this?

if goagain=='y' or goagain=='yes':
print('ok')
elif goagain!='y' or goagain!='yes':
print('goodbye')

Using a plain 'else' guarantees that exactly one of the branches will
be executed, rather than having the possibility that neither will,
which isn't the intention here.

Hope that helps!

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


Re: [GUI] Good frameworks for Windows/Mac?

2013-08-06 Thread Gilles
On Tue, 6 Aug 2013 13:22:01 +0200, Vlastimil Brom
 wrote:
>I mostly use wxPython myself, but if you just need some basic widgets
>and not some very complex or non-standard layouts, the tkinter -
>available in the standard library - might be perfectly viable.
>http://docs.python.org/3.3/library/tk.html
>The more recent versions of python also support ttk and Tix which has
>further possibilities, styling etc.
>There is further e.g. Python GUI
>http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
>
>and several others
>http://wiki.python.org/moin/GuiProgramming

Thanks for the links. I'll play with Tkinter, and if it's not good
enough, check the alternatives.
-- 
http://mail.python.org/mailman/listinfo/python-list


[ActivePython] Upgrading fails

2013-08-06 Thread Gilles
Hello,

I already posted in their forum, but got no reply and figured some
people here might have experienced this too.

I'm currently running ActivePython 2.5.1.1 on my XP Pro host.

After downloading and running the installer to 2.7.2.5, I get the
following error message:

"Windows Installer: The Windows Installer Service could not be
accessed. This can occur if the Windows Installer is not correctly
installed."

Has someone seen this, and knows what to do?

Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-08-06 Thread Rhodri James

On Tue, 06 Aug 2013 22:35:44 +0100,  wrote:

Why won't the 'goodbye' part of this code work right? it prints 'ok' no  
matter what is typed. Much thanks.


def thing():
print('go again?')
goagain=input()
if goagain=='y' or 'yes':


This line doesn't do what you think it does :-)  Typing that condition at  
an interactive prompt reveals something interesting:



goagain = "n"
goagain=="y"

False

goagain=="y" or "yes"

'yes'

Oho.  What's actually happening is that you've mistaken the operator  
precedence.  "==" has a higher precedence than "or", so your condition is  
equivalent to '(goagain=="y") or "yes"'.  Since it's left-hand argument is  
False, "or" returns its right-hand argument, which has the value 'yes',  
which in a boolean context is "True".


What you seem to want to do is to have your condition be true if goagain  
is either "y" or "yes".  Probably the easiest way of doing this and  
learning something new at the same time is to ask if goagain appears in a  
list (or rather a tuple) of strings:


if goagain in ('y', 'yes'):
  print('ok')
elif goagain not in ('y', 'yes'):
  print('goodbye')
  sys.exit()

or better,

if goagain in ('y', 'yes', 'ohdeargodyes', 'you get the idea'):
  print('ok')
else:
  print('goodbye')
  sys.exit()


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Easier to Ask Forgiveness than Permission (was: Newbie: static typing?)

2013-08-06 Thread Ben Finney
Rui Maciel  writes:

> Gary Herron wrote:
>
> > The Pythonic way is to *enjoy* the freedom and flexibility and power
> > of dynamic typing. If you are stepping out of a static typing
> > language into Python, don't step just half way. Embrace dynamic
> > typing. (Like any freedom, it can bite you at times, but that's no
> > reason to hobble Python with static typing.)
>
> What's the Python way of dealing with objects being passed to a
> function that aren't of a certain type, have specific attributes of a
> specific type, nor support a specific interface?

Python has strong typing. That means every Python object (and in Python,
every value is an object) knows what its type is and therefore what
behaviours it supports.

Types (that is, classes; the two terms refer to the same thing in
Python) are the correct place to put checks on whether the type's
instances are being used properly.

Don't check types of objects in every place where you use those objects.
(This is a sub-set of Look Before You Leap programming, which is
discouraged because it makes your code far too heavy on checking for
problems rather than the purpose of the code.)

Check for type appropriate usage in the type itself.

So the Pythonic way to deal with objects that don't support particular
behaviour is: Use the object on the assumption that it supports the
behaviour you want – that is, assume the caller of your function is
giving you an object that your function can use. If the object doesn't
support that behaviour, an error will be raised from the type.

Sometimes your function will know exactly what to do with an error, and
can give more specific information about the problem. In those cases,
you should catch the exception and ‘raise MoreSpecificError("foo") from
exc’. But only in those cases where your function *actually does* know
more about the problem.

In the majority of cases, don't check the type at all, and allow the
type-specific error to raise back to the caller, who then has to deal
with the fact they've passed your function an object that doesn't
support the necessary behaviour.

This principle – of assuming the behaviour is supported, and having a
robust infrastructure for dealing with errors – is known as Easier to
Ask Forgiveness than Permission.

In Python, we discourage LBYL and encourage EAFP. Our code tends to have
a lot less boiler-plate and obfuscatory error-checking as a result, and
tends to be more expressive than statically-typed languages.

-- 
 \   “If you make people think they're thinking, they'll love you; |
  `\ but if you really make them think, they'll hate you.” —Donald |
_o__) Robert Perry Marquis |
Ben Finney

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


[tkinter] trouble running imported modules in main program

2013-08-06 Thread snakeinmyboot
Hello,

I am currently just starting to learn the basics of the tkinter module and ive 
run into a problem. To teach myself I am messing around by creating separate 
modules containing basic GUI apps like a tip calculator and kilometer 
converter, then creating a main program that displays buttons you can click 
that will create instances of the modules (tip calculator, kilometer 
converter). So far ive managed to successfully make the basic GUI apps works 
just fine, and have been able to import them into my main program and get them 
to launch in a new window when i click the buttons and everything, but heres my 
problem.

Everything displays ok, like the labels, entry boxes, and buttons, but when I 
actually click the buttons (which are supposed to trigger a method within the 
module and display a label containing the calculated data).. nothing happens. 
When I run the modules by themselves everything works just fine (testing by 
making the module create an instance of itself but i # them out before running 
the main program).

I have posted all my code to this forum if you need to look at it

http://python-forum.org/viewtopic.php?f=12&t=5620

Any idea what im doing wrong here?

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


Re: Newbie: static typing?

2013-08-06 Thread Ben Finney
Rui Maciel  writes:

> class AbstractVisitor(object):
> def visit(self, element):
> pass

A small improvement to your code:

If you want an abstract method – that is, a method which should not be
called directly but which sub-classes should over-ride – then your
abstract method should not ‘pass’. Instead, it should ‘raise
NotImplementedError’ so this will be clear to anyone if the MRO falls
back to the abstract method.

> not_a_valid_type = "foo"
>
> model.accept(not_a_valid_type)

At this point, the ‘not_a_valid_type’ object is asked for its ‘visit’
method, and a TypeError is raised. That's good, because it informs the
person looking at the code that this object doesn't support the needed
behaviour.

This is as it's meant to be; what problem are you pointing out here?

-- 
 \  “Software patents provide one more means of controlling access |
  `\  to information. They are the tool of choice for the internet |
_o__) highwayman.” —Anthony Taylor |
Ben Finney

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


HTTP post with urllib2

2013-08-06 Thread cerr
Hi,

Why does this code:

#!/usr/bin/python


import urllib2
from binascii import hexlify, unhexlify

host = "localhost"
uri="/test.php"
data ="\x48\x65\x6C\x6C\x6F\x57\x6F\x72\x6C\x64" #Hello World
url="http://{0}{1}?f=test".format(host, uri)
req = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
req.get_method = lambda: 'PUT'
response = urllib2.urlopen(req, 120)
retval = response.read()
print "RETVAL "+retval



return me this:

./post.py
Traceback (most recent call last):
  File "./post.py", line 13, in 
response = urllib2.urlopen(req, 120)
  File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 398, in open
req = meth(req)
  File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
'Content-length', '%d' % len(data))


I don't get it, what's going on here?

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


Enum vs OrderedEnum

2013-08-06 Thread Ian Kelly
Using the OrderedEnum recipe from the Python 3.4 docs, I have the
following code:


class Environment(OrderedEnum):

gaia = 1
fertile = 2
terran, jungle, ocean, arid, steppe, desert, minimal = range(3, 10)
barren, tundra, dead, inferno, toxic, radiated = range(10, 16)

def is_standard(self):
return Environment.terran <= self <= Environment.minimal

def is_hostile(self):
return Environment.barren <= self

@property
def growth_factor(self):
if self.is_standard():
return 1.0
elif self.is_hostile():
return 0.5
elif self is Environment.fertile:
return 1.5
elif self is Environment.gaia:
return 2.0
else:
raise AttributeError("Unknown growth_factor for %s" % self)


This works, and the ordering is logical and intuitive, and I think
result is quite readable.  That said, really the only reason for
subclassing OrderedEnum instead of Enum is to support the is_standard
and is_hostile methods.  In normal usage there is no reason for the
members to be ordered.  Can anyone suggest an alternative formulation
that is as readable as the above without relying on OrderedEnum?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: static typing?

2013-08-06 Thread Terry Reedy

On 8/6/2013 6:50 AM, Chris Angelico wrote:

On Tue, Aug 6, 2013 at 11:28 AM, Rui Maciel  wrote:

Chris Angelico wrote:

def add_three_values(x,y,z):
 return x+y+z

Do you want to test these values for compatibility? Remember, you
could take a mixture of types, as most of the numeric types can safely
be added. You can also add strings, or lists, but you can't mix them.
And look! It already raises TypeError if it's given something
unsuitable:


If the type problems aren't caught right away when the invalid types are
passed to a function then the problem may only manifest itself in some far
away point in the code, making this bug needlessly harder to spot and fix,
and making the whole ordeal needlessly too time consuming.


There are two problems that can result from not checking:

1) The traceback will be deeper and may be less clear.

2) Some code will be executed and then an exception thrown.


3) The code falls into an infinite loop or recursion.

The solution is to think before looping or recursing.  This often 
involves value checking (non-negative int or non-fractional float, for 
instance) rather than type checking in the usual static type-checking sense.


One also needs to be careful about passing unbounded iterators to other 
functions and remember that unboundedness is contagious. (filter(pred, 
unbounded_iterator) is an unbounded iterator). Again, this is a 'value' 
or implicit sub-type issue rather than a explicit, visible 'type' issue.


Infinite recursion will be caught eventually when memory runs out (and 
that is an advantage of recursion over iteration ;-), but I prefer to 
avoid it anyway.


--
Terry Jan Reedy

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


Re: HTTP post with urllib2

2013-08-06 Thread Joel Goldstick
On Tue, Aug 6, 2013 at 6:52 PM, cerr  wrote:
> Hi,
>
> Why does this code:
>
> #!/usr/bin/python
>
>
> import urllib2
> from binascii import hexlify, unhexlify
>
> host = "localhost"
> uri="/test.php"
> data ="\x48\x65\x6C\x6C\x6F\x57\x6F\x72\x6C\x64" #Hello World
> url="http://{0}{1}?f=test".format(host, uri)
> req = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
> req.get_method = lambda: 'PUT'

What does the above line do? is it the same as req.get_method = 'PUT'
> response = urllib2.urlopen(req, 120)

the docs say req should be a url.  Is it?
> retval = response.read()
> print "RETVAL "+retval
>
>
>
> return me this:
>
> ./post.py
> Traceback (most recent call last):
>   File "./post.py", line 13, in 
> response = urllib2.urlopen(req, 120)
>   File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
> return _opener.open(url, data, timeout)
>   File "/usr/lib/python2.7/urllib2.py", line 398, in open
> req = meth(req)
>   File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
> 'Content-length', '%d' % len(data))
>
>
> I don't get it, what's going on here?
>
> Thank you!
> --
> http://mail.python.org/mailman/listinfo/python-list

KInda of ducking your questions, but the requests module is a lot
easier to use and
understand:http://docs.python-requests.org/en/latest/



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


Re: Enum vs OrderedEnum

2013-08-06 Thread Ethan Furman

On 08/06/2013 04:00 PM, Ian Kelly wrote:

Use the .value attribute instead.  You could also substitute self for 
Environment.



class Environment(Enum):

 gaia = 1
 fertile = 2
 terran, jungle, ocean, arid, steppe, desert, minimal = range(3, 10)
 barren, tundra, dead, inferno, toxic, radiated = range(10, 16)

 def is_standard(self):
 return self.terran.value <= self.value <= self.minimal.value

 def is_hostile(self):
 return self.barren.value <= self.value

 @property
 def growth_factor(self):
 if self.is_standard():
 return 1.0
 elif self.is_hostile():
 return 0.5
 elif self is self.fertile:
 return 1.5
 elif self is self.gaia:
 return 2.0
 else:
 raise AttributeError("Unknown growth_factor for %s" % self)


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


Re: Class hierarchy problem

2013-08-06 Thread Terry Reedy

On 8/6/2013 11:36 AM, BrJohan wrote:


Consider a botanical classification system (somewhat analogous to my
'problem' as it effectively is related to classification of entities):

A Domain should know about its Kingdoms,
a Kingdom should know about its Phylums,
...
a Genus should know about its Species.


As some already said, 'a domain' is an instance of Domain (or possibly 
generic Taxon). We have on Earth one instance of 'Life'.


Of course it is possible to implement such a decision tree as a
'factory'. However, I would rather prefer to encapsulate those decisions
at the class level where they 'belong'.


Each instance could have a .classify function that assigns instances to 
sub-instance. The master classifier function would only know how to use 
the .classify functions and have no specific content knowledge in itself.


--
Terry Jan Reedy

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


Re: [argparse] mutually exclusive group with 2 sets of options

2013-08-06 Thread Francois Lafont
Hi,

On relfection, it's clear that:

1. the "(-a -b VALUE-B | -c -d VALUE-D)" syntax is not
implemented by the argparse module;

2. and get this syntax with "argparse + hacking" is not very clean.

So, finally I'll use the docopt module version 0.6.1.
For the inheritance of common options, I'll used something like
that (even if I prefer the oriented object side of the argparse
module):



[the main file]
#---
import importlib
import sys
from docopt import docopt

help_message ="""
Usage:
  my-script (-h | --help)
  my-script  [...]

Options:
  -h, --help
Show this help message and exit.

Available commands:
  command1  Description1...
  command2  Description2...

See 'my-script  -h' for more information on a specific command.
"""

if __name__ == '__main__':

args = docopt(help_message, options_first=True)
command = args['']

try:
m = importlib.import_module('mymodule.' + command)
except ImportError:
print("Sorry, the %s command doesn't exist. See 'my-script -h'.") % 
(command,)
sys.exit(1)

args = docopt(m.help_message, options_first=False)
m.run(args)
#---



[a file for each specific command, mymodule/command1.py etc.]
#---
import mymodule.common as common

help_message = """
Usage:
  my-script subcommand1 (-h | --help)
  my-script subcommand1 %s -w  -c 

Options:
%s
  -w , --warning=
Some help.
  -c , --critical=
Some help.
""" % (common.common_syntax, common.common_help,)


def run(args):
pass
#---



[and a file for the common syntax, mymodule/common.py]
#---
common_syntax = """-H  -t 
  (--v2c -C  | -l  -x  -X  -L 
)"""

common_help = """  -h, --help
Show this help message and exit.
  -H , --host=
Some help.
  -t , --timeout=
Some help.
  --v2c
Some help.
  -C , --community=
Set the community password for SNMP V2c.
   # etc.
   # etc.
"""
#---

Thank you all.

-- 
François Lafont
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [tkinter] trouble running imported modules in main program

2013-08-06 Thread Terry Reedy

On 8/6/2013 6:28 PM, snakeinmyboot wrote:

Hello,

I am currently just starting to learn the basics of the tkinter module and ive 
run into a problem. To teach myself I am messing around by creating separate 
modules containing basic GUI apps like a tip calculator and kilometer 
converter, then creating a main program that displays buttons you can click 
that will create instances of the modules (tip calculator, kilometer 
converter). So far ive managed to successfully make the basic GUI apps works 
just fine, and have been able to import them into my main program and get them 
to launch in a new window when i click the buttons and everything, but heres my 
problem.

Everything displays ok, like the labels, entry boxes, and buttons, but when I 
actually click the buttons (which are supposed to trigger a method within the 
module and display a label containing the calculated data).. nothing happens. 
When I run the modules by themselves everything works just fine (testing by 
making the module create an instance of itself but i # them out before running 
the main program)


Make the boilerplate test code conditional, something like

if __name__ == '__main__':
root = tkinter.Tk()
app = MainClass(root)  # 'MainClass' depends on the module.
root.mainloop
root.destroy

and you do not need to comment it out as it will be ignored when the 
module is imported.



I have posted all my code to this forum if you need to look at it

http://python-forum.org/viewtopic.php?f=12&t=5620


Code comments: double and triple spacing code make it painful to read, 
especiallly in a 10 line box.


self.miles_button = tkinter.Button(self.frame3, \
   text = 'Miles', \
   command = self.conv_miles)

Leave off the unneeded \s.


Any idea what im doing wrong here?


You got the answer there -- only one mainloop. Revising the code as 
suggested above will do that.


Note: I am a tkinter beginner too, so I would also have to experiment 
with details to get importable custom widgets, built from tk widgets, right.



--
Terry Jan Reedy

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


Re: HTTP post with urllib2

2013-08-06 Thread cerr
On Tuesday, August 6, 2013 4:08:34 PM UTC-7, Joel Goldstick wrote:
> On Tue, Aug 6, 2013 at 6:52 PM, cerr  wrote:
> 
> > Hi,
> 
> >
> 
> > Why does this code:
> 
> >
> 
> > #!/usr/bin/python
> 
> >
> 
> >
> 
> > import urllib2
> 
> > from binascii import hexlify, unhexlify
> 
> >
> 
> > host = "localhost"
> 
> > uri="/test.php"
> 
> > data ="\x48\x65\x6C\x6C\x6F\x57\x6F\x72\x6C\x64" #Hello World
> 
> > url="http://{0}{1}?f=test".format(host, uri)
> 
> > req = urllib2.Request(url, data,{'Content-Type': 
> > 'application/octet-stream'})
> 
> > req.get_method = lambda: 'PUT'
> 
> 
> 
> What does the above line do? is it the same as req.get_method = 'PUT'

I guess so, I got this from an example copy & paste :x

> 
> > response = urllib2.urlopen(req, 120)
> 
> 
> 
> the docs say req should be a url.  Is it?

no, it's an instance of req = urllib2.Request()
> 
> > retval = response.read()
> 
> > print "RETVAL "+retval
> 
> >
> 
> >
> 
> >
> 
> > return me this:
> 
> >
> 
> > ./post.py
> 
> > Traceback (most recent call last):
> 
> >   File "./post.py", line 13, in 
> 
> > response = urllib2.urlopen(req, 120)
> 
> >   File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
> 
> > return _opener.open(url, data, timeout)
> 
> >   File "/usr/lib/python2.7/urllib2.py", line 398, in open
> 
> > req = meth(req)
> 
> >   File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
> 
> > 'Content-length', '%d' % len(data))
> 
> >
> 
> >
> 
> > I don't get it, what's going on here?
> 
> >
> 
> > Thank you!
> 
> > --
> 
> > http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> KInda of ducking your questions, but the requests module is a lot
> 
> easier to use and
> 
> understand:http://docs.python-requests.org/en/latest/

But there must be a way to get this working with urllib alone...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [argparse] mutually exclusive group with 2 sets of options

2013-08-06 Thread Francois Lafont
Le 07/08/2013 01:18, Francois Lafont a écrit :

> For the inheritance of common options, I'll used something like
> that (even if I prefer the oriented object side of the argparse
> module):

But I admit that this is a very simple and intelligent module. ;-)

-- 
François Lafont
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner question

2013-08-06 Thread Chris Down
On 2013-08-06 14:35, eschneide...@comcast.net wrote:
> Why won't the 'goodbye' part of this code work right? it prints 'ok' no
> matter what is typed. Much thanks.

"if" statements do not fall through, because the first statement was matched,
no other ones in the same chain will be evaluted.

"elif" means "else if", where "else" means "if nothing previous matched".


pgpmktmYIQJiC.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enum vs OrderedEnum

2013-08-06 Thread Ian Kelly
On Aug 6, 2013 5:15 PM, "Ethan Furman"  wrote:
>
> Use the .value attribute instead.  You could also substitute self for
Environment.

It feels more natural and readable to compare the enum instances rather
than their value attributes. If I am ordering the values then that seems to
imply that the enumeration itself is ordered. So I guess my question is
better stated: is there a better way to do this that doesn't involve
ordered comparisons at all?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ActivePython] Upgrading fails

2013-08-06 Thread Terry Reedy

On 8/6/2013 6:12 PM, Gilles wrote:

Hello,

I already posted in their forum, but got no reply and figured some
people here might have experienced this too.

I'm currently running ActivePython 2.5.1.1 on my XP Pro host.

After downloading and running the installer to 2.7.2.5, I get the
following error message:

"Windows Installer: The Windows Installer Service could not be
accessed. This can occur if the Windows Installer is not correctly
installed."

Has someone seen this, and knows what to do?


No and no. I would search "Windows Installer Service could not be
accessed" (I just did and there are lots of relevant hits.)
Try the same for any Windows error message.
--
Terry Jan Reedy

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


Re: HTTP post with urllib2

2013-08-06 Thread Joel Goldstick
On Tue, Aug 6, 2013 at 7:35 PM, cerr  wrote:
> On Tuesday, August 6, 2013 4:08:34 PM UTC-7, Joel Goldstick wrote:
>> On Tue, Aug 6, 2013 at 6:52 PM, cerr  wrote:
>>
>> > Hi,
>>
>> >
>>
>> > Why does this code:
>>
>> >
>>
>> > #!/usr/bin/python
>>
>> >
>>
>> >
>>
>> > import urllib2
>>
>> > from binascii import hexlify, unhexlify
>>
>> >
>>
>> > host = "localhost"
>>
>> > uri="/test.php"
>>
>> > data ="\x48\x65\x6C\x6C\x6F\x57\x6F\x72\x6C\x64" #Hello World
>>
>> > url="http://{0}{1}?f=test".format(host, uri)
>>
>> > req = urllib2.Request(url, data,{'Content-Type': 
>> > 'application/octet-stream'})
>>
>> > req.get_method = lambda: 'PUT'
>>
>>
>>
>> What does the above line do? is it the same as req.get_method = 'PUT'
>
> I guess so, I got this from an example copy & paste :x

That's not a very good answer!  Honest, but really.  Just because you
can cut and paste, doesn't mean you are learning to program.
>
>>
>> > response = urllib2.urlopen(req, 120)
>>
>>
>>
>> the docs say req should be a url.  Is it?
>
> no, it's an instance of req = urllib2.Request()
>>
>> > retval = response.read()
>>
>> > print "RETVAL "+retval
>>
>> >
>>
>> >
>>
>> >
>>
>> > return me this:
>>
>> >
>>
>> > ./post.py
>>
>> > Traceback (most recent call last):
>>
>> >   File "./post.py", line 13, in 
>>
>> > response = urllib2.urlopen(req, 120)
>>
>> >   File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
>>
>> > return _opener.open(url, data, timeout)
>>
>> >   File "/usr/lib/python2.7/urllib2.py", line 398, in open
>>
>> > req = meth(req)
>>
>> >   File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
>>
>> > 'Content-length', '%d' % len(data))
>>
>> >
>>
>> >
>>
>> > I don't get it, what's going on here?
>>
>> >
>>
>> > Thank you!
>>
>> > --
>>
>> > http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>> KInda of ducking your questions, but the requests module is a lot
>>
>> easier to use and
>>
>> understand:http://docs.python-requests.org/en/latest/
>
> But there must be a way to get this working with urllib alone...

I'm sure there is.  I'm not a pro at urllib, not even requests but
when I have used it, it made a lot more sense.

It got changed in python 3, so the python core group seemed not to
like how the earlier modules worked.

At any rate.  wait a while.  Someone on the list will give you more
specific advice I'm sure
> --
> http://mail.python.org/mailman/listinfo/python-list



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


Re: Enum vs OrderedEnum

2013-08-06 Thread Rhodri James
On Wed, 07 Aug 2013 00:46:39 +0100, Ian Kelly   
wrote:



On Aug 6, 2013 5:15 PM, "Ethan Furman"  wrote:


Use the .value attribute instead.  You could also substitute self for

Environment.

It feels more natural and readable to compare the enum instances rather
than their value attributes. If I am ordering the values then that seems  
to

imply that the enumeration itself is ordered. So I guess my question is
better stated: is there a better way to do this that doesn't involve
ordered comparisons at all?


You could create sets (frozensets?) of standard and hostile environments  
as class variables.


--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP post with urllib2

2013-08-06 Thread MRAB

On 06/08/2013 23:52, cerr wrote:

Hi,

Why does this code:

#!/usr/bin/python


import urllib2
from binascii import hexlify, unhexlify

host = "localhost"
uri="/test.php"
data ="\x48\x65\x6C\x6C\x6F\x57\x6F\x72\x6C\x64" #Hello World
url="http://{0}{1}?f=test".format(host, uri)
req = urllib2.Request(url, data,{'Content-Type': 'application/octet-stream'})
req.get_method = lambda: 'PUT'
response = urllib2.urlopen(req, 120)
retval = response.read()
print "RETVAL "+retval



return me this:

./post.py
Traceback (most recent call last):
   File "./post.py", line 13, in 
 response = urllib2.urlopen(req, 120)
   File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
 return _opener.open(url, data, timeout)
   File "/usr/lib/python2.7/urllib2.py", line 398, in open
 req = meth(req)
   File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
 'Content-length', '%d' % len(data))


I don't get it, what's going on here?


The docs say """urllib2.urlopen(url[, data][, timeout])""".

You're calling it as """urllib2.urlopen(req, 120)""".

In other words, 'url' is req and 'data' is 120.

It should be """urllib2.urlopen(req, None, 120)""".

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


Re: Newbie: static typing?

2013-08-06 Thread Chris Angelico
On Wed, Aug 7, 2013 at 12:02 AM, Terry Reedy  wrote:
> 3) The code falls into an infinite loop or recursion.
>
> The solution is to think before looping or recursing.  This often involves
> value checking (non-negative int or non-fractional float, for instance)
> rather than type checking in the usual static type-checking sense.

Yeah, there aren't many languages that let you declare that the
argument must be a positive integer. That's just something you have to
test for manually.

> One also needs to be careful about passing unbounded iterators to other
> functions and remember that unboundedness is contagious. (filter(pred,
> unbounded_iterator) is an unbounded iterator). Again, this is a 'value' or
> implicit sub-type issue rather than a explicit, visible 'type' issue.

Not quite always; I'd say that unboundedness is as contagious as IEEE
Infinity. Lots of operations on infinity will yield infinity, but a
few won't. itertools.islice can guarantee a finite iterator, and
takewhile may terminate. But yes, with filter() it certainly is.

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


Re: HTTP post with urllib2

2013-08-06 Thread Chris Angelico
On Tue, Aug 6, 2013 at 11:52 PM, cerr  wrote:
> ./post.py
> Traceback (most recent call last):
>   File "./post.py", line 13, in 
> response = urllib2.urlopen(req, 120)
>   File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
> return _opener.open(url, data, timeout)
>   File "/usr/lib/python2.7/urllib2.py", line 398, in open
> req = meth(req)
>   File "/usr/lib/python2.7/urllib2.py", line 1116, in do_request_
> 'Content-length', '%d' % len(data))
>
>
> I don't get it, what's going on here?
>

You've given a traceback without the actual error. MRAB happened to
figure out the mistake just from what you posted, but in future, do
try to copy a bit more down :)

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


Re: Enum vs OrderedEnum

2013-08-06 Thread Ethan Furman

On 08/06/2013 04:46 PM, Ian Kelly wrote:


On Aug 6, 2013 5:15 PM, "Ethan Furman" mailto:et...@stoneleaf.us>> wrote:


Use the .value attribute instead.  You could also substitute self for 
Environment.


It feels more natural and readable to compare the enum instances rather than 
their value attributes. If I am ordering
the values then that seems to imply that the enumeration itself is ordered. So 
I guess my question is better stated: is
there a better way to do this that doesn't involve ordered comparisons at all?


If the only time you are using their Ordered nature is inside the class, it's an implementation detail.  As such, using 
the value seems fine to me.


There are other options:

  - using sets, as Rhodri pointed out (extra work is needed, though, because a 
set would want to turn into an Enum member)

  - using AutoNumber instead of Ordered, and specifing the growth factor 
directly


AutoNumber
--

class AutoNumber(Enum):
"ignore any arguments, __init__ can have them"
def __new__(cls, *args):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj

class Environment(AutoNumber):

gaia = 2.0
fertile = 1.5
terran = 1.0
jungle = 1.0
ocean = 1.0
arid = 1.0
steppe = 1.0
desert = 1.0
minimal = 1.0
barren = 0.5
tundra = 0.5
dead = 0.5
inferno = 0.5
toxic = 0.5
radiated = 0.5

def __init__(self, growth_factor):
self._growth_factor = growth_factor

@property
def growth_factor(self):
return self._growth_factor

This works because each Enum member gets its own integer value (1 - 15) in __new__, plus a growth factor that is stored 
by __init__.  Whether you think this is better I have no idea.  ;)


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


Re: Enum vs OrderedEnum

2013-08-06 Thread Ben Finney
Ian Kelly  writes:

> class Environment(OrderedEnum):

I have nothing to add regarding the Python code, but I wanted to make a
language correction:

> gaia = 1
> fertile = 2
> terran, jungle, ocean, arid, steppe, desert, minimal = range(3, 10)
> barren, tundra, dead, inferno, toxic, radiated = range(10, 16)

Terrain that is “radiated” would be terrain that has some kind of spokes
spreading out from its centre. I think you mean “irradiated”.

Hope the game goes well :-)

-- 
 \  “Saying that Java is nice because it works on all OSes is like |
  `\ saying that anal sex is nice because it works on all genders” |
_o__)—http://bash.org/ |
Ben Finney

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


Re: Class hierarchy problem

2013-08-06 Thread Ben Finney
Terry Reedy  writes:

> On 8/6/2013 11:36 AM, BrJohan wrote:
>
> > Consider a botanical classification system (somewhat analogous to my
> > 'problem' as it effectively is related to classification of entities):
> >
> > A Domain should know about its Kingdoms,
> > a Kingdom should know about its Phylums,
> > ...
> > a Genus should know about its Species.
>
> As some already said, 'a domain' is an instance of Domain (or possibly
> generic Taxon). We have on Earth one instance of 'Life'.

I think the term for a taxonomic grouping of life, if you want to avoid
specifying some specific level of the taxonomy, is “clade”
https://en.wiktionary.org/wiki/clade>.

-- 
 \ “First they came for the verbs, and I said nothing, for verbing |
  `\weirds language. Then, they arrival for the nouns and I speech |
_o__)   nothing, for I no verbs.” —Peter Ellis |
Ben Finney

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


Re: Beginner question

2013-08-06 Thread eschneider92
Thanks that helped a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can someone suggest better resources for learning sqlite3? I wanted to use the Python library but I don't know sql.

2013-08-06 Thread memilanuk
On 08/03/2013 10:57 AM, Aseem Bansal wrote:
> I was writing a Python script for getting the user stats of a
> website(Specifically codereview.stackexchange). I wanted to store the
> stats in a database. I found Python3's sqlite3 library. I found that
> I needed sql commands for using it.
> 
> I have tried sql.learncodethehardway but it isn't complete yet. I
> tired looking on stackoverflow's  sql tag also but nothing much
> there. Can someone suggest me better resources for learning
> sql/sqlite3?
> 

https://www.youtube.com/watch?v=__eI1sbEfLw&feature=c4-overview-vl&list=PLAA9B7C174493EC68

The same author has some other videos on working with sqlite in general,
sql, etc. that may also prove useful.

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


new to While statements

2013-08-06 Thread krismesenbrink
import random



def room ():

hp = 10
while hp != 0:

random_Number = random.randint(1, 2)

#asking if you want to roll/play
des = input("Would you like to roll the die?")

if des == ("y"):
print ("Rolling the die...")
print ("You rolled a...")
print (random_Number)

#a "monster" appers if you roll a 1""
if random_Number == 1:
monster_hp = 10
print ("Oh no a Monsster!")
print ("would you like to attack?")
answer = input("y or n?")
if answer == "y":
#if you choose to battle this is what happens
while monster_hp >=0:
print ("you attack")
damage_done = random.randint(0,5)
print ("You do ",damage_done,"damage")
monster_hp = monster_hp - damage_done
print ("the monster takes a hit, it has ", monster_hp,
"left")


elif answer == ("n"):
print ("you run away")

else:
print ("You and the monster just stare at one another")
else:
print ("You find nothing")
# if you decisde to not play it will kill you
elif des == ("no"):
hp = 0
print ("Maybe next time!")
else:
print ("please enter yes or no")

room()


this is the code i'm making. as the subject says im new to while statements. i 
am having problems with the monster battle part, it takes health away from the 
"monster" but as soon as it gets to 0 or less i'd like the code to start from 
the top and ask you to roll the die again. any help on this would be greatly 
appreciative
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new to While statements

2013-08-06 Thread snakeinmyboot
Hey there, cool idea you've got going on here! As far as I can tell 
though...what you want to happen, is indeed actually happening. Did you mean 
something else? Everytime I run the script and defeat a monster, it asks me if 
I want to roll the dice again. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new to While statements

2013-08-06 Thread krismesenbrink
and it seems you are right about that, i don't know what was wrong with my IDE 
before, i closed it and opened it up again,seemed to fix the problem. thanks 
for taking the time to look at it anyway! 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new to While statements

2013-08-06 Thread snakeinmyboot
yea no problem. heres a little tip though so you atleast get something out of 
the post.

monster_hp = monster_hp - damage_done

can be simplified by writing

monster_hp -= damage_done

the -= means equal to whatever is on the left, minus whatevers on the right. 
this can be done with addition, multiplication, division, etc etc etc.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >