Re: Nested Mapping

2010-10-21 Thread Arnaud Delobelle
Raymond Hettinger  writes:

> I'm considering a nested mapping class for the collections module and
> would like to solicit feedback from people here on comp.lang.python:
>
>
> http://code.activestate.com/recipes/577434-nested-contexts-a-chain-of-mapping-objects/
>

Django has such contexts in its templating engine.  It may be worth
looking if this fits with theirs.

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


ANN: wxPython 2.9.1.1

2010-10-21 Thread Robin Dunn

Announcing
--

The 2.9.1.1 release of wxPython is now available for download at
http://wxpython.org/download.php.  This is the first official release
in the 2.9 development release series.  There are lots and lots of new
widgets and other awesome stuff that have been added since the 2.8
series, with more to come in future releases.  A list of changes can be
seen at http://wxpython.org/recentchanges.php.  Also new with this
release is a build for Mac OSX and Python 2.7 that uses the Cocoa API
and supports the 64-bit architecture on OSX 10.5 and 10.6.

Various binaries are available for 32-bit and 64-bit Windows, and also
for OSX using the Carbon and Cocoa APIs, for Python 2.5, 2.6 and 2.7.
And source code is also available at http://wxpython.org/download.php
of course for building your own.


What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a set of Python extension modules that wrap the GUI 
components of the popular wxWidgets cross platform library, which is 
written in C++.


wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit and 64-bit Microsoft Windows,
most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+.
In most cases the native widgets are used on each platform to provide
a 100% native look and feel for the application.

--
Robin Dunn
Software Craftsman
http://wxPython.org

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


Help Needed - Using Safenet( Previously, Aladdin) HASP Hardware Lock with Python

2010-10-21 Thread Bishwarup Banerjee
Dear All,

It will be very kind of you, if you can let me know (Or point to some
links), how to use HASP Hardware Lock using Python ?
I am trying to handle Hardware Lock authentication for our project, but cant
find any clear cut solution.

I am using python 2.5 on windows XP platform.

With Warm Regards,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythagorean triples exercise

2010-10-21 Thread Terry Reedy

On 10/21/2010 7:55 PM, Baba wrote:


the bit i'm having difficulties with in constructing my loops is:
"whose small sides are no larger than n"


from math import sqrt

def py_trips(n):
  for b in range(4,n+1):
for a in range(3,b+1):
  cf = sqrt(a*a+b*b)
  c  = int(cf)
  if c == cf: yield a, b, c

for t in py_trips(200): print(t)

# prints
(3,4,5)
...
(150, 200, 250)

This version assumes that if a*a+b*c is an exact square of an integer, 
the floating point sqrt will be an exact integral value, which I believe 
it should be for values up to the max (for n max 200) of 8.


It produces multiples of each triple, such as (3,4,5), (6,8,10), 
(9,12,15), ... (150,200, 250), which a different formulation of the 
problem might exclude, to only ask for 'basic' triples of relatively 
prime numbers.




--
Terry Jan Reedy

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


removing a post from python

2010-10-21 Thread Mike L

http://www.mail-archive.com/python-list@python.org/msg175722.html
 
hello could you remove above post... off topic and spam
 
thank you -- 
http://mail.python.org/mailman/listinfo/python-list


Re: functions, list, default parameters

2010-10-21 Thread Andreas Waldenburger
On Thu, 21 Oct 2010 19:53:53 -0700 John Nagle  wrote:

> On 10/21/2010 2:51 PM, Chris Rebert wrote:
> > On Thu, Oct 21, 2010 at 2:36 PM, Sean Choi  wrote:
> >> I found two similar questions in the mailing list, but I didn't
> >> understand the explanations.
> >> I ran this code on Ubuntu 10.04 with Python 2.6.5.
> >> Why do the functions g and  behave differently? If calls
> >> (3) and g(3) both exit their functions in the same state, why
> >> do they not enter in the same state when I call (4) and g(4)?
> >>
> >> #
> >> --
> >> my code: def (a, L=[]):
> >
> > This is a common newbie stumbling-block: Don't use lists (or
> > anything mutable) as default argument values
> 
>  That really should be an error.
> 
What do you mean? That using a list as default arguments should throw
an error?

While not very commonly needed, why should a shared default argument be
forbidden?

/W

-- 
To reach me via email, replace INVALID with the country code of my home 
country.  But if you spam me, I'll be one sour Kraut.

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


Re: functions, list, default parameters

2010-10-21 Thread John Nagle

On 10/21/2010 2:51 PM, Chris Rebert wrote:

On Thu, Oct 21, 2010 at 2:36 PM, Sean Choi  wrote:

I found two similar questions in the mailing list, but I didn't understand
the explanations.
I ran this code on Ubuntu 10.04 with Python 2.6.5.
Why do the functions g and  behave differently? If calls (3) and
g(3) both exit their functions in the same state, why do they not enter in
the same state when I call (4) and g(4)?

# -- my
code:
def (a, L=[]):


This is a common newbie stumbling-block: Don't use lists (or anything
mutable) as default argument values


That really should be an error.

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


Re: Ideas on how to parse a dynamically generated html pages

2010-10-21 Thread Tim Harig
On 2010-10-22, chad  wrote:
> Let's say there is a site that uses javascript to generate menus. More
> or less what happens is when a person clicks on url, a pop up menu
> appears asking the users for some data. How would I go about
> automating this? Just curious because the web spider doesn't actually
> pick up the urls that generate the menu. I'm assuming the actual url
> link is dynamically generated?

You have two options:

1. Look at the javascript to see what interfaces it uses.  If it is
generating menues, then it is getting the data it uses to generate
those menus from somewhere.  Once you have found that resource,
you can access it yourself with a request from your Python code.
This is generally the best approach if possible.

2. You can automate a bowser thorough a COM/XPCOM/etc. interface
which allows you to access the DOM object in real time as it is
modified by the Javascript and even to trigger javascript events.
There are libraries that will do this as well.  I have used
this on heavy AJAX style interfaces with mountains of spagetti
Javascript that were simply too large and poorly designed to
try to understand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Ideas on how to parse a dynamically generated html pages

2010-10-21 Thread chad
Let's say there is a site that uses javascript to generate menus. More
or less what happens is when a person clicks on url, a pop up menu
appears asking the users for some data. How would I go about
automating this? Just curious because the web spider doesn't actually
pick up the urls that generate the menu. I'm assuming the actual url
link is dynamically generated?

Here is the code I'm using to get the URLs...

>>> from HTMLParser import HTMLParser
>>> from urllib2 import urlopen
>>> class Spider(HTMLParser):
...   def __init__(self, url):
...   HTMLParser.__init__(self)
...   req = urlopen(url)
...   self.feed(req.read())
...   def handle_starttag(self, tag, attrs):
...   if tag == 'a' and attrs:
... print "Found Link => %s" % attrs[0][1]


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


Earn unlimited in Management careers.

2010-10-21 Thread gaurav
Additional income resources - Fresher or experience candidate can grow
career
http://managementjobs.webs.com/pm.htm

Get careers in Management work. Careers recruitments.
http://topcareer.webs.com/businessmanagement.htm

Work from home genuine bulk data entry, home and government jobs
sources.
http://rojgars1.webs.com/gov.htmhttp://rojgars.webs.com/bankingjobs.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested Mapping

2010-10-21 Thread Paul Rubin
Raymond Hettinger  writes:
> The c.parent.parent.parent chain finds successive enclosing contexts:

I was asking about finding the child contexts, not the parents.  This is
analogous to how you can find the keys in a dict with dict.keys().

>> One question: what should
>>
>>    c["foo"] = 7
>>    d = c.new_child()
>>    del d["foo"]
>>
>> do?  
>
> By default, it raises a KeyError because 'foo' is not in the current
> context.  But if enable_nonlocal is set to True, it removes 'foo' from
> the parent context, c.

I would not have guessed either of those behaviors.  What happens on

  c["foo"] = 7
  d = c.new_child()
  d["foo"] = 8
  del d["foo"]
  print c["foo"], d["foo"]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested Mapping

2010-10-21 Thread Raymond Hettinger
On Oct 21, 5:18 pm, Paul Rubin  wrote:
> The API you suggested looks reasonable although you should also say how
> to delete a context, how to find the inner contexts of a context, etc.

The c.parent.parent.parent chain finds successive enclosing contexts:

   while c.parent is not None:
   print c
   c = c.parent


> One question: what should
>
>    c["foo"] = 7
>    d = c.new_child()
>    del d["foo"]
>
> do?  

By default, it raises a KeyError because 'foo' is not in the current
context.

But if enable_nonlocal is set to True, it removes 'foo' from the
parent context, c.

Depends on whether you want parent contexts to be mutable or not.
With Python's nonlocal keyword, we can set values in an enclosing
scope.  This tool lets you do that also.


Raymond

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


Re: Nested Mapping

2010-10-21 Thread Paul Rubin
Raymond Hettinger  writes:
> Hopefully, that discussion can be in a separate thread.
> This is really about keeping all the nice O(1) characteristics
> of dicts and keeping their straight-forward API while adding
> the ability to support nested lookups.

Are you saying the O(1) characteristics are retained even when the
contexts are N levels deep?

> Sorry for the brush-off, but it would be ashamed if this thread got
> immediately hijacked, and I were to lose possible feedback on the
> API for nested mappings.

The API you suggested looks reasonable although you should also say how
to delete a context, how to find the inner contexts of a context, etc.

One question: what should

   c["foo"] = 7
   d = c.new_child()
   del d["foo"]

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


Re: pythagorean triples exercise

2010-10-21 Thread Baba
On Oct 21, 10:18 pm, Terry Reedy  wrote:
> On 10/21/2010 6:55 AM, Baba wrote:
>
> > Hi everyone
>
> > i need a hint regarding the following exercise question:
>
> > "Write a program that generates all Pythagorean triples whose small
> > sides are no larger than n.
>
> This is not well worded. I take 'small sides' (plural) to mean the two
> smaller, non-hypotenuse sides (which are necessarily shorter than the
> hypotenuse). So the possible pairs of values i,j, where i is the shorter
> of the two, have
>
> > Try it with n<= 200."
>
> Again, not well worded; I believe this is meant to be n==200, except
> that the program should take n as a parameter and then give it value
> 200, so that the could work if n were given some other value.
>
> So the possible pairs of values i,j, where i is the shorter of the two,
> have j <= n (==200) and i <= j.
>
> --
> Terry Jan Reedy

Hi Terry,

the full exercise reads as follows:

Write a program that generates all Pythagorean triples whose small
sides are no larger than n. Try it with n <= 200. (Hint: Use two for
loops to enumerate
possible values for the small sides and then test to determine whether
the result
is an integral square.

source: http://users.soe.ucsc.edu/~pohl/12A/ch03-state.pdf (exercise
11, it's a Java book but i like to use Python for solving such basic
exercises as it is a much less cumbersome language)

i agree that possibly the wording makes this more difficult than it
is. Anyway, i'm a beginner so my problem solving techniques are still
quite shaky.

the bit i'm having difficulties with in constructing my loops is:
"whose small sides are no larger than n"
i don't know what to do with that :(

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


Re: Nested Mapping

2010-10-21 Thread Raymond Hettinger
On Oct 21, 4:28 pm, Paul Rubin  wrote:
> Raymond Hettinger  writes:
> What I really want is a Haskell-like persistent (i.e. purely functional)
> dictionary implemented as an AVL tree or something like that.

Hopefully, that discussion can be in a separate thread.
This is really about keeping all the nice O(1) characteristics
of dicts and keeping their straight-forward API while adding
the ability to support nested lookups.

An AVL tree has different performance characteristics (like O(log n)
search and has a substantially different API (adding ordering
operations)
and works on different data types (relying on total ordering rather
than hashing an equality).  Also, having a persistence is a different
requirement.

Sorry for the brush-off, but it would be ashamed if this thread got
immediately hijacked, and I were to lose possible feedback on the
API for nested mappings.


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


Re: Nested Mapping

2010-10-21 Thread Paul Rubin
Raymond Hettinger  writes:
> I would appreciate any feedback on the API and on how well it fits
> with various use cases that you've found in the wild.

What I really want is a Haskell-like persistent (i.e. purely functional)
dictionary implemented as an AVL tree or something like that.  It means
the "child" can just be a forked version of the parent, that shares most
of the same nodes.  I think that handles most of the obvious uses of the
nested mapping proposal.

Hedgehog Lisp has AVL-based persistent dictionaries implemented in C,
that I've been thinking of trying to port to the Python C API sometime.
-- 
http://mail.python.org/mailman/listinfo/python-list


Nested Mapping

2010-10-21 Thread Raymond Hettinger
I'm considering a nested mapping class for the collections module and
would like to solicit feedback from people here on comp.lang.python:

   
http://code.activestate.com/recipes/577434-nested-contexts-a-chain-of-mapping-objects/

The class is an attempt to generalize from existing use cases (i.e.
the _multimap class in string.py).  I also took guidance from the
symbol table analysis tools in ANTLR (see p.173 of Language
Implementation Patterns by Terence Parr).  Nested mappings make it
easy to build chains and trees of scopes (like vocabularies in Forth
or like inheritance hierarchies in Python).

The basic idea is to perform look-ups into a series a dictionaries,
much like Python does with locals, nested scopes, global (module
level) scope and builtins.

Starting with a root context which has a full dictionary API, multiple
child contexts can be created.  New values are stored in the child
contexts, potentially masking those in a parent context (much like
shadowing a Python builltin).  Lookups start with the child node and
work upward through the chain of parents.

There is also a variant where __setitem__ and __delitem__ can mutate
values in parent contexts (much like the nonlocal keyword allows in
Python).

The API seeks to fully emulate regular dictionaries.  The only extra
capabilities are:

   d = c.new_child()# create a subcontext
   e = d.new_child()# create a subsubcontext
   e.parent # find the next enclosing context
   e.root # find the outermost enclosing context
   f = c.new_child() # create a subcontext of c, independent of d
& e

I would appreciate any feedback on the API and on how well it fits
with various use cases that you've found in the wild.


Raymond

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


Re: socket.sendto / UDP problem

2010-10-21 Thread MRAB

On 21/10/2010 21:05, Todd Walter wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 17:03:58 +0100
MRAB  wrote:


On 21/10/2010 15:57, Todd Walter wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 00:07:58 +0100
MRAB   wrote:




[snip]

The docs for 'sendto' say:

   """The socket should not be connected to a remote socket,
since the destination socket is specified by address."""

Could your problem be caused by you binding the socket to a source
port, so it's going out both to the bound port _and_ the one given
the binding?

Have you tried using two sockets, one outgoing and the other
incoming?

BTW, your code for handling the response doesn't cope with it
coming in a bit at a time. It loops discard any previous data from
the previous iteration.

Also, it's more Pythonic to say:

   while '\r' not in response:
   ...

I haven't bound the socket to a remote port, as I read it; it'sp
bound to a source port (192.168.10.2:2260, the local machine) and
just transmits to an address with a port glommed onu sn
(192.168.10.1:2002, the PLC).

[snip]
What I meant was that you're using 'pcSocket' for both directions and
using .bind on it.

Try creating two sockets, 'pcInSocket' and 'pcOutSocket', and bind
only pcOutSocket.



> As it turns out, Windows will throw a 10022 if you try and .recvfrom
> on an unbound port so I went back to the old way as it didn't seem to
> be related to my problem.
>
Oops! I should've said "bind only pcInSocket". Sorry! :-(
   |
> I re-captured the packets from the utility again and I noticed that my
> text string is getting s p a c e d o u t in the datagram whereas the
> primary utility sends a nice cohesive "spacedout".  My early
> transmissions work this way, successfully, as well and I think it is
> because either Python or Windows is treating my text strings
> differently than my numerical strings; more clearly when I send "1234"
> it goes out "1234" and when I send "Todd" it goes out as "T o d d ".
> This will obviously overflow the PLC and cause a reset.
>
> Any ideas?
>
If they're all bytestrings then the contents shouldn't matter. Try
printing their repr just to check.
--
http://mail.python.org/mailman/listinfo/python-list


question regarding thread display on python mailing list

2010-10-21 Thread Sean Choi
I notice sometimes when I follow a thread on the mailing list archives, the
thread will not be all together. To see what I mean, look at the thread
"splitting comp.lang.python" as shown here:
http://mail.python.org/pipermail/python-list/2000-March/thread.html#639685.
You can see one large chunk of replies listed together and a subsequent set
of replies listed further down. Is there some action I need to do on my part
to prevent thread display separation from happening when I write replies on
the mailing list?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python shell silently ignores termios.tcsetattr()

2010-10-21 Thread Nobody
On Wed, 20 Oct 2010 16:18:57 +, kj wrote:

> I tried to fix the problem by applying the equivalent of "stty -echo"
> within a python interactive session, but discovered that this setting is
> immediately (and silently) overwritten.

FWIW, I don't see this behaviour with Python 2.6.5 on Linux. If I change
the tty settings from within an interactive Python session, they stay
changed. The only reference to tcsetattr() I can find in the Python source
code is in the termios module.

I suspect that it may be related to the "readline" module. My Python is
built with readline support (I normally use XEmacs' comint-based modes
rather than e.g. xterm, and readline either doesn't help or gets in the
way). Also, the implementation of the readline module is platform-specific:



The readline  module defines a number of functions to facilitate
completion and reading/writing of history files from the Python
interpreter. This module can be used directly or via the rlcompleter
module. Settings made using this module affect the behaviour of both the
interpreter's interactive prompt and the prompts offered by the
raw_input()  and input() built-in functions. 

Note: On MacOS X the readline module can be implemented using the 
libedit
library instead of GNU readline. 

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


Re: functions, list, default parameters

2010-10-21 Thread Chris Rebert
On Thu, Oct 21, 2010 at 2:36 PM, Sean Choi  wrote:
> I found two similar questions in the mailing list, but I didn't understand
> the explanations.
> I ran this code on Ubuntu 10.04 with Python 2.6.5.
> Why do the functions g and  behave differently? If calls (3) and
> g(3) both exit their functions in the same state, why do they not enter in
> the same state when I call (4) and g(4)?
>
> # -- my
> code:
> def (a, L=[]):

This is a common newbie stumbling-block: Don't use lists (or anything
mutable) as default argument values (in this case, for L); a new list
is *not* created for every function invocation, they'll all share the
*exact same list object*. Use None and then create a fresh list (or
what have you) in the function body. See
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

>     print "enter function"
>     print "a = ", a, "and L = ", L
>     if L == []:
>         print "hey, L is empty"
>         L = []

The previous line is why the two functions' behaviors differ (g()
lacks this line). Read the above FAQ, and then carefully trace through
the execution of the functions; the difference will then be clear.

Cheers,
Chris
--
http://blog.rebertia.com

>     L.append(a)
>     print "after append, L = ", L
>     return L

> def g(a, L=[]):
>     print "enter function"
>     print "a = ", a, "and L = ", L
>     if L == []:
>         print "hey, L is empty"
>     L.append(a)
>     print "after append, L = ", L
>     return L
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do I search python mailing list archives?

2010-10-21 Thread Sean Choi
just sending out a late thank you for the response
-- 
http://mail.python.org/mailman/listinfo/python-list


functions, list, default parameters

2010-10-21 Thread Sean Choi
I found two similar questions in the mailing list, but I didn't understand
the explanations.

I ran this code on Ubuntu 10.04 with Python 2.6.5.

Why do the functions g and  behave differently? If calls (3) and
g(3) both exit their functions in the same state, why do they not enter in
the same state when I call (4) and g(4)?



# -- my
code:
def (a, L=[]):
print "enter function"
print "a = ", a, "and L = ", L
if L == []:
print "hey, L is empty"
L = []
L.append(a)
print "after append, L = ", L
return L

def g(a, L=[]):
print "enter function"
print "a = ", a, "and L = ", L
if L == []:
print "hey, L is empty"
L.append(a)
print "after append, L = ", L
return L

print (3)
print (4)
print (7)
print g(3)
print g(4)
print g(7)



# -- my
output:
--- calls
enter function
a =  3 and L =  []
hey, L is empty
after append, L =  [3]
[3]
enter function
a =  4 and L =  []
hey, L is empty
after append, L =  [4]
[4]
enter function
a =  7 and L =  []
hey, L is empty
after append, L =  [7]
[7]
---g calls
enter function
a =  3 and L =  []
hey, L is empty
after append, L =  [3]
[3]
enter function
a =  4 and L =  [3]
after append, L =  [3, 4]
[3, 4]
enter function
a =  7 and L =  [3, 4]
after append, L =  [3, 4, 7]
[3, 4, 7]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythagorean triples exercise

2010-10-21 Thread Terry Reedy

On 10/21/2010 6:55 AM, Baba wrote:

Hi everyone

i need a hint regarding the following exercise question:

"Write a program that generates all Pythagorean triples whose small
sides are no larger than n.


This is not well worded. I take 'small sides' (plural) to mean the two 
smaller, non-hypotenuse sides (which are necessarily shorter than the 
hypotenuse). So the possible pairs of values i,j, where i is the shorter 
of the two, have



Try it with n<= 200."


Again, not well worded; I believe this is meant to be n==200, except 
that the program should take n as a parameter and then give it value 
200, so that the could work if n were given some other value.


So the possible pairs of values i,j, where i is the shorter of the two, 
have j <= n (==200) and i <= j.


--
Terry Jan Reedy

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


Re: socket.sendto / UDP problem

2010-10-21 Thread Todd Walter
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 17:03:58 +0100
MRAB  wrote:

> On 21/10/2010 15:57, Todd Walter wrote:
> > -BEGIN PGP SIGNED MESSAGE-
> > Hash: SHA1
> >
> > On Thu, 21 Oct 2010 00:07:58 +0100
> > MRAB  wrote:
> >
> >>>
> >> [snip]
> >>
> >> The docs for 'sendto' say:
> >>
> >>   """The socket should not be connected to a remote socket,
> >> since the destination socket is specified by address."""
> >>
> >> Could your problem be caused by you binding the socket to a source
> >> port, so it's going out both to the bound port _and_ the one given
> >> the binding?
> >>
> >> Have you tried using two sockets, one outgoing and the other
> >> incoming?
> >>
> >> BTW, your code for handling the response doesn't cope with it
> >> coming in a bit at a time. It loops discard any previous data from
> >> the previous iteration.
> >>
> >> Also, it's more Pythonic to say:
> >>
> >>   while '\r' not in response:
> >>   ...
> > I haven't bound the socket to a remote port, as I read it; it'sp
> > bound to a source port (192.168.10.2:2260, the local machine) and
> > just transmits to an address with a port glommed onu sn
> > (192.168.10.1:2002, the PLC).
> [snip]
> What I meant was that you're using 'pcSocket' for both directions and
> using .bind on it.
> 
> Try creating two sockets, 'pcInSocket' and 'pcOutSocket', and bind
> only pcOutSocket.

As it turns out, Windows will throw a 10022 if you try and .recvfrom
on an unbound port so I went back to the old way as it didn't seem to
be related to my problem.  I re-captured the packets from the utility
again and I noticed that my text string is getting s p a c e d o u t
in the datagram whereas the primary utility sends a nice cohesive
"spacedout".  My early transmissions work this way, successfully, as
well and I think it is because either Python or Windows is treating my
text strings differently than my numerical strings; more clearly when I
send "1234" it goes out "1234" and when I send "Todd" it goes out as 
"T o d d ".   This will obviously overflow the PLC and cause a reset.  

Any ideas?

Regards,

- - Todd
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.16 (GNU/Linux)

iEYEARECAAYFAkzAnQUACgkQwnknPuQqPIOx6QCgjNP/S/dODwO/c7xk8xKZk1A7
IMQAniGKd5yaqRo3nAmHJJsrkEP6iL/j
=aH+4
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python has a "really hidden encapsulation"?

2010-10-21 Thread Arnaud Delobelle
dmytro starosud  writes:

> Hello,
> I'm Python beginner (from Ukraine).
> I may have found the way to really hide attributes in Python class.
> The whole control on this attribute is implemented inside of the
> class.
> *(code is below, Python 3)
> You see that we can't get the reference to instance of class
> "en_property" outside the class "segment", but in the inside we can.
>
> *It seems like there is no way to get the reference to field
> “en_property.v_min” or “en_property.v_max”.
> And object “s” has “two” attributes “v_min”: “s.__dict__['v_min']” and
> “s.v_min”.
>
> Help me find the answer, Can I change this hidden attribute outside
> the class?
> Or is it just an interesting feature?
> ...and Python has a "really hidden encapsulation"?
>
> code:
> class en_property(property):
>ptr_pget = None
>ptr_pset = None
>
>def pset(self, _class, value):
>self.ptr_pset(self, _class, value)
>
>def pget(self, _class):
>return self.ptr_pget(self, _class)
>
>def __init__(self, pget, pset):
>property.__init__(self, self.pget, self.pset)
>self.ptr_pget = pget
>self.ptr_pset = pset
>
> class segment():
>def min_set(prop, self, p_min):
>if (self.v_max is not None) and (p_min > self.v_max):
>raise AttributeError('It must be: "min < max"')
>else:
>prop.v_min = p_min
>
>def min_get(prop, self):
>if 'v_min' in dir(prop):
>return prop.v_min
>
>def max_set(prop, self, p_max):
>if (self.v_min is not None) and (p_max < self.v_min):
>raise AttributeError('It must be: "min < max"')
>else:
>prop.v_max = p_max
>
>def max_get(prop, self):
>if 'v_max' in dir(prop):
>return prop.v_max
>
>v_min = en_property(min_get, min_set)
>del min_set, min_get
>v_max = en_property(max_get, max_set)
>del max_set, max_get
>
> 
 s = segment()
 s.v_min = -1
 s.v_max = 1
 s.v_min = 2
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 6, in pset
>self.ptr_pset(self, _class, value)
>  File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 19, in min_set
>raise AttributeError('It must be: "min < max"')
> AttributeError: It must be: "min < max"
 s.__dict__['v_min'] = 2
 s.__dict__['v_min']
> 2
 s.v_min
> -1


One big problem is that the value of v_min and v_max is shared by all
instances of segment:

>>> s = segment()
>>> s.v_min = 3
>>> t = segment()
>>> t.v_min
3
>>> t.v_min = 5
>>> s.v_min
5

So it's not very useful (I suppose it's some kind of "class property").
Moreover I can still make v_min > v_max:

>>> s = segment()
>>> s.v_min = 5
>>> segment.v_max.v_max = 1
>>> s.v_min <= s.v_max
False

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


Re: Python has a "really hidden encapsulation"?

2010-10-21 Thread dmytro starosud
Thanks for answer,

Attribute accessing inside the class is implemented by getters and
setters: "min_set", "min_get", "max_set" and "max_get".
You can put your logic to this functions and parameter "prop" is the
direct reference to this property.
I can create a "really read-only attribute", and other developers
which use my class can't affect this attribute, they can only using
getters and setters written inside the class.
I realize that attribute changes can be just in getters and setters,
but this restriction it's insignificant.

In case with using __setattr__: you always can access an attribute by
__dict__ and implementation of this method also use __dict__,
but in case with "hidden property" you can rich the reference to
property inside the class (it is parapeter "prop") and outside the
class you cannot.

I didn't want to affirm that this way is like C# or Java
encapsulation, but I think the fact that physical reference to
attribute hides is really interesting and is the way to do
encapsulating like in C# or similar others.

*I have been locking for encapsulating in Python because all say that
is no way to "really" hide attributes. I think I disproved this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embarrassing class question

2010-10-21 Thread Robert Kern

On 10/21/10 2:12 PM, Brendan wrote:

On Oct 21, 3:56 pm, Ethan Furman  wrote:

Jonas H. wrote:

On 10/21/2010 08:09 PM, Brendan wrote:

Two modules:
x.py:
class x(object):
  pass



y.py:
from x import x
class y(x):
  pass



Now from the python command line:

import y
dir(y)

['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'x', 'y']



I do not understand why class 'x' shows up here.



Because that's how `import` behaves. It imports *every* member of the
module into the importing module's global namespace (except for
attributes that start with an underscore).


Um, no.  (unless you do "from  import *" at the module level)

What it does is add whatever you imported into the namespace where you
imported it.

Because y.py has "from x import x" the x class from x.py is added to the
y.py namespace.

~Ethan~- Hide quoted text -

- Show quoted text -


So what is usually done to prevent this? (In my case not wanting class
x added to the y.py namespace)
It seems sloppy.


You can explicitly delete it at the end of the file if you never reference it 
from one of your methods.


Mostly though, it just doesn't matter much. I recommend leaving it alone. If you 
want a nice, clean namespace for people to use, make a module (e.g. api.py) that 
doesn't define any classes or functions but just imports them from their 
defining modules.


--
Robert Kern

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

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


Re: embarrassing class question

2010-10-21 Thread Carl Banks
On Oct 21, 11:53 am, Brendan  wrote:
> On Oct 21, 3:47 pm, Carl Banks  wrote:
> > On Oct 21, 11:09 am, Brendan  wrote:
>
> > > Two modules:
> > > x.py:
> > > class x(object):
> > >     pass
>
> > > y.py:
> > > from x import x
> > > class y(x):
> > >     pass
>
> > > Now from the python command line:>>> import y
> > > >>> dir(y)
>
> > > ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
> > > 'x', 'y']
>
> > > I do not understand why class 'x' shows up here.
>
> > Because you imported it into the namespace, which is what the import
> > statement does.  dir() shows you what's in the namesace; therefore it
> > lists x.  dir() doesn't care, and can't know, if something was defined
> > in a namespace, or merely imported.
>
> > If it bothers you, you can put "del x" after the class y definition,
> > but I recommend against doing that in general.  If there's a reference
> > to x inside a function that function will raise an exception if
> > called, because it expects x to be inside the namespace.
>
> So it must never make sense to put subclasses in separate modules?

Putting a subclass in the same module simply because you don't want it
to appear in some other module's namespace is not a good idea, IMO.
Sometimes it makes sense to put the subclass in another module, it
depends on the organization of the project.

I'm not sure how familiar you are with Python's object and namespace
systems.  I assumed you were using dir() to see what objects were
defined in a module, and were disappointed to see x in the listing
also, but maybe you're under the impression that there is a lot of
duplicated data?  Not really: a namespace contains references
(pointers) and so takes up a minimal amount of space, not worth
worrying about.


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


Re: embarrassing class question

2010-10-21 Thread Brendan
On Oct 21, 3:56 pm, Ethan Furman  wrote:
> Jonas H. wrote:
> > On 10/21/2010 08:09 PM, Brendan wrote:
> >> Two modules:
> >> x.py:
> >> class x(object):
> >>      pass
>
> >> y.py:
> >> from x import x
> >> class y(x):
> >>      pass
>
> >> Now from the python command line:
> > import y
> > dir(y)
> >> ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
> >> 'x', 'y']
>
> >> I do not understand why class 'x' shows up here.
>
> > Because that's how `import` behaves. It imports *every* member of the
> > module into the importing module's global namespace (except for
> > attributes that start with an underscore).
>
> Um, no.  (unless you do "from  import *" at the module level)
>
> What it does is add whatever you imported into the namespace where you
> imported it.
>
> Because y.py has "from x import x" the x class from x.py is added to the
> y.py namespace.
>
> ~Ethan~- Hide quoted text -
>
> - Show quoted text -

So what is usually done to prevent this? (In my case not wanting class
x added to the y.py namespace)
It seems sloppy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embarrassing class question

2010-10-21 Thread Ian
On Oct 21, 12:53 pm, Brendan  wrote:
> So it must never make sense to put subclasses in separate modules?

It doesn't matter to Python whether the subclass is in the same module
or imported.  Do it whichever way makes the most sense to you from a
code organization perspective.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Arnaud Delobelle
Steven D'Aprano  writes:

> On Thu, 21 Oct 2010 11:37:36 +0200, Jean-Michel Pichavant wrote:

> By the way:
>
>> xCoordinate, yCoordinate, zCoordinate = polygon.nextPointCoordinates()
>
> Coordinates are pairs or triples of *ordinates* (no "co"). You can't have 
> an "x coordinate" -- that would be like unpacking a single pair of shoes 
> into a "left-pair" and a "right-pair".

Wrong, the ordinate is specifically the second coordinate (the first one
being the abscissa).  I don't think these words are in common use in the
english speaking world though (in France, "abscisse" and "ordonnée" are
terms taught at school).  The terms x-coordinate and y-coordinate are
very commonly used.

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


Re: embarrassing class question

2010-10-21 Thread Robert Kern

On 10/21/10 1:53 PM, Brendan wrote:

On Oct 21, 3:47 pm, Carl Banks  wrote:

On Oct 21, 11:09 am, Brendan  wrote:






Two modules:
x.py:
class x(object):
 pass



y.py:
from x import x
class y(x):
 pass



Now from the python command line:>>>  import y

dir(y)



['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'x', 'y']



I do not understand why class 'x' shows up here.


Because you imported it into the namespace, which is what the import
statement does.  dir() shows you what's in the namesace; therefore it
lists x.  dir() doesn't care, and can't know, if something was defined
in a namespace, or merely imported.

If it bothers you, you can put "del x" after the class y definition,
but I recommend against doing that in general.  If there's a reference
to x inside a function that function will raise an exception if
called, because it expects x to be inside the namespace.

Carl Banks


So it must never make sense to put subclasses in separate modules?


Of course it can make sense to put subclasses in separate modules, just for 
other reasons.


--
Robert Kern

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

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


Re: embarrassing class question

2010-10-21 Thread Chris Rebert
On Thu, Oct 21, 2010 at 11:53 AM, Brendan  wrote:
> On Oct 21, 3:47 pm, Carl Banks  wrote:
>> On Oct 21, 11:09 am, Brendan  wrote:
>> > Two modules:
>> > x.py:
>> > class x(object):
>> >     pass
>>
>> > y.py:
>> > from x import x
>> > class y(x):
>> >     pass
>>
>> > Now from the python command line:>>> import y
>> > >>> dir(y)
>>
>> > ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
>> > 'x', 'y']
>>
>> > I do not understand why class 'x' shows up here.
>>
>> Because you imported it into the namespace, which is what the import
>> statement does.  dir() shows you what's in the namesace; therefore it
>> lists x.  dir() doesn't care, and can't know, if something was defined
>> in a namespace, or merely imported.
>>
>> If it bothers you, you can put "del x" after the class y definition,
>> but I recommend against doing that in general.  If there's a reference
>> to x inside a function that function will raise an exception if
>> called, because it expects x to be inside the namespace.
>>
>> Carl Banks
>
> So it must never make sense to put subclasses in separate modules?

Limiting yourself to one class per module is neither mandatory nor
common in Python. Python is not Java.

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


Re: python shell silently ignores termios.tcsetattr()

2010-10-21 Thread kj
In  Lawrence D'Oliveiro 
 writes:

>In message , kj wrote:

>> I tried to fix the problem by applying the equivalent of "stty
>> -echo" within a python interactive session, but discovered that
>> this setting is immediately (and silently) overwritten.

>That seems reasonable behaviour; the command loop is resetting the terminal 
>to a reasonable state to allow it to read the next command. But the command 
>you execute can do anything it likes in-between. What’s wrong with that?

What's wrong with it is that what python thinks is a "reasonable
state" is actually wrong in this case (it differs from the default
setting established by the Emacs shell).  I had hoped that there
was a way to tell python what to regard as a "reasonable state".
I gather that there is no way to do this?

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


Re: embarrassing class question

2010-10-21 Thread Ethan Furman

Jonas H. wrote:

On 10/21/2010 08:09 PM, Brendan wrote:

Two modules:
x.py:
class x(object):
 pass

y.py:
from x import x
class y(x):
 pass

Now from the python command line:

import y
dir(y)

['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'x', 'y']

I do not understand why class 'x' shows up here.


Because that's how `import` behaves. It imports *every* member of the 
module into the importing module's global namespace (except for 
attributes that start with an underscore).


Um, no.  (unless you do "from  import *" at the module level)

What it does is add whatever you imported into the namespace where you 
imported it.


Because y.py has "from x import x" the x class from x.py is added to the 
y.py namespace.


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


Re: embarrassing class question

2010-10-21 Thread Brendan
On Oct 21, 3:47 pm, Carl Banks  wrote:
> On Oct 21, 11:09 am, Brendan  wrote:
>
>
>
>
>
> > Two modules:
> > x.py:
> > class x(object):
> >     pass
>
> > y.py:
> > from x import x
> > class y(x):
> >     pass
>
> > Now from the python command line:>>> import y
> > >>> dir(y)
>
> > ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
> > 'x', 'y']
>
> > I do not understand why class 'x' shows up here.
>
> Because you imported it into the namespace, which is what the import
> statement does.  dir() shows you what's in the namesace; therefore it
> lists x.  dir() doesn't care, and can't know, if something was defined
> in a namespace, or merely imported.
>
> If it bothers you, you can put "del x" after the class y definition,
> but I recommend against doing that in general.  If there's a reference
> to x inside a function that function will raise an exception if
> called, because it expects x to be inside the namespace.
>
> Carl Banks- Hide quoted text -
>
> - Show quoted text -

So it must never make sense to put subclasses in separate modules?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embarrassing class question

2010-10-21 Thread Carl Banks
On Oct 21, 11:09 am, Brendan  wrote:
> Two modules:
> x.py:
> class x(object):
>     pass
>
> y.py:
> from x import x
> class y(x):
>     pass
>
> Now from the python command line:>>> import y
> >>> dir(y)
>
> ['__builtins__', '__doc__', '__file__', '__name__', '__package__',
> 'x', 'y']
>
> I do not understand why class 'x' shows up here.

Because you imported it into the namespace, which is what the import
statement does.  dir() shows you what's in the namesace; therefore it
lists x.  dir() doesn't care, and can't know, if something was defined
in a namespace, or merely imported.

If it bothers you, you can put "del x" after the class y definition,
but I recommend against doing that in general.  If there's a reference
to x inside a function that function will raise an exception if
called, because it expects x to be inside the namespace.


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


Re: Spreadsheet-style dependency tracking

2010-10-21 Thread Stefaan Himpe

Florian Weimer wrote:


Are there libraries which implement some form of spreadsheet-style
dependency tracking?


The first that come to mind (I have very limited experience with them):

trellis http://peak.telecommunity.com/DevCenter/Trellis
pycells http://pycells.pdxcb.net/

Best regards,
Stefaan.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python has a "really hidden encapsulation"?

2010-10-21 Thread Carl Banks
On Oct 21, 9:49 am, dmytro starosud  wrote:
> Hello,
> I'm Python beginner (from Ukraine).
> I may have found the way to really hide attributes in Python class.
> The whole control on this attribute is implemented inside of the
> class.
> *(code is below, Python 3)
> You see that we can't get the reference to instance of class
> "en_property" outside the class "segment", but in the inside we can.
>
> *It seems like there is no way to get the reference to field
> “en_property.v_min” or “en_property.v_max”.
> And object “s” has “two” attributes “v_min”: “s.__dict__['v_min']” and
> “s.v_min”.
>
> Help me find the answer, Can I change this hidden attribute outside
> the class?
> Or is it just an interesting feature?
> ...and Python has a "really hidden encapsulation"?
[snip example]


Well, you say you can access the attribute from inside the class, but
you didn't show any examples of it.  What would happen if you had a
method that tried to run this: "self.v_min = 2"?  I didn't check it
but it looks like it'd raise the exception, too.

This is what the term "data hiding" means to me, and, in my
experience, with most people talking about OOP: they usually mean
hiding it from code outside the class while keeping it open to code
inside the class.  Which means "self.v_min=2" would work, but
"s.v_min=2" would not.  What you've done is to hide it from everyone,
so I wouldn't call it Data Hiding(tm), even if you have, technically,
hidden data.

The term I use for what you did here is "enforcing an invariant", and
I think it is an interesting feature and occasionally indispensible,
but it's also something Python's always been able to do.  Even in
Python 1.5, before properties and such, you could override __setattr__
to enforce invariants.


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


Re: embarrassing class question

2010-10-21 Thread Jonas H.

On 10/21/2010 08:09 PM, Brendan wrote:

Two modules:
x.py:
class x(object):
 pass

y.py:
from x import x
class y(x):
 pass

Now from the python command line:

import y
dir(y)

['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'x', 'y']

I do not understand why class 'x' shows up here.


Because that's how `import` behaves. It imports *every* member of the 
module into the importing module's global namespace (except for 
attributes that start with an underscore).


You can specify the attributes that shall be import with a star-import 
by settings __all__. In your case, you would add `__all__ = ['y']` to y.py.


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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Seebs
On 2010-10-21, Jean-Michel Pichavant  wrote:
> It can be short if descriptive:

> for o, c in cars:
> park(o)
> phone(c)

> for owner, car in cars: # by just using meaningful names you give the 
> info to the reader that you expect cars to be a list of tuple (owner, car)
> park(owner)
> phone(car) # see how it is easier to spot bug

In this case, yes.

The one that brought this up, though, was "except FooError, e:", and in
that case, there is no need for any further description; the description
is provided by the "except", and "e" is a perfectly reasonable, idiomatic,
pronoun for the caught exception.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Seebs
On 2010-10-21, Jean-Michel Pichavant  wrote:
> Let me quote the paper I linked in the previous post:
>
> list1 = []
> for x in theList:
> if x[0] == 4: 
> list1 += x;
> return list1
>
> compare it to:
>
> flaggedCells = []
> for cell in theBoard:
> if cell[STATUS_VALUE] == FLAGGED:
> flaggedCells += cell
> return flaggedCells   

The latter is better, but:

flagged = []
for cell in board:
if cell.flagged():
flagged += cell;

is probably even better.  (Here's where I love Ruby's idiom of
"flagged?" as a method name.)

The "Cells" suffix on flagged is questionable; I'd omit it in context because
the programmer knows we're working on cells.  The "the" prefix on "theBoard"
is actively harmful -- it communicates nothing and clutters.  Adding symbolic
words to the cell[0] == 4 test is a great idea, but it's been done
questionably:
1.  Did we just clutter the entire global namespace with "FLAGGED"
and "STATUS_VALUE"?  If not, what namespace are they in, that
we're able to use them unqualified?
2.  Why are we exposing that much of our interface in the first place?

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


embarrassing class question

2010-10-21 Thread Brendan
Two modules:
x.py:
class x(object):
pass

y.py:
from x import x
class y(x):
pass

Now from the python command line:
>>> import y
>>> dir(y)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'x', 'y']

I do not understand why class 'x' shows up here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Seebs
On 2010-10-21, Jean-Michel Pichavant  wrote:
> In the middle of thousand lines of code, when you are reviewing or 
> debugging, the later is better TMO, the point is that x, y, z = is only 
> easy to read during the assignement.

Bull.

> x, y, z = p.nextpoint()
> [snip a dozen of code line]
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> y += 1 # hmmm ??

Uh, no.

That is not confusing at all.  That is CLEAR AND TRANSPARENT.

> yCoordinate += 1

In the real world, this will take substantially longer for the reader
to comprehend.  You've just taken the important information (y), and
hidden it behind 10 times as much UNIMPORTANT information.  You're
forcing them to read 11 characters, 10 of which are just tagging,
and made it much easier for them to miss that the "y" here should have
been an "x", because the word is 90% correct anyway...

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Seebs
On 2010-10-21, Martin P. Hellwig  wrote:
> Although intuitively I would say the shorthand, however that is 
> depending on the context being me knowing at least the basics of 3d 
> spaces and having the pre-warning that you are going to mention 
> something with either coordinates or colours.

> Take away this pre-information, as you would when first reading an 
> application, and all of the sudden the latter would be much clearer to 
> the fellow programmer.

Would it really?  Would it stay clearer to the new programmer for more
than two or three minutes?

I don't think it would.  At worst, the new programmer has to look up
coordinates, once, and then we're back to the state where calling them
x, y, and z, or calling them r, g, and b, is MUCH easier on the new
guy.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.sendto / UDP problem

2010-10-21 Thread Todd Walter
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 17:03:58 +0100
MRAB  wrote:

> On 21/10/2010 15:57, Todd Walter wrote:
> > -BEGIN PGP SIGNED MESSAGE-
> > Hash: SHA1
> >
> > On Thu, 21 Oct 2010 00:07:58 +0100
> > MRAB  wrote:
> >
> >>>
> >> [snip]
> >>
> >> The docs for 'sendto' say:
> >>
> >>   """The socket should not be connected to a remote socket,
> >> since the destination socket is specified by address."""
> >>
> >> Could your problem be caused by you binding the socket to a source
> >> port, so it's going out both to the bound port _and_ the one given
> >> the binding?
> >>
> >> Have you tried using two sockets, one outgoing and the other
> >> incoming?
> >>
> >> BTW, your code for handling the response doesn't cope with it
> >> coming in a bit at a time. It loops discard any previous data from
> >> the previous iteration.
> >>
> >> Also, it's more Pythonic to say:
> >>
> >>   while '\r' not in response:
> >>   ...
> > I haven't bound the socket to a remote port, as I read it; it's
> > bound to a source port (192.168.10.2:2260, the local machine) and
> > just transmits to an address with a port glommed on
> > (192.168.10.1:2002, the PLC).
> [snip]
> What I meant was that you're using 'pcSocket' for both directions and
> using .bind on it.
> 
> Try creating two sockets, 'pcInSocket' and 'pcOutSocket', and bind
> only pcOutSocket.

Ah, I comprehend now.  Thanks!

- - Todd
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.16 (GNU/Linux)

iEYEARECAAYFAkzAb14ACgkQwnknPuQqPIOYEwCeNQNjGSQ/fwy2kLn862lY4fIk
OosAn0WplhDaFE3gVVmyLHrFwfwjfLFm
=j9fb
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Python has a "really hidden encapsulation"?

2010-10-21 Thread dmytro starosud
Hello,
I'm Python beginner (from Ukraine).
I may have found the way to really hide attributes in Python class.
The whole control on this attribute is implemented inside of the
class.
*(code is below, Python 3)
You see that we can't get the reference to instance of class
"en_property" outside the class "segment", but in the inside we can.

*It seems like there is no way to get the reference to field
“en_property.v_min” or “en_property.v_max”.
And object “s” has “two” attributes “v_min”: “s.__dict__['v_min']” and
“s.v_min”.

Help me find the answer, Can I change this hidden attribute outside
the class?
Or is it just an interesting feature?
...and Python has a "really hidden encapsulation"?

code:
class en_property(property):
   ptr_pget = None
   ptr_pset = None

   def pset(self, _class, value):
   self.ptr_pset(self, _class, value)

   def pget(self, _class):
   return self.ptr_pget(self, _class)

   def __init__(self, pget, pset):
   property.__init__(self, self.pget, self.pset)
   self.ptr_pget = pget
   self.ptr_pset = pset

class segment():
   def min_set(prop, self, p_min):
   if (self.v_max is not None) and (p_min > self.v_max):
   raise AttributeError('It must be: "min < max"')
   else:
   prop.v_min = p_min

   def min_get(prop, self):
   if 'v_min' in dir(prop):
   return prop.v_min

   def max_set(prop, self, p_max):
   if (self.v_min is not None) and (p_max < self.v_min):
   raise AttributeError('It must be: "min < max"')
   else:
   prop.v_max = p_max

   def max_get(prop, self):
   if 'v_max' in dir(prop):
   return prop.v_max

   v_min = en_property(min_get, min_set)
   del min_set, min_get
   v_max = en_property(max_get, max_set)
   del max_set, max_get


>>> s = segment()
>>> s.v_min = -1
>>> s.v_max = 1
>>> s.v_min = 2
Traceback (most recent call last):
 File "", line 1, in 
 File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 6, in pset
   self.ptr_pset(self, _class, value)
 File "D:\_dimka\I_Master\Programs_PyPg\enca.py", line 19, in min_set
   raise AttributeError('It must be: "min < max"')
AttributeError: It must be: "min < max"
>>> s.__dict__['v_min'] = 2
>>> s.__dict__['v_min']
2
>>> s.v_min
-1
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to scrutch a dict()

2010-10-21 Thread John Nagle

On 10/20/2010 9:32 PM, Phlip wrote:

Not Hyp:

def _scrunch(**dict):
 result = {}

 for key, value in dict.items():
 if value is not None:  result[key] = value

 return result

That says "throw away every item in a dict if the Value is None".

Are there any tighter or smarmier ways to do that?


Yes.

class nonnulldict(dict) :
def __setitem__(self, k, v) :
if not (v is None) :
   dict.__setitem__(self, k, v)

That creates a subclass of "dict" which ignores stores of None values.
So you never store the unwanted items at all.

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


Re: Python3: Is this a bug in urllib?

2010-10-21 Thread Johannes Bauer
Am 20.10.2010 14:32, schrieb Justin Ezequiel:
> On Oct 20, 12:47 am, Johannes Bauer  wrote:
>>
> from urllib import request; request.URLopener().open("http://google.de";)
>
> aren't you supposed to call read on the return value of open?
> i.e.,
> request.URLopener().open("http://google.de";).read()

If open blocks, a appended "read()" will never be executed. In order to
demonstrate the problem, I reduced the call to the least amount of code
needed to trigger it. Had I appended read(), it would not have been
clear if the read() actually hangs or the open(). The way I posted it,
it is clear.

Regards,
Johannes

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.sendto / UDP problem

2010-10-21 Thread MRAB

On 21/10/2010 15:57, Todd Walter wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 00:07:58 +0100
MRAB  wrote:




[snip]

The docs for 'sendto' say:

  """The socket should not be connected to a remote socket, since
the destination socket is specified by address."""

Could your problem be caused by you binding the socket to a source
port, so it's going out both to the bound port _and_ the one given the
binding?

Have you tried using two sockets, one outgoing and the other incoming?

BTW, your code for handling the response doesn't cope with it coming
in a bit at a time. It loops discard any previous data from the
previous iteration.

Also, it's more Pythonic to say:

  while '\r' not in response:
  ...

I haven't bound the socket to a remote port, as I read it; it's bound to
a source port (192.168.10.2:2260, the local machine) and just transmits
to an address with a port glommed on (192.168.10.1:2002, the PLC).

[snip]
What I meant was that you're using 'pcSocket' for both directions and
using .bind on it.

Try creating two sockets, 'pcInSocket' and 'pcOutSocket', and bind only
pcOutSocket.
--
http://mail.python.org/mailman/listinfo/python-list


Re: memory management - avoid swapping/paging

2010-10-21 Thread Nobody
On Thu, 21 Oct 2010 02:34:15 -0700, Jon Clements wrote:

> I'm after something that says: "I want 512mb of physical RAM, I don't
> want you to page/swap it, if you can't do that, don't bother at all".
> Now I'm guessing, that an OS might be able to grant that, but later on
> have to kill the process as other higher-priority processes need RAM

The mlock() system call locks a region of virtual memory into physical
memory. AFAICT, Python doesn't provide an interface, but you can use
ctypes for that.

In Linux 2.6.9 and later, the ability to lock memory is controlled via
resource limits (see "man 2 setrlimit", "help ulimit" and "man 5
limits.conf"). Earlier versions limit memory locking to processes owned by
root or with the CAP_IPC_LOCK capability.

Also, locking a specific region of memory won't necessarily help if the
program code and stack are subject to paging/swapping. You can use
mlockall() to lock all memory for a process.

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Neil Cerutti
On 2010-10-21, Jean-Michel Pichavant  wrote:
> So If I get you right, because comments can lie, we should stop
> using comments?

No, but use comment judiciously. Kernighan and Pike (_The
Practice of Programming_) recommend writing your code to require
as little comment as possible. They provide typical examples of
useful and of harmful comments.

> While I totally understand why some ppl prefer to use short
> names, I really don't see the point in saying that because any
> information can be wrong, we should stop giving any.

Don't go that far. Applicable is Strunk's characteristic
admonition from _Elements of Style_: "Omit needless words! Omit
needless words! Omit needless words!" We should strive for a
balance between clarity and brevity. A useful comment, for
example one which  provides references to documents on the
algorithm implemented in your module, should be included.
Beginner mistakes like, "define a class to model birds," and, "#
increment the total," are worse than empty space.

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


Re: Filename for stdout

2010-10-21 Thread Nobody
Richard Gibbs  wrote:

> If my python script is called with stdout (or stdin or stderr)
> redirected to a file, how can I find the filename under Linux?  Under
> Windows?

On Linux, you can read the /proc/self/fd/* symlinks, e.g.:

stdin_filename = os.readlink('/proc/self/fd/0')

This isn't portable, and won't always work, e.g. stdin may not be
associated with a file, the file may have been deleted, or /proc may not
be mounted.

If /proc isn't mounted, you can achieve the same result albeit with a lot
more effort by using os.fstat(0) to determine the device and inode
number then searching the filesystem (with e.g. os.walk or the "find"
utility) for a match (if one exists).

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Jean-Michel Pichavant

Mel wrote:

Steven D'Aprano wrote:

  

On Thu, 21 Oct 2010 12:49:47 +, Neil Cerutti wrote:



_The Practice of Programming_ has this right. In general the bigger the
scope of a variable, the longer and more descriptive should be its name.
In a small scope, a big name is mostly noise.
  

Thank you! The scope of the variable is an important factor.



Wittgenstein remarked somewhere* "...it is the particular use of a word only 
which gives the word its meaning...".  For a variable, if you can see the 
entire use at a glance, then any other cues to its meaning, like a long 
variable name, are redundant.


Long variable names can lie; they share this ability with comments.  The one 
study** I've seen of newbie errors observed the #1 error being as assumption 
that descriptive variable names could somehow replace computation, e.g. that 
if you called a variable "total_sales", then accessing it would get you a 
sales total, regardless of what you might or might not write as 
computational statements.


Mel.

  


So If I get you right, because comments can lie, we should stop using 
comments ?
Computation never lies ? Well that's called a bug, and they are your 
every day worries.


Meaningfull names helps spotting miscomputation.

total_sales = some_computation()
How are you supposed to verify that some_computation is filling its role 
without even knowing what it is supposed to do ?


While I totally understand why some ppl prefer to use short names, I 
really don't see the point in saying that because any information can be 
wrong, we should stop giving any.


JM


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


Re: socket.sendto / UDP problem

2010-10-21 Thread Todd Walter
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On Thu, 21 Oct 2010 00:07:58 +0100
MRAB  wrote:

> >
> [snip]
> 
> The docs for 'sendto' say:
> 
>  """The socket should not be connected to a remote socket, since
> the destination socket is specified by address."""
> 
> Could your problem be caused by you binding the socket to a source
> port, so it's going out both to the bound port _and_ the one given the
> binding?
> 
> Have you tried using two sockets, one outgoing and the other incoming?
> 
> BTW, your code for handling the response doesn't cope with it coming
> in a bit at a time. It loops discard any previous data from the
> previous iteration.
> 
> Also, it's more Pythonic to say:
> 
>  while '\r' not in response:
>  ...
I haven't bound the socket to a remote port, as I read it; it's bound to
a source port (192.168.10.2:2260, the local machine) and just transmits
to an address with a port glommed on (192.168.10.1:2002, the PLC). 
Unfortunately I cannot alter the PLC's logic; it was provided by the
vendor without source (and I'm not entirely sure i have the appropriate
software to deal with it anyway as we're an Omron/A-B shop).  I based
this code on the actual conversation on the wire from the utility GUI
that came with the storage unit. It ping pongs back and forth on just
those two ports, likely because the old controller used a RS232
half-duplex interface. That being said, I don't know for a fact that the
PLC cares about the source port -- they are usually pretty "dumb" and
only care about the input but you never know what's been hard-coded.  I
will have to test this.  

I am primarily interested in the '\r'; it serves as the EOT (ie.,
'over' not 'out')  I know the response packet size is fixed and it only
gets sent once in full.  No re-transmission or fragmentation (this is
likely by design - full stack isn't really necessary on this kind of
PLC.)  

I'll change my loops to be more pythonic; it reads better.

Thanks for your help,

- - Todd
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.16 (GNU/Linux)

iEYEARECAAYFAkzAVPAACgkQwnknPuQqPIPevgCdGHTXUiJLvyVOgcV12weBRDuV
h0AAn0spYoMaxSuyoQi0EwEKXIk+rG20
=sgL9
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pythagorean triples exercise

2010-10-21 Thread Jeffrey Gaynor
What you want is to realize that all integer Pythagorean triples can be 
generated by a pair of integers, (i,j), j < i. The values are just (* = 
multiply, ^ = exponentiation)

a = 2*i*j
b = i^2 - j^2
c = i^2 + j^2 (hypotenuse)

So yes indeed a^2 + b^2 = c^2. This is a very ancient result, btw and used to 
be taught in public schools until recently. 

So the programming problem is to sort through these and toss out all triangles 
for which the short side (a or b, it will vary) is less than or equal to n. Or 
you could be Math-y  and use an inequality argument to find when a or b is the 
short side (bit of work).

Hope this helps...

- Original Message -
From: "Baba" 
To: python-list@python.org
Sent: Thursday, October 21, 2010 5:51:07 AM
Subject: pythagorean triples exercise

Hi everyone

i need a hint regarding the following exercise question:

"Write a program that generates all Pythagorean triples whose small
sides are no larger than n.
Try it with n <= 200."


what is "n" ? i am guessing that it is a way to give a bound to the
triples to be returned but i can't figure out where to fit in "n".

a^a + b^b = c^c is the condition to satisfy and i need to use loops
and "n" will be an upper limit of one (or more?) of the loops but i am
a bit lost. Please help me get thinking about this right.

exercise source: Java by Dissection (Ira Pohl and Charlie McDowell)

thanks

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

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Mel
Steven D'Aprano wrote:

> On Thu, 21 Oct 2010 12:49:47 +, Neil Cerutti wrote:
> 
>> _The Practice of Programming_ has this right. In general the bigger the
>> scope of a variable, the longer and more descriptive should be its name.
>> In a small scope, a big name is mostly noise.
> 
> Thank you! The scope of the variable is an important factor.

Wittgenstein remarked somewhere* "...it is the particular use of a word only 
which gives the word its meaning...".  For a variable, if you can see the 
entire use at a glance, then any other cues to its meaning, like a long 
variable name, are redundant.

Long variable names can lie; they share this ability with comments.  The one 
study** I've seen of newbie errors observed the #1 error being as assumption 
that descriptive variable names could somehow replace computation, e.g. that 
if you called a variable "total_sales", then accessing it would get you a 
sales total, regardless of what you might or might not write as 
computational statements.

Mel.

* "somewhere" hah! I covertly looked it up.  It's in the _Blue and Brown 
Books_.

** This I haven't looked up.  It got some publicity a year or so ago.  It 
started when somebody gave a mid-term computer science test to a class who 
had only just started the course.  Then they studied the results to find out 
what the students might have been thinking.

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


Re: how to scrutch a dict()

2010-10-21 Thread Hrvoje Niksic
Joost Molenaar  writes:

> Using a 2.7/3.x dictionary comprehension, since you don't seem to mind
> creating a new dictionary:
>
> def _scrunched(d):
>     return { key: value for (key, value) in d.items() if value is not None }

Note that a dict comprehension, while convenient, is not necessary for
this to be formulated as a single expression:

def _scrunched(d):
return dict((key, value) for (key, value) in d.items() if value is not None)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Jean-Michel Pichavant



You
won't be that happy everyone wrote their mail in this list like a mobile
text message, if u c what I mean.



I never suggested that. What I am trying to get across is that long names 
are not automatically better than short names, and even one letter names 
can be as good or better than long names *when appropriate*.



  


You misunderstood my point, I'm not pro long names, I'm pro descriptive 
names, It can be short if descriptive:


for o, c in cars:
   park(o)
   phone(c)

for owner, car in cars: # by just using meaningful names you give the 
info to the reader that you expect cars to be a list of tuple (owner, car)

   park(owner)
   phone(car) # see how it is easier to spot bug


JM




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


Python script executable

2010-10-21 Thread kostia
Hi all,

I'm working with glite grid middleware. This is the server-side
program which allows to calculate exe or sh files using languages like
python, c++ and so on.

No matter, my question is following: I need to make my python script
executable to be able to run it under the glite. I have found this
article 
http://effbot.org/pyfaq/how-do-i-make-a-python-script-executable-on-unix.htm,
but it did not help me. Also I know about py2exe program, but it is
only available in Windows.

Can anyone help me? It will be very nice, if you know what is glite
and jdl file, so you can give me an example.

Be happy! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Has Next in Python Iterators

2010-10-21 Thread Paul Rudin
Kelson Zawack  writes:

> Since an iterator having an end is not actually an exceptional case...

There's no requirement on iterators to be finite, so in a sense it is.

In general it may be impractical to know whether an iterator has reached
the end without calling next().


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


Re: how to scrutch a dict()

2010-10-21 Thread Phlip
> for k in [k for k, v in d.items() if v is None]:
>   del d[k]

Tx everyone!

And I forgot about shadowing dict(), I forgot about del d[k], and I
didn't know Python had "dict comprehensions" yet.

Anyway this one might become the winner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Steven D'Aprano
On Thu, 21 Oct 2010 11:27:57 +0200, Jean-Michel Pichavant wrote:


> There is another important point: the time where code size matters is
> over. 

That's ridiculous. Which would you rather write?


import os
if os.path.exists("myfile"):
print open("myfile").read()


or this?

import the module called "os";
get the attribute named "exists" of the attribute named "path" of the 
module called "os";
if it returns a true value when called with argument "myfile":
get the function called "open" and call it with argument "myfile";
get the attribute called "read" of it;
print the result to standard output;


Even by the standards of Apple's (much missed) Hypertalk, that's overly 
verbose! Even Hypertalk compromised on perfect English grammar for 
brevity and conciseness.


> You
> won't be that happy everyone wrote their mail in this list like a mobile
> text message, if u c what I mean.

I never suggested that. What I am trying to get across is that long names 
are not automatically better than short names, and even one letter names 
can be as good or better than long names *when appropriate*.



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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Steven D'Aprano
On Thu, 21 Oct 2010 12:49:47 +, Neil Cerutti wrote:

> _The Practice of Programming_ has this right. In general the bigger the
> scope of a variable, the longer and more descriptive should be its name.
> In a small scope, a big name is mostly noise.

Thank you! The scope of the variable is an important factor.

+1

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Steven D'Aprano
On Thu, 21 Oct 2010 11:37:36 +0200, Jean-Michel Pichavant wrote:

> In the middle of thousand lines of code, 

If you have a function that is a thousand lines of code long, I don't 
care what you name the variables, you won't be able to keep it straight 
in your head.

This is one of the reasons why we break code up into functions -- so you 
don't have to remember 1000 lines worth of variables names all at once.


> when you are reviewing or
> debugging, the later is better TMO, the point is that x, y, z = is only
> easy to read during the assignement. Consider this:
> 
> x, y, z = p.nextpoint()
> [snip a dozen of code line]
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> y += 1 # hmmm ??

A dozen lines isn't much. They will all fit on the screen at once.

Honestly, you guys are talking about variable names as if the average 
coder was a moron barely more intelligent than a pigeon. Seriously, even 
*goldfish* have better memory than that -- they can remember events for 
many minutes at a time. That's the fatal flaw in your argument... if you 
don't credit the average programmer with being able to remember that y is 
an ordinate of a point after just twelve lines, what makes you think he 
can remember that "yCoordinate" is the *second* item in the tuple, rather 
than the first, or third, or twenty-first?

If coders were really as dim-witted as you seem to believe, you would 
have to write:

firstItemOfPointCoordinates, secondItemOfPointCoordinates, \
  thirdItemOfPointCoordinates = polygon. \
  methodReturningNextPoint3ItemCoordinate()

Whew.


I find it ironic that after complaining about single character variable 
names, you sign your post with your initials "JM" instead of "Jean-Michel 
Pichavant".



By the way:

> xCoordinate, yCoordinate, zCoordinate = polygon.nextPointCoordinates()

Coordinates are pairs or triples of *ordinates* (no "co"). You can't have 
an "x coordinate" -- that would be like unpacking a single pair of shoes 
into a "left-pair" and a "right-pair".



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


Re: Unicode questions

2010-10-21 Thread OdarR
On Oct 19, 9:02 pm, Tobiah  wrote:
> I've been reading about the Unicode today.
> I'm only vaguely understanding what it is
> and how it works.
>
...
> Thanks,
>
> Tobiah

Hi,

A good advice,
read this presentation,
http://farmdev.com/talks/unicode/
Explanation and advices for coding.

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Neil Cerutti
On 2010-10-21, Jean-Michel Pichavant  wrote:
> In the middle of thousand lines of code, when you are reviewing
> or debugging, the later is better TMO, the point is that x, y,
> z = is only easy to read during the assignement. Consider this:
>
> x, y, z = p.nextpoint()
> [snip a dozen of code line]
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> y += 1 # hmmm ??
>
> vs
>
> xCoordinate, yCoordinate, zCoordinate = polygon.nextPointCoordinates()
> [snip a dozen of code line]
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> ...
> yCoordinate += 1

_The Practice of Programming_ has this right. In general the
bigger the scope of a variable, the longer and more descriptive
should be its name. In a small scope, a big name is mostly noise.

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


Re: how to scrutch a dict()

2010-10-21 Thread Neil Cerutti
On 2010-10-21, James Mills  wrote:
> Rather than creating a new dict why don't you just do:
>
> def _scrunch(d):
>for k, v in d.items():
>   if v is None:
>  del d[k]

In Python 3, where items returns an iterator, modifying the
dictionary in this way may lead to cirrhossis of the dictionary.
Here's another idea:

for k in [k for k, v in d.items() if v is None]:
  del d[k]

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


Re: how to scrutch a dict()

2010-10-21 Thread Joost Molenaar
Using a 2.7/3.x dictionary comprehension, since you don't seem to mind
creating a new dictionary:

def _scrunched(d):
    return { key: value for (key, value) in d.items() if value is not None }

Joost

On 21 October 2010 06:32, Phlip  wrote:
>
> Not Hyp:
>
> def _scrunch(**dict):
>    result = {}
>
>    for key, value in dict.items():
>        if value is not None:  result[key] = value
>
>    return result
>
> That says "throw away every item in a dict if the Value is None".
>
> Are there any tighter or smarmier ways to do that? Python does so
> often manage maps better than that...
>
> --
>  Phlip
>  http://zeekland.zeroplayer.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Has Next in Python Iterators

2010-10-21 Thread Steven D'Aprano
On Thu, 21 Oct 2010 19:08:00 +0800, Kelson Zawack wrote:

> I have been programing in python for a while now and by in large love
> it.  One thing I don't love though is that as far as I know iterators
> have no has_next type functionality.  As a result if I want to iterate
> until an element that might or might not be present is found I either
> wrap the while loop in a try block or break out of a for loop.

Yes, they are two solutions to the problem. You could also look at 
takewhile and dropWhile from the itertools module.


> Since an
> iterator having an end is not actually an exceptional case 

But it is. An iterator is supposed to yield items. That's what they're 
for. When there are no more items, that's an exceptional change of state.

> and the for
> construct is really for iterating though the entirety of a list

Nonsense. That's why Python has continue and break statements, so you can 
break out of for loops early. But if you don't like break, you could 
always use a while loop.


> both of
> these solutions feel like greasy workarounds and thus not very pythonic.

I can't help how they feel to you, but I assure you they are perfectly 
Pythonic.


>  Is there something I am missing?  Is there a reason python iterators
> don't have has_next functionality?  

Yes. What you ask for is impossible to implement for generic iterators. 
Not hard. Not inconvenient. Impossible.

Of course you can implement it yourself in your own iterators:


class LookAheadIterator:
def __init__(self, n):
self.n = n
def next(self):
if self._n < 0:  raise StopIteration
self._n -= 1
return self._n + 1
def __iter__(self):
return self
def hasNext(self):
return self._n >= 0


but there's no general solution that will work for arbitrary iterators.


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


Re: memory management - avoid swapping/paging

2010-10-21 Thread Alain Ketterlin
Jon Clements  writes:

> Is there a cross-platform way using Python to guarantee that an object
> will never be swapped/paged to disk? I'll be honest and say I'm really
> not sure if this is a particular language question or rather specific
> to an OS.
> 
> Under linux it appears I could create a ramfs and mmap a file under
> that. Is there a way to do the above with mmap?

It's called mlock()

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


Re: Has Next in Python Iterators

2010-10-21 Thread Steven D'Aprano
On Thu, 21 Oct 2010 09:36:41 -0200, Felipe Bastos Nunes wrote:

> Looking in the documentation, only the StopIteration raises. I'd like a
> hasNext() too. I'll see if it is easy to implement,


Iterators can be unpredictable. In general, you can't tell whether an 
iterator is finished or not until you actually try it. Consider the 
following example:

def rand():
x = random.random()
while x < 0.5:
yield x

it = rand()


What should it.hasNext() return?

I know what you're thinking: "it's easy to cache the next result, and 
return it on the next call". But iterators can also be dependent on the 
time that they are called, like in this example:

def evening_time():
while 1:
yield time.strftime("%H:%m")  # e.g. "23:20"


it = time_of_day()  # it's 23:59
if it.hasNext(): # Returns True
time.sleep(180)  # Do some other processing for three minutes
print it.next()  # time is now 00:02, but iterator says it's 23:59



Of course, caching the result of an iterator can work for *some* 
iterators. But it's not a general solution suitable for all iterators. 
There is no general solution.



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


Re: pythagorean triples exercise

2010-10-21 Thread Alex Hall
On 10/21/10, Baba  wrote:
> Hi everyone
>
> i need a hint regarding the following exercise question:
>
> "Write a program that generates all Pythagorean triples whose small
> sides are no larger than n.
> Try it with n <= 200."
>
> what is "n" ? i am guessing that it is a way to give a bound to the
> triples to be returned but i can't figure out where to fit in "n".
Picture a right triangle. The two short sides (the two sides coming
off either side of the right angle) must be no longer than n. The
lengths of these two sides are a and b, and you are looping until
either side exceeds n... HTH.
>
> a^a + b^b = c^c is the condition to satisfy and i need to use loops
> and "n" will be an upper limit of one (or more?) of the loops but i am
> a bit lost. Please help me get thinking about this right.
>
> import math
> for b in range(20):
> for a in range(1, b):
> c = math.sqrt( a * a + b * b)
> if c % 1 == 0:
> print (a, b, int(c))
>
> this returns
>
> (3, 4, 5) (6, 8, 10) (5, 12, 13) (9, 12, 15) (8, 15, 17) (12, 16, 20)
>
> is that the desired output? what is the step that i'm missing?
>
> thanks in advance
>
> Baba
> p.s. this is not homework but self-study
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Has Next in Python Iterators

2010-10-21 Thread Ben Finney
Kelson Zawack  writes:


> […] if I want to iterate until an element that might or might not be
> present is found I either wrap the while loop in a try block or break
> out of a for loop.

I'm not sure what exception you would catch, but that could be a good
solution.

The general solution would be to break from the ‘for’ loop when you find
the terminating item.

> Since an iterator having an end is not actually an exceptional case

Right. You're not talking about the end of the iterator, though; you're
talking about stopping *before* the end, when a particular item is
reached.

Either that, or you'll need to be clearer about what the problem is.
A simple, complete, working example would help.

> and the for construct is really for iterating though the entirety of a
> list

Or until something else happens to change the flow, such as a ‘break’
statement.

> both of these solutions feel like greasy workarounds and thus not
> very pythonic.

Show us a simple, complete, working example, and let's see how Pythonic
it looks.

> Is there something I am missing? Is there a reason python iterators
> don't have has_next functionality?

Many iterators can't know whether they have a next item without actually
generating that item.

> What is the standard solution to this problem?

I'm not sure that it is a problem. Let's see the example, to make it
more concrete.

-- 
 \   “We must respect the other fellow's religion, but only in the |
  `\   sense and to the extent that we respect his theory that his |
_o__) wife is beautiful and his children smart.” —Henry L. Mencken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Has Next in Python Iterators

2010-10-21 Thread Felipe Bastos Nunes
Looking in the documentation, only the StopIteration raises. I'd like
a hasNext() too. I'll see if it is easy to implement, but maybe it'sn
ot yet there coz for does the work greatly.

2010/10/21, Kelson Zawack :
> I have been programing in python for a while now and by in large love
> it.  One thing I don't love though is that as far as I know iterators
> have no has_next type functionality.  As a result if I want to iterate
> until an element that might or might not be present is found I either
> wrap the while loop in a try block or break out of a for loop.  Since an
> iterator having an end is not actually an exceptional case and the for
> construct is really for iterating though the entirety of a list both of
> these solutions feel like greasy workarounds and thus not very
> pythonic.  Is there something I am missing?  Is there a reason python
> iterators don't have has_next functionality?  What is the standard
> solution to this problem?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Felipe Bastos Nunes
-- 
http://mail.python.org/mailman/listinfo/python-list


Has Next in Python Iterators

2010-10-21 Thread Kelson Zawack
I have been programing in python for a while now and by in large love 
it.  One thing I don't love though is that as far as I know iterators 
have no has_next type functionality.  As a result if I want to iterate 
until an element that might or might not be present is found I either 
wrap the while loop in a try block or break out of a for loop.  Since an 
iterator having an end is not actually an exceptional case and the for 
construct is really for iterating though the entirety of a list both of 
these solutions feel like greasy workarounds and thus not very 
pythonic.  Is there something I am missing?  Is there a reason python 
iterators don't have has_next functionality?  What is the standard 
solution to this problem?


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


pythagorean triples exercise

2010-10-21 Thread Baba
Hi everyone

i need a hint regarding the following exercise question:

"Write a program that generates all Pythagorean triples whose small
sides are no larger than n.
Try it with n <= 200."

what is "n" ? i am guessing that it is a way to give a bound to the
triples to be returned but i can't figure out where to fit in "n".

a^a + b^b = c^c is the condition to satisfy and i need to use loops
and "n" will be an upper limit of one (or more?) of the loops but i am
a bit lost. Please help me get thinking about this right.

import math
for b in range(20):
for a in range(1, b):
c = math.sqrt( a * a + b * b)
if c % 1 == 0:
print (a, b, int(c))

this returns

(3, 4, 5) (6, 8, 10) (5, 12, 13) (9, 12, 15) (8, 15, 17) (12, 16, 20)

is that the desired output? what is the step that i'm missing?

thanks in advance

Baba
p.s. this is not homework but self-study
-- 
http://mail.python.org/mailman/listinfo/python-list


pythagorean triples exercise

2010-10-21 Thread Baba
Hi everyone

i need a hint regarding the following exercise question:

"Write a program that generates all Pythagorean triples whose small
sides are no larger than n.
Try it with n <= 200."


what is "n" ? i am guessing that it is a way to give a bound to the
triples to be returned but i can't figure out where to fit in "n".

a^a + b^b = c^c is the condition to satisfy and i need to use loops
and "n" will be an upper limit of one (or more?) of the loops but i am
a bit lost. Please help me get thinking about this right.

exercise source: Java by Dissection (Ira Pohl and Charlie McDowell)

thanks

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


Re: how to scrutch a dict()

2010-10-21 Thread John Pinner
On Oct 21, 5:40 am, Paul Rubin  wrote:
> Phlip  writes:
> > def _scrunch(**dict):
> >     result = {}
>
> >     for key, value in dict.items():
> >         if value is not None:  result[key] = value
>
> >     return result
>
> > That says "throw away every item in a dict if the Value is None".
> > Are there any tighter or smarmier ways to do that? Python does so
> > often manage maps better than that...

As James has suggested, you can 'clean the dict in place (as it's
mutable), you don't have to return a whole new object.

> Untested:
>
> def _scrunch(**kwargs):
>    return dict(k,v for k,v in kwargs.iteritems() if v is not None)
>
> Note: it's best not to use "dict" as a parameter name,

Yes, likewise with any other builtin; if you use pychecker and/or
pylint routinely, they would warn you about this.

> since it is a
> built in function (dictionary constructor).

I don't think so:

>>> type(dict)

>>>

So you're not running a function, but creating an instance of a dict.

Best wishes,

John
--

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


Re: The 'n' format specifier

2010-10-21 Thread Peter Otten
Boštjan Mejak wrote:

> The locale.setlocale(category=locale.LC_NUMERIC, locale="Slovenian") 
> works like a charm in my application. Now the 'n format specifier works as
> I want. But tell me whether the 'n' forma specifier can be forced to round
> the float to just one decimal place. I know that the 'f' format specifier
> does that by specifying ".1f", but 'f' is not locale-aware. I have set the
> 'n' format specifier in my application like ".3n", which is okay if the
> returned number is two integers and one decimal, but is not okay if the
> returned number is one integer and two decimals, because I want just one
> decimal, always. How can I make that by using the 'n' format specifier?

Looks like you have to resort to:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'de_DE.UTF-8'
>>> locale.format("%.1f", 12345.6789, grouping=True)
'12.345,7'


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


Re: OO and game design questions

2010-10-21 Thread Jonathan Hartley
On Oct 20, 12:11 pm, dex  wrote:
> On Oct 20, 12:25 pm, Jonathan Hartley  wrote:
>
>
>
> > On Oct 18, 8:28 am, dex  wrote:
>
> > > I'm building a turn based RPG game as a hobby. The design is becoming
> > > increasingly complicated and confusing, and I think I may have
> > > tendency to over-engineer simple things. Can anybody please check my
> > > problems-solutions and point me to more elegant solution?
>
> > > Every item/character/room is a separate object. Items/characters need
> > > to have references to room they are in, and room needs to have a list
> > > of references to items/characters that are contained within. I decided
> > > to use weak references. That way I can destroy object by deleting it,
> > > I don't have to destroy all references as well. In each object's
> > > __init__() that object is added to game_object list, and in each
> > > __del__() they are removed from game_object list. This mechanism keeps
> > > them safe from garbage collector. How pythonic is this design?
>
> > > In turn-based games, the order of action execution in battle can give
> > > unfair advantage to players. For example, if player's arm is crippled
> > > before his action is executed, he would do less damage. To offset
> > > this, I first execute all players' actions and calculate effects in
> > > first pass, then apply the effects in second pass. The effect can be
> > > health decrease by 15HP, item pick-up, 30p experience gain, etc. This
> > > means the player deals the same amount of damage no matter what
> > > happens to him in that turn. The difficult part is keeping track of
> > > various effects. I had to make separate class for various types of
> > > effects (ChangeAttributeEffect, GetItemEffect, LooseItemEffect). Each
> > > class stores weak reference to target object and has apply() method
> > > that applies the effect to object. I'm not satisfied with this as it's
> > > limiting, error-prone and uses metaprogramming. Is there a design
> > > pattern that would remember changes to an object, and apply them
> > > later?
>
> > > Sorry for the wall of text.
>
> > One common way to store delayed actions is as a lambda (an anonymous
> > function.) A lambda defines a new function:
>
> > , and you can call this function later. The created function has no
> > name, (but you can assign it to a variable to give it a name if you
> > like) and can be called later:
>
> > So in the game, you could have a collection 'effects', each one will
> > be a lambda:
>
> >   effects = []
>
> > At the start of the round, as each entity makes its moves, they add
> > lambdas to this collection.
>
> >   effects.append(
> >       lambda: decrease_hp(monster_a, 4)
> >   )
> >   effects.append(
> >       lambda: lose_item(monster_a, item_b)
> >   )
>
> > Instead of appending it directly like this, I imagine the lambdas
> > could be returned by the monster's 'act' or 'update' method:
>
> >   class Monster():
> >     def act(self):
> >       # blah and finally
> >       return lambda: decrease_hp(monster_a, 4)
>
> > Then for the start of a round, first you ask each monster what action
> > it is going to perform:
>
> >   for monster in room.monsters:
> >       effects.append(
> >           monster.act()
> >       )
>
> > Then for the end of the round, call all the lambdas
>
> >   for effect in effects:
> >       effect()
>
> Mr. Roy Smith already proposed using closures. I already did a similar
> thing in my code, but instead of decrease_hp() I have AttributeEffect
> class which is able to modify any attribute (in old RPGs some monsters
> could drain your intelligence, in my game laser gun hit will decrease
> HP as well as armor integrity). The first version looks like this
> (missing few checks):
>
> class AttributeEffect(object):
>     '''Effect changes object's attribute by delta'''
>     def __init__(self, obj, attrib, delta):
>         self.obj = obj               # reference to object the effect
> applies to
>         self.attrib = attrib         # name of attribute that effect
> applies to
>         self.delta = delta           # change of value for
> object.attribute
>     def apply(self):
>         value = getattr(self.obj, self.attrib) # todo: try, except
>         value += self.delta
>         setattr(self.obj(), self.attrib, value)
>
> Yesterday I learned that Python 3.0 introduces nonlocal keyword which
> would simplify defining effect functions and passing them along. Nice
> improvement.


Very cool, that looks like it would work. The thing I like about the
lambda idea though, is that you don't have to write any classes like
AttributeEffect, (and presumably other such classes, like
LoseItemEffect, etc.) Instead of *modelling* the different kind of
effects that could happen, you just write code that *performs* the
desired effect. (e.g. monster.hp -= damage) To my eyes, lambda's are
therefore more flexible and require less code. But I could be wrong,
and obviously you should do what you think is best for your
circumstances. Very

Re: OO and game design questions

2010-10-21 Thread Jonathan Hartley
On Oct 20, 12:11 pm, dex  wrote:
> On Oct 20, 12:25 pm, Jonathan Hartley  wrote:
>
>
>
> > On Oct 18, 8:28 am, dex  wrote:
>
> > > I'm building a turn based RPG game as a hobby. The design is becoming
> > > increasingly complicated and confusing, and I think I may have
> > > tendency to over-engineer simple things. Can anybody please check my
> > > problems-solutions and point me to more elegant solution?
>
> > > Every item/character/room is a separate object. Items/characters need
> > > to have references to room they are in, and room needs to have a list
> > > of references to items/characters that are contained within. I decided
> > > to use weak references. That way I can destroy object by deleting it,
> > > I don't have to destroy all references as well. In each object's
> > > __init__() that object is added to game_object list, and in each
> > > __del__() they are removed from game_object list. This mechanism keeps
> > > them safe from garbage collector. How pythonic is this design?
>
> > > In turn-based games, the order of action execution in battle can give
> > > unfair advantage to players. For example, if player's arm is crippled
> > > before his action is executed, he would do less damage. To offset
> > > this, I first execute all players' actions and calculate effects in
> > > first pass, then apply the effects in second pass. The effect can be
> > > health decrease by 15HP, item pick-up, 30p experience gain, etc. This
> > > means the player deals the same amount of damage no matter what
> > > happens to him in that turn. The difficult part is keeping track of
> > > various effects. I had to make separate class for various types of
> > > effects (ChangeAttributeEffect, GetItemEffect, LooseItemEffect). Each
> > > class stores weak reference to target object and has apply() method
> > > that applies the effect to object. I'm not satisfied with this as it's
> > > limiting, error-prone and uses metaprogramming. Is there a design
> > > pattern that would remember changes to an object, and apply them
> > > later?
>
> > > Sorry for the wall of text.
>
> > One common way to store delayed actions is as a lambda (an anonymous
> > function.) A lambda defines a new function:
>
> > , and you can call this function later. The created function has no
> > name, (but you can assign it to a variable to give it a name if you
> > like) and can be called later:
>
> > So in the game, you could have a collection 'effects', each one will
> > be a lambda:
>
> >   effects = []
>
> > At the start of the round, as each entity makes its moves, they add
> > lambdas to this collection.
>
> >   effects.append(
> >       lambda: decrease_hp(monster_a, 4)
> >   )
> >   effects.append(
> >       lambda: lose_item(monster_a, item_b)
> >   )
>
> > Instead of appending it directly like this, I imagine the lambdas
> > could be returned by the monster's 'act' or 'update' method:
>
> >   class Monster():
> >     def act(self):
> >       # blah and finally
> >       return lambda: decrease_hp(monster_a, 4)
>
> > Then for the start of a round, first you ask each monster what action
> > it is going to perform:
>
> >   for monster in room.monsters:
> >       effects.append(
> >           monster.act()
> >       )
>
> > Then for the end of the round, call all the lambdas
>
> >   for effect in effects:
> >       effect()
>
> Mr. Roy Smith already proposed using closures. I already did a similar
> thing in my code, but instead of decrease_hp() I have AttributeEffect
> class which is able to modify any attribute (in old RPGs some monsters
> could drain your intelligence, in my game laser gun hit will decrease
> HP as well as armor integrity). The first version looks like this
> (missing few checks):
>
> class AttributeEffect(object):
>     '''Effect changes object's attribute by delta'''
>     def __init__(self, obj, attrib, delta):
>         self.obj = obj               # reference to object the effect
> applies to
>         self.attrib = attrib         # name of attribute that effect
> applies to
>         self.delta = delta           # change of value for
> object.attribute
>     def apply(self):
>         value = getattr(self.obj, self.attrib) # todo: try, except
>         value += self.delta
>         setattr(self.obj(), self.attrib, value)
>
> Yesterday I learned that Python 3.0 introduces nonlocal keyword which
> would simplify defining effect functions and passing them along. Nice
> improvement.


Very cool, that looks like it would work. The thing I like about the
lambda idea though, is that you don't have to write any classes like
AttributeEffect, (and presumably other such classes, like
LoseItemEffect, etc.) Instead of *modelling* the different kind of
effects that could happen, you just write code that *performs* the
desired effect. (e.g. monster.hp -= damage) To my eyes, lambda's are
therefore more flexible and require less code. But I could be wrong,
and obviously you should do what you think is best for your
circumstances. Very

Re: OO and game design questions

2010-10-21 Thread Jonathan Hartley
On Oct 20, 12:11 pm, dex  wrote:
> On Oct 20, 12:25 pm, Jonathan Hartley  wrote:
>
>
>
> > On Oct 18, 8:28 am, dex  wrote:
>
> > > I'm building a turn based RPG game as a hobby. The design is becoming
> > > increasingly complicated and confusing, and I think I may have
> > > tendency to over-engineer simple things. Can anybody please check my
> > > problems-solutions and point me to more elegant solution?
>
> > > Every item/character/room is a separate object. Items/characters need
> > > to have references to room they are in, and room needs to have a list
> > > of references to items/characters that are contained within. I decided
> > > to use weak references. That way I can destroy object by deleting it,
> > > I don't have to destroy all references as well. In each object's
> > > __init__() that object is added to game_object list, and in each
> > > __del__() they are removed from game_object list. This mechanism keeps
> > > them safe from garbage collector. How pythonic is this design?
>
> > > In turn-based games, the order of action execution in battle can give
> > > unfair advantage to players. For example, if player's arm is crippled
> > > before his action is executed, he would do less damage. To offset
> > > this, I first execute all players' actions and calculate effects in
> > > first pass, then apply the effects in second pass. The effect can be
> > > health decrease by 15HP, item pick-up, 30p experience gain, etc. This
> > > means the player deals the same amount of damage no matter what
> > > happens to him in that turn. The difficult part is keeping track of
> > > various effects. I had to make separate class for various types of
> > > effects (ChangeAttributeEffect, GetItemEffect, LooseItemEffect). Each
> > > class stores weak reference to target object and has apply() method
> > > that applies the effect to object. I'm not satisfied with this as it's
> > > limiting, error-prone and uses metaprogramming. Is there a design
> > > pattern that would remember changes to an object, and apply them
> > > later?
>
> > > Sorry for the wall of text.
>
> > One common way to store delayed actions is as a lambda (an anonymous
> > function.) A lambda defines a new function:
>
> > , and you can call this function later. The created function has no
> > name, (but you can assign it to a variable to give it a name if you
> > like) and can be called later:
>
> > So in the game, you could have a collection 'effects', each one will
> > be a lambda:
>
> >   effects = []
>
> > At the start of the round, as each entity makes its moves, they add
> > lambdas to this collection.
>
> >   effects.append(
> >       lambda: decrease_hp(monster_a, 4)
> >   )
> >   effects.append(
> >       lambda: lose_item(monster_a, item_b)
> >   )
>
> > Instead of appending it directly like this, I imagine the lambdas
> > could be returned by the monster's 'act' or 'update' method:
>
> >   class Monster():
> >     def act(self):
> >       # blah and finally
> >       return lambda: decrease_hp(monster_a, 4)
>
> > Then for the start of a round, first you ask each monster what action
> > it is going to perform:
>
> >   for monster in room.monsters:
> >       effects.append(
> >           monster.act()
> >       )
>
> > Then for the end of the round, call all the lambdas
>
> >   for effect in effects:
> >       effect()
>
> Mr. Roy Smith already proposed using closures. I already did a similar
> thing in my code, but instead of decrease_hp() I have AttributeEffect
> class which is able to modify any attribute (in old RPGs some monsters
> could drain your intelligence, in my game laser gun hit will decrease
> HP as well as armor integrity). The first version looks like this
> (missing few checks):
>
> class AttributeEffect(object):
>     '''Effect changes object's attribute by delta'''
>     def __init__(self, obj, attrib, delta):
>         self.obj = obj               # reference to object the effect
> applies to
>         self.attrib = attrib         # name of attribute that effect
> applies to
>         self.delta = delta           # change of value for
> object.attribute
>     def apply(self):
>         value = getattr(self.obj, self.attrib) # todo: try, except
>         value += self.delta
>         setattr(self.obj(), self.attrib, value)
>
> Yesterday I learned that Python 3.0 introduces nonlocal keyword which
> would simplify defining effect functions and passing them along. Nice
> improvement.


Very cool, that looks like it would work. The thing I like about the
lambda idea though, is that you don't have to write any classes like
AttributeEffect, (and presumably other such classes, like
LoseItemEffect, etc.) Instead of *modelling* the different kind of
effects that could happen, you just write code that *performs* the
desired effect. (e.g. monster.hp -= damage) To my eyes, lambda's are
therefore more flexible and require less code. But I could be wrong,
and obviously you should do what you think is best for your
circumstances. Very

Re: Unix-head needs to Windows-ize his Python script

2010-10-21 Thread Ulrich Eckhardt
gb345 wrote:
> I have a handy Python script, which takes a few command-line
> arguments, and accepts a few options. [...]
> I want to adapt my script, with the minimum amount of
> work, so that it can have a double-clickable icon that brings up
> a small GUI to accept command-line options (including a couple of
> file-selectors for input and output files).

I'm not sure if this is acceptable for you, but you can simply remove the
commandline stuff and simply ask the user with raw_input(). This is still a
textual UI, but it probably requires least changes. You could even add
an "--interactive" switch regardless of the target environment and then
create an MS Windows batch file that simply runs the Python script with
that switch.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Jean-Michel Pichavant

Martin P. Hellwig wrote:

On 10/20/10 22:09, Seebs wrote:

On 2010-10-20, Matteo Landi  wrote:

Another situation in which I needed to disable such kind of warnings
is while working with graphics modules.
I often use variable names such as x, y, z for coordinates, or r,g,b 
for colors.

Would longer names make the reader's life easier?


Interesting point.  Which is really easier to read:

x, y, z = p.nextpoint()

xCoordinate, yCoordinate, zCoordinate = 
polygon.nextPointCoordinates()


-s


Although intuitively I would say the shorthand, however that is 
depending on the context being me knowing at least the basics of 3d 
spaces and having the pre-warning that you are going to mention 
something with either coordinates or colours.


Take away this pre-information, as you would when first reading an 
application, and all of the sudden the latter would be much clearer to 
the fellow programmer.


I couldn't have said it better (I'll ignore the anti-camelCase lobby for 
now :D )


In the middle of thousand lines of code, when you are reviewing or 
debugging, the later is better TMO, the point is that x, y, z = is only 
easy to read during the assignement. Consider this:


x, y, z = p.nextpoint()
[snip a dozen of code line]
...
...
...
...
...
...
...
...
y += 1 # hmmm ??


vs

xCoordinate, yCoordinate, zCoordinate = polygon.nextPointCoordinates()
[snip a dozen of code line]
...
...
...
...
...
...
...
...
yCoordinate += 1

JM


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


memory management - avoid swapping/paging

2010-10-21 Thread Jon Clements
Hi all,

Is there a cross-platform way using Python to guarantee that an object
will never be swapped/paged to disk? I'll be honest and say I'm really
not sure if this is a particular language question or rather specific
to an OS.

Under linux it appears I could create a ramfs and mmap a file under
that. Is there a way to do the above with mmap?

I'm after something that says: "I want 512mb of physical RAM, I don't
want you to page/swap it, if you can't do that, don't bother at all".
Now I'm guessing, that an OS might be able to grant that, but later on
have to kill the process as other higher-priority processes need RAM
-- that's fine.


Cheers,

Jon.

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Jean-Michel Pichavant

Steven D'Aprano wrote:

On Wed, 20 Oct 2010 12:47:02 +0200, Jean-Michel Pichavant wrote:

  

except ValueError, e:

Use meaningful names, this is so important. 'e' is not meaningful.
'exception' would be slighly better.



While I agree with everything else you had to say, I have to take 
exception to this comment [pun intended].


"e" as a short name for a generic exception instance is perfectly 
reasonable, like:


i, j, k for an index, or a loop variable
e.g. for i in range(100)
n for some other integer variable
s for a string
x for a float, or an arbitrary sequence object
e.g. [x.spam() for x in some_sequence]

and similar.

The last example is very instructive. What do you gain by racking your 
brain for a "more meaningful" name instead of x? The obvious 
alternatives, "obj" or "item", are equally generic as "x", they don't add 
any further information. And how much information do you need? It's easy 
to parody:


[some_sequence_item.spam() for some_sequence_item in some_sequence]

The very shortness of the name is valuable because it reduces the *human* 
parsing time in reading, and there is no cost because the conventions are 
so familiar. The convention of "for i in ..." says "this is a loop over 
an integer" so strongly, that I would argue that "for index in ..." would 
actually *delay* comprehension.


Furthermore, the use of a single letter cues the reader that this 
variable isn't notable -- there's nothing unusual or unconventional about 
it, or it isn't the important part of the algorithm, or that its scope is 
severely limited. For instance, consider the classic example of 
exchanging two variables in Python:


a, b = b, a

versus:

thing, other_thing = other_thing, thing

The first example puts the emphasis on the *technique*, not the 
variables. The second obscures it behind needlessly longer but still 
generic names.


You are absolutely right to insist on meaningful variable names. Where 
you go wrong is to assume that single letter names can't be meaningful.



  


You are using meaningless example without any context, for sure you 
won't find a proper meaningful name.

Let me quote the paper I linked in the previous post:

list1 = []
for x in theList:
   if x[0] == 4: 
   list1 += x;

return list1

compare it to:

flaggedCells = []
for cell in theBoard:
   if cell[STATUS_VALUE] == FLAGGED:
   flaggedCells += cell
return flaggedCells   


There is another important point: the time where code size matters is over. Now 
we have the opportunity to write better structured english and that is 
priceless. Why to your opinion Python has the 'not in' operator ?.
Code is written once, but read dozen of times so we should pay attention to how 
it reads, not really how long it takes to write. You won't be that happy 
everyone wrote their mail in this list like a mobile text message, if u c what 
I mean.

JM


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


Re: Reading Outlook .msg file using Python

2010-10-21 Thread Tim Golden

On 21/10/2010 09:34, Jon Clements wrote:

Only just noticed this thread, and had something similar. I took the
following approach:-

(I'm thinking this might be relevant as you mentioned checking whether
your client's Outlook could export .EML directly, which indicates (to
me at least) that you have some control over that...)

- Set up an IMAP email server on a machine (in this case linux and
dovecot)
- Got client to set up a new account in Outlook for the new server
- Got client to use the Outlook interface to copy relevant emails (or
the whole lot) to new server
- Used the standard imaplib and related modules to do what was needed


Nice lateral approach. It would also be possible to do this same
kind of thing via the native Microsoft toolset alone if the OP
has access to the appropriate Outlook / Exchange accounts. (Indeed,
Exchange itself can act as an IMAP server which might be another
approach). I confess I was starting from the original "Can I read an
.msg file?" question.

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


Re: Reading Outlook .msg file using Python

2010-10-21 Thread Jon Clements
On 20 Oct, 18:13, John Henry  wrote:
> On Oct 20, 9:01 am, John Henry  wrote:
>
>
>
> > On Oct 20, 1:41 am, Tim Golden  wrote:
>
> > > On 19/10/2010 22:48, John Henry wrote:
>
> > > > Looks like this flag is valid only if you are getting messages
> > > > directly from Outlook.  When reading the msg file, the flag is
> > > > invalid.
>
> > > > Same issue when accessing attachments.  In addition, the MAPITable
> > > > method does not seem to work at all when trying to get attachments out
> > > > of the msg file (works when dealing with message in an Outlook
> > > > mailbox).  Eitherway, the display_name doesn't work when trying to
> > > > display the filename of the attachment.
>
> > > > I was able to get the date by using the PR_TRANSPORT_MESSAGE_HEADERS
> > > > mapitags
>
> > > Ah, thanks. As you will have realised, my code is basically geared
> > > to reading an Outlook/Exchange message box. I hadn't really tried
> > > it on individual message files, except my original excerpt. If it
> > > were opportune, I'd be interested in seeing your working code.
>
> > > TJG
>
> > When (and if) I finally figure out how to get it done, I surely will
> > make the code available.  It's pretty close.  All I need is to figure
> > out how to extract the attachments.
>
> > Too bad I don't know (and don't have) C#.  This guy did it so cleanly:
>
> >http://www.codeproject.com/KB/office/reading_an_outlook_msg.aspx?msg=...
>
> > May be somebody that knows both C# and Python can convert the code
> > (not much code) and then the Python community will have it.  As it
> > stands, it seems the solution is available in Java, C#, VB  but
> > not Python.
>
> BTW: For the benefit of future search on this topic, with the code
> listed above where:
>
> storage_flags = STGM_DIRECT | STGM_READ | STGM_SHARE_EXCLUSIVE
>
> I had to change it to:
>
> storage_flags = STGM_DIRECT | STGM_READ | STGM_SHARE_DENY_NONE |
> STGM_TRANSACTED
>
> otherwise I get a sharing violation 
> (seehttp://efreedom.com/Question/1-1086814/Opening-OLE-Compound-Documents...).
>
> For now, I am using a brute force method (http://mail.python.org/
> pipermail/python-win32/2009-February/008825.html) to get the names of
> the attachments and if I need to extract the attachments, I pop up the
> message in Outlook and let Outlook extract the files.  Ugly but fits
> my client's need for now.  Hopefully there will be a cleaner solution
> down the road.
>
> Here's my code for brute forcing attachments out of the msg file (very
> ugly):
>
>         def get_attachments(self, fileID):
>                 #from win32com.storagecon import *
>                 from win32com import storagecon
>                 import pythoncom
>
>                 flags = storagecon.STGM_READ | 
> storagecon.STGM_SHARE_DENY_NONE |
> storagecon.STGM_TRANSACTED
>                 try:
>                         storage = pythoncom.StgOpenStorage (fileID, None, 
> flags)
>                 except:
>                         return []
>
>                 flags = storagecon.STGM_READ | storagecon.STGM_SHARE_EXCLUSIVE
>                 attachments=[]
>                 for data in storage.EnumElements ():
>                         print data[0], data[1]
>                         if data[1] == 2 or data[0] == "__substg1.0_007D001F":
>                                 stream = storage.OpenStream (data[0], None, 
> flags)
>                                 try:
>                                         msg = stream.Read (data[2])
>                                 except:
>                                         pass
>                                 else:
>                                         msg = repr (msg).replace("\
> \x00","").strip("'").replace("%23","#")
>                                         if data[0] == "__substg1.0_007D001F":
>                                                 try:
>                                                         
> attachments.append(msg.split("name=\"")[1].split("\"")[0])
>                                                 except:
>                                                         pass
>
>                 return attachments

Only just noticed this thread, and had something similar. I took the
following approach:-

(I'm thinking this might be relevant as you mentioned checking whether
your client's Outlook could export .EML directly, which indicates (to
me at least) that you have some control over that...)

- Set up an IMAP email server on a machine (in this case linux and
dovecot)
- Got client to set up a new account in Outlook for the new server
- Got client to use the Outlook interface to copy relevant emails (or
the whole lot) to new server
- Used the standard imaplib and related modules to do what was needed

>From my POV I didn't have to mess around with proprietary formats or
deal with files. From the client's POV, they were able to, with an
interface familiar to them, add/remove what needed processing. It also
enabled multiple people at the client's site to cont

The 'n' format specifier

2010-10-21 Thread Boštjan Mejak
The locale.setlocale(category=locale.LC_NUMERIC, locale="Slovenian")  works
like a charm in my application. Now the 'n format specifier works as I want.
But tell me whether the 'n' forma specifier can be forced to round the float
to just one decimal place. I know that the 'f' format specifier does that by
specifying ".1f", but 'f' is not locale-aware. I have set the 'n' format
specifier in my application like ".3n", which is okay if the returned number
is two integers and one decimal, but is not okay if the returned number is
one integer and two decimals, because I want just one decimal, always. How
can I make that by using the 'n' format specifier?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unix-head needs to Windows-ize his Python script

2010-10-21 Thread Tim Golden

On 20/10/2010 18:38, gb345 wrote:

I have a handy Python script, which takes a few command-line
arguments, and accepts a few options.  I developed it on Unix, with
very much of a Unix-mindset.  Some Windows-using colleagues have
asked me to make the script "easy to use under Windows 7".  I.e.:
no command-line.


The usual suspects for this include:

  http://easygui.sourceforge.net/

  http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

  http://www.averdevelopment.com/python/EasyDialogs.html


Any of those will suffice, I suspect. Personally, I use my
own winsys.dialogs:

  http://timgolden.me.uk/python/winsys/dialogs.html

which have the very slight advantage of allowing dragging-and-dropping
files from explorer into textedit controls and/or having a button which
brings up the FileOpen (or any other) system dialog. If you do want
to use it, I suggest the svn trunk which will work for Py2 or Py3
(courtesy of 2to3).

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


Re: pylint -- should I just ignore it sometimes?

2010-10-21 Thread Martin P. Hellwig

On 10/20/10 22:09, Seebs wrote:

On 2010-10-20, Matteo Landi  wrote:

Another situation in which I needed to disable such kind of warnings
is while working with graphics modules.
I often use variable names such as x, y, z for coordinates, or r,g,b for colors.
Would longer names make the reader's life easier?


Interesting point.  Which is really easier to read:

x, y, z = p.nextpoint()

xCoordinate, yCoordinate, zCoordinate = polygon.nextPointCoordinates()

-s


Although intuitively I would say the shorthand, however that is 
depending on the context being me knowing at least the basics of 3d 
spaces and having the pre-warning that you are going to mention 
something with either coordinates or colours.


Take away this pre-information, as you would when first reading an 
application, and all of the sudden the latter would be much clearer to 
the fellow programmer.


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


Re: Unix-head needs to Windows-ize his Python script

2010-10-21 Thread Eric Brunel
In article ,
 Shawn Milochik  wrote:
> Also, wxPython automatically looks native Mac, Windows, and Linux.

And so do the recent versions of Tkinter/tcl-tk... In Python, you just 
have to use the widgets in the new ttk module. These widgets also have 
fewer options than their equivalent in Tkinter, so they probably are 
even more accessible to people who never wrote a GUI before. The 
documentation is here: http://docs.python.org/library/ttk.html#module-ttk

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