Re: choose value from custom distribution

2010-10-19 Thread Ian
On Oct 18, 9:27 pm, elsa  wrote:
> Hello,
>
> I'm trying to find a way to collect a set of values from real data,
> and then sample values randomly from this data - so, the data I'm
> collecting becomes a kind of probability distribution. For instance, I
> might have age data for some children. It's very easy to collect this
> data using a list, where the index gives the value of the data, and
> the number in the list gives the number of times that values occurs:
>
> [0,0,10,20,5]
>
> could mean that there are no individuals that are no people aged 0, no
> people aged 1, 10 people aged 2, 20 people aged 3, and 5 people aged 4
> in my data collection.
>
> I then want to make a random sample that would be representative of
> these proportions - is there any easy and fast way to select an entry
> weighted by its value? Or are there any python packages that allow you
> to easily create your own distribution based on collected data? Two
> other things to bear in mind are that in reality I'm collating data
> from up to around 5 million individuals, so just making one long list
> with a new entry for each individual won't work. Also, it would be
> good if I didn't have to decide before hand what the possible range of
> values is (which unfortunately I have to do with the approach I'm
> currently working on).

My suggestion is to sample into a cumulative sum list and find the
index by binary search:

import bisect
import random

data = [0, 0, 10, 20, 5]
cumsum = []
for x in data:
cumsum.append(cumsum[-1] + x if cumsum else x)
virtual_index = random.randrange(cumsum[-1])
actual_index = bisect.bisect_right(cumsum, virtual_index)

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


Re: Deferring a function call

2010-10-19 Thread Michael Ricordeau
For scheduling, I use eventlet package and spawn_after_local .
 http://eventlet.net

But you must be aware of the constraints like using "monkey patched" modules .
  



Le Mon, 18 Oct 2010 21:21:41 -0700,
TomF  a écrit :

> I'm writing a simple simulator, and I want to schedule an action to 
> occur at a later time.  Basically, at some later point I want to call a 
> function f(a, b, c).  But the values of a, b and c are determined at 
> the current time.
> 
> One way way to do this is to keep a list of entries of the form [[TIME, 
> FN, ARGS]...] and at simulated time TIME do: apply(FN, ARGS)
> Aside from the fact that apply is deprecated, it seems like there 
> should be a cleaner (possibly more Pythonic) way to do this.   Ideas?
> 
> -Tom
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting returncode of a command executed with Popen through xterm

2010-10-19 Thread Diez B. Roggisch
amfr...@web.de writes:

> Hi,
>
> i have a program that have to execute linux commands. I do it like this:
>
> retcode = Popen(["xterm", "-e", command],stdin=PIPE, stdout=PIPE,
> stderr=PIPE)
>
> I have to use xterm because some commands need further input from the
> user after they are executed.
> But when i use xterm i can't get the returncode or the errormessage
> from a command:
>
> print retcode.returncode  # always 0
> print retcode.stderr.read()   # always empty
> print retcode.stdout.read()   # always empty
>
> The same code works without xterm. As i understand it, if i use xterm
> the retcode refers to the xterm window (process).
> But is there a way i can get the returncode and errormessage of the
> command i sent to xterm ?

You could create a python-wrapper-script that will store the result and
streams in files. Like this


command = ["callwrapper", "--dest-key=", "the_real_command"]
Popen(["xterm", "-e", command])

The dest-key will be used to create files named .status,
.stdout, .stderr so that you can read from
them afterwards.

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


Re: OO and game design questions

2010-10-19 Thread dex
> I'm not sure if it's a good idea to let an item disappear from your
> inventory by a weak reference disappearing.  It seems a little shaky
> to not know where your objects are being referenced, but that's yout
> decision.

OK, imagine a MUD, where players can "dig out" new rooms. Room A has a
door that holds reference to newly created room B. By "using" a door,
player is transported to room B. At later time someone destroys room
B.

Using strong references, I have to remove room B from list of rooms,
and also remove door to room B, as it holds reference to room B. To do
that, I have to keep list of doors that lead to room B.

Using weak references, I don't have to worry about removing all doors
to room B. They all now have a dead reference, which better models
actual situation. If part of mine collapses, or if a module on space
station is destroyed, the passage to that location does not magically
vanish - it's just obstructed.

Can you please tell me if there's something wrong with my reasoning?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Catching a SIGSEGV signal on an import

2010-10-19 Thread Chris Torek
(I realize this is old but I am recovering from dental surgery and,
while on the Good Drugs for the pain, going through old stuff on
purpose :-) )

>On Thu, 09 Sep 2010 05:23:14 -0700, Ryan wrote:
>> In general, is there anyway to catch a  SIGSEGV on import?

In article ,
Nobody   wrote:
>No. If SIGSEGV is raised, it often indicates that memory has been
>corrupted. At that point, you can't assume that the Python runtime is
>still functional.

Indeed.

Still, there *is* a way to do this, should you choose to live
somewhat dangerously.

First, make a copy of the original process.  Using Unix as an
example:

pid = os.fork()
if pid == 0:
# child
import untrustworthy
os._exit(0)

The import will either succeed or fail.  If it fails with a SIGSEGV
the child process will die; if not, the child will move on to the
next statement and exit (using os._exit() to bypass exit handlers,
since this is a forked child etc).

The parent can then do a waitpid and see whether the child was able
to do the import.

The obvious flaw in this method is that something that causes Python
to die with a SIGSEGV when imported probably has some serious bugs
in it, and depending on the state of the importing process, these
bugs might not cause a problem immediately, but instead set time-bombs
that will go off later.  In this case, the child import will succeed
and the parent will then trust the import itself (note that you
have to re-do the same import in the parent as it is completely
independent after the fork()).  Still, if you are dead set on the
idea, the test code below that I threw together here may be helpful.

---

import os, signal, sys

pid = os.fork()
if pid == 0:
# deliberately not checking len(sys.argv) nor using try
# this allows you to see what happens if you run "python t.py"
# instead of "python t.py sig" or "python t.py fail" or
# "python t.py ok", for instance.
if sys.argv[1] == 'sig':
os.kill(os.getpid(), signal.SIGSEGV)
if sys.argv[1] == 'fail':
os._exit(1)
# Replace the above stuff with the untrustworthy "import",
# assuming you like the general idea.
os._exit(0)

print 'parent: child =', pid
wpid, status = os.waitpid(pid, 0)
print 'wpid =', wpid, 'status =', status
if os.WIFSIGNALED(status):
print 'child died from signal', os.WTERMSIG(status)
if os.WCOREDUMP(status):
print '(core dumped)'
elif os.WIFEXITED(status):
print 'child exited with', os.WEXITSTATUS(status)
# at this point the parent can repeat the "import"
else:
print 'I am confused, maybe I got the wrong pid'

---

The same kind of thing can be done on other OSes, but all the details
will differ.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


User interaction with Python

2010-10-19 Thread Wolfgang Meiners
Hello all,

I would like to have a function to edit values in a database.

So I am reading values from the database and do something like

newString = edit(oldString)

and then oldString is written to the screen and can be edited in a
vi-like manner for example. The function edit should return the edited
Value. I am sure, there is a possibility to do such work in python, but
I don't know where to look.

Thank you for all hints
Wolfgang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: stats 0.1a calculator statistics for Python

2010-10-19 Thread Jean-Michel Pichavant

Steven D'Aprano wrote:

On Tue, 19 Oct 2010 11:53:40 +1100, Ben Finney wrote:

  

Steven D'Aprano  writes:



On Mon, 18 Oct 2010 11:56:39 +0200, Jean-Michel Pichavant wrote:

  

I already have a stats module:
/usr/lib/python2.5/site-packages/stats.py


The name of my module is not set in stone.

I can't help what site-packages you have, but the above is not on PyPI,
and it's certainly not part of the standard library.
  

How did you determine that? Unfortunately, the name of the package
listed on PyPI bears no relation to the name of packages installed into
Python.



Fair point. 



  

It's part of the debian distribution. Just sayin so you know :).

apt-cache showpkg python-stats
Package: python-stats
Versions:
0.6-7 
(/var/lib/apt/lists/apt-cache.sequans.com_debian_dists_lenny_main_binary-i386_Packages) 
(/var/lib/dpkg/status)



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


Windows: getting notification about power state changes

2010-10-19 Thread Gelonida
Hi,


I wondered how I could achieve this.

I'd like to be notified about certain events and call certain python
functions depending on the event.

call a function:
- before (or after) the screen saver kicks in
- before (or after) the monitor is switched off
- before (or after) the hard disk is switched off
- before the PC enters stand by mode

- after the PC left stand by mode
- before (or after) the PC's hard disk was powered up
- before (or after) the monitor was switched on
- before (or after) the screen saver was stopped


Thanks a lot for any pointers

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


Re: choose value from custom distribution

2010-10-19 Thread Peter Otten
Chris Rebert wrote:

> On Mon, Oct 18, 2010 at 11:40 PM, Arnaud Delobelle 
> wrote:
>> elsa  writes:
>>> Hello,
>>>
>>> I'm trying to find a way to collect a set of values from real data,
>>> and then sample values randomly from this data - so, the data I'm
>>> collecting becomes a kind of probability distribution. For instance, I
>>> might have age data for some children. It's very easy to collect this
>>> data using a list, where the index gives the value of the data, and
>>> the number in the list gives the number of times that values occurs:
>>>
>>> [0,0,10,20,5]
>>>
>>> could mean that there are no individuals that are no people aged 0, no
>>> people aged 1, 10 people aged 2, 20 people aged 3, and 5 people aged 4
>>> in my data collection.
>>>
>>> I then want to make a random sample that would be representative of
>>> these proportions - is there any easy and fast way to select an entry
>>> weighted by its value? Or are there any python packages that allow you
>>> to easily create your own distribution based on collected data?
> 
>> If you want to keep it simple, you can do:
>>
> t = [0,0,10,20,5]
> expanded = sum([[x]*f for x, f in enumerate(t)], [])
> random.sample(expanded, 10)
>> [3, 2, 2, 3, 2, 3, 2, 2, 3, 3]
> random.sample(expanded, 10)
>> [3, 3, 4, 3, 2, 3, 3, 3, 2, 2]
> random.sample(expanded, 10)
>> [3, 3, 3, 3, 3, 2, 3, 2, 2, 3]
>>
>> Is that what you need?
> 
> The OP explicitly ruled that out:
> 
>>> Two
>>> other things to bear in mind are that in reality I'm collating data
>>> from up to around 5 million individuals, so just making one long list
>>> with a new entry for each individual won't work.

Python can cope with a list of 5 million integer entries just fine on 
average hardware. Eventually you may have to switch to Ian's cumulative sums 
approach -- but not necessarily at 10**6.

>>> Also, it would be
>>> good if I didn't have to decide before hand what the possible range of
>>> values is (which unfortunately I have to do with the approach I'm
>>> currently working on).

This second objection seems invalid to me, too, and I think what Arnaud 
provides is a useful counterexample.

However, if you (elsa) are operating near the limits of the available memory 
on your machine using sum() on lists is not a good idea. It does the 
equivalent of

expanded = []
for x, f in enumerate(t):
expanded = expanded  + [x]*f

which creates a lot of "large" temporary lists where you want the more 
memory-friendly

expanded = []
for x, f in enumerate(t):
expanded.extend([x]*f) 
# expanded += [x]*f

> The internet is wrecking people's attention spans and reading
> comprehension.

Maybe, but I can't google the control group that is always offline and I 
have a hunch that facebook wouldn't work either ;)

Peter


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


Re: Windows: getting notification about power state changes

2010-10-19 Thread Tim Golden

On 19/10/2010 10:06, Gelonida wrote:

I'd like to be notified about certain events and call certain python
functions depending on the event.

call a function:
- before (or after) the screen saver kicks in
- before (or after) the monitor is switched off
- before (or after) the hard disk is switched off
- before the PC enters stand by mode

- after the PC left stand by mode
- before (or after) the PC's hard disk was powered up
- before (or after) the monitor was switched on
- before (or after) the screen saver was stopped


This should take you a certain amount of the way:

  http://timgolden.me.uk/python/win32_how_do_i/track-session-events.html

I honestly don't know if the OS even knows when the monitor's
switched on / when the disk is spun up.

WMI has some power events:

  http://msdn.microsoft.com/en-us/library/aa394362%28v=VS.85%29.aspx


http://timgolden.me.uk/python/wmi/cookbook.html#monitor-multiple-machines-for-power-events

but again I don't know about disk/monitor events.

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


Re: User interaction with Python

2010-10-19 Thread Peter Otten
Wolfgang Meiners wrote:


> I would like to have a function to edit values in a database.
> 
> So I am reading values from the database and do something like
> 
> newString = edit(oldString)
> 
> and then oldString is written to the screen and can be edited in a
> vi-like manner for example. The function edit should return the edited
> Value. I am sure, there is a possibility to do such work in python, but
> I don't know where to look.

When readline is available:

http://mail.python.org/pipermail/python-list/2009-June/1209309.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deferring a function call

2010-10-19 Thread Peter Otten
TomF wrote:

> I'm writing a simple simulator, and I want to schedule an action to
> occur at a later time.  Basically, at some later point I want to call a
> function f(a, b, c).  But the values of a, b and c are determined at
> the current time.
> 
> One way way to do this is to keep a list of entries of the form [[TIME,
> FN, ARGS]...] and at simulated time TIME do: apply(FN, ARGS)
> Aside from the fact that apply is deprecated, it seems like there
> should be a cleaner (possibly more Pythonic) way to do this.   Ideas?

You can prepare the function 

fstar = functools.partial(f, a, b, c)

and later invoke it as

fstar()

Peter

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


Re: Simple logging example doesn't work!

2010-10-19 Thread Chris Torek
>On Oct 18, 10:45 pm, "robinsieb...@gmail.com" 
>wrote:
>> If I setlogging.basicConfig() call tologging.INFO, then I see info
>> messages in the logfile. I only want to see error messages in the
>> logfile.

I am not sure how good the documentation is (having not gone back
to look at it) but I had the same problem when I first started using
the logging module for a server.  Vinay Sajip's recipe below is
correct, the only thing missing is "why it is correct":

In article <0945c1e3-f575-4940-8f2c-0374308a3...@j18g2000yqd.googlegroups.com>
Vinay Sajip   wrote:
>What you need to do is,
>
>1. Set the root logger's level to INFO. That's because you want at
>least INFO messages to go somewhere.
>2. Don't use basicConfig(), but instead create a console handler and a
>file handler explicitly.
>3. Set the file handler's level to ERROR, so only ERROR messages and
>higher go to the file.
>4. Set the console handler's level to INFO, so INFO messages and
>higher go to console.

The reason for step 2 (avoid logging.basicConfig()) is that
basicConfig() creates a handler that goes to sys.stderr.  There is
no way to adjust that handler.  (Well, it is on a list of handlers
that you could peek into, but that seems ... unwise.)

>If you need anything more involved (for example, you ONLY want INFO
>messages to be shown on the console) you'll need to set up a suitable
>Filter and add it to the console handler to filter out messages you
>don't want. See the logging docs for more info on Filters.

Here's a moderately complex example that is full of some bad coding
practices :-) but shows how to do some fancy things.  I snipped it
out of a real program, so there are parts that probably look kind
of whacky but have some real purpose; other parts that look whacky
are because I wrote a lot of this while in early "learning Python"
stages.

import logging.handlers

logger = None

[Next is a hack I was experimenting with to sort-of-hide
some globals ... much irrelevant stuff has been snipped out,
so everything you see in "g" here is purely for logging, and
it would make more sense to have a class for logging control
to retain this stuff.  As I said, early code. :-) ]

class g: pass

# syslog adds its own time and level stamp.
g.syslog_format = (
'nodemgr: %(threadName)s %(message)s'
' - %(filename)s/%(funcName)s:%(lineno)d'
)
g.stderr_format = '%(levelname)-8s (%(threadName)s) %(message)s'
g.log_format = (
'%(asctime)s: ' + g.stderr_format + 
' - %(filename)s/%(funcName)s:%(lineno)d'
)

# these are actually "log handlers"
g.file_logger = None
g.stderr_logger = None
g.syslog_logger = None

# Set up initial logger.
#
# Although it is labeled "temporary", it persists: it is
# just its configuration that is "temporary", until we read
# the config file.
def init_temporary_logger():
global logger

# Get "master" logger with stderr "slave".  Note that we
# set the master level no higher than DEBUG, otherwise the slaves
# never see DEBUG-level entries.
#
# Can't use basicConfig here as it creates a sys.stderr
# StreamHandler that we can't adjust later.  Just omit the call:
#   logging.basicConfig(level = logging.DEBUG, format = ...)
# which leaves logging.root unset, which is OK.
nl = logging.getLogger('nodemgr')
nl.setLevel(logging.DEBUG)
stream = logging.StreamHandler(sys.stderr)
stream.setFormatter(logging.Formatter(g.stderr_format))
stream.setLevel(logging.INFO) # until later
nl.addHandler(stream)
g.stderr_logger = stream
logger = nl

# Get a syslog "address" given a string.
def get_syslog_addr(syslog_to):
# Syslog takes either a host name and optional port, or a path
# name to a file.  We choose here based on a regexp match.
m = re.compile('([^/:]+)(:([0-9]+))?$').match(syslog_to)
if m:
(host, _, port) = m.groups()
if port is not None:
try:
port = int(port)
except ValueError:
port = 0
if port < 1 or port > 65535:
logger.error('syslog-to=%s: bad port number', syslog_to)
port = 0
addr = (host, port or logging.handlers.SYSLOG_UDP_PORT)
else:
addr = syslog_to
return addr

# Update logger based on configuration.
def update_logger(conf):
global logger

# Helper function for swapping out syslog and file loggers.
def swapout(old, new):
if old != new and old is not None:
logger.removeHandler(old)
if new is not None:
logger.addHandler(new)
return new

# Helper function: is given fd already open to given file name?
# (Note that this gives you a slightly stale answer, in 

Re: User interaction with Python

2010-10-19 Thread Wolfgang Meiners
Am 19.10.10 11:31, schrieb Peter Otten:
> Wolfgang Meiners wrote:
>>
>> newString = edit(oldString)
>>
> 
> When readline is available:
> 
> http://mail.python.org/pipermail/python-list/2009-June/1209309.html

Thank you for this hint.
Wolfgang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO and game design questions

2010-10-19 Thread Dave Angel

 On 2:59 PM, dex wrote:

I'm not sure if it's a good idea to let an item disappear from your
inventory by a weak reference disappearing.  It seems a little shaky
to not know where your objects are being referenced, but that's yout
decision.

OK, imagine a MUD, where players can "dig out" new rooms. Room A has a
door that holds reference to newly created room B. By "using" a door,
player is transported to room B. At later time someone destroys room
B.

Using strong references, I have to remove room B from list of rooms,
and also remove door to room B, as it holds reference to room B. To do
that, I have to keep list of doors that lead to room B.

Using weak references, I don't have to worry about removing all doors
to room B. They all now have a dead reference, which better models
actual situation. If part of mine collapses, or if a module on space
station is destroyed, the passage to that location does not magically
vanish - it's just obstructed.

Can you please tell me if there's something wrong with my reasoning?

Simply replace room B with a "destroyed room" object.  That can be quite 
small, and you only need one, regardless of how many rooms are thus 
eliminated.


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


Re: OO and game design questions

2010-10-19 Thread Roy Smith
dex  wrote:

> I'm building a turn based RPG game as a hobby. The design is becoming
> increasingly complicated and confusing

Such is often the case in real life code :-)

> In turn-based games, the order of action execution in battle can give
> unfair advantage to players. [...] Is there a design
> pattern that would remember changes to an object, and apply them
> later?

This sounds like a database transaction.  Perhaps what you want is for 
each object to include a delayedActions list.  Each time something 
happens to an object, you push a closure onto the list.  At the end of 
the turn, you run

for obj in global_object_list:
   obj.apply_delayed_actions()

> Sorry for the wall of text.

No problem.  The newsgroup ducks, swivels around on its Content-Type 
header, hides behind an NNTP outcropping on the server, and just barely 
avoids being hit by the oncoming wall.  You roll 2d10 and make your 
saving throw against Magical Text Wall, preventing any residual effects 
of the attack.  Whew, that was close!

In another article, Dave Angel suggested:

> Simply replace room B with a "destroyed room" object.  That can be quite 
> small, and you only need one, regardless of how many rooms are thus 
> eliminated.

I worked with an OODB system which did exactly this.  Each object class 
had a Class::Deleted singleton.  Whenever an object was deleted, 
references to it were replaced by references to the Deleted object.  For 
the most part, this worked, but resulted in a 4-byte memory leak for 
each reference (there was still a C++ pointer to Class::Deleted).

This memory leak was a known problem, but deemed to be small enough that 
we could live with it.  In the particular application domain we were 
working in, object deletions were rare.  I don't know if that's the case 
in your MUD.  I would assume that the physical structure of the world 
(rooms, corridors, doors) for the most part get created and rarely 
deleted, but that may not be true of other objects in the game?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: stats 0.1a calculator statistics for Python

2010-10-19 Thread Chris Torek
>2010/10/17 Steven D'Aprano :
>> http://pypi.python.org/pypi/stats

In article 
Vlastimil Brom   wrote:
>Thanks for this useful module!
>I just wanted to report a marginal error triggered in the doctests:
>
>Failed example:
>isnan(float('nan'))
>Exception raised:
>Traceback (most recent call last):
>  File "C:\Python25\lib\doctest.py", line 1228, in __run
>compileflags, 1) in test.globs
>  File "", line 1, in 
>isnan(float('nan'))
>ValueError: invalid literal for float(): nan
>
>(python 2.5.4 on win XP; this might be OS specific; probably in the
>newer versions float() was updated, the tests on 2.6 and 2.7 are ok ):

Indeed it was; in older versions float() just invoked the C library
routines, so float('nan') works on Mac OS X python 2.5, for instance,
but then you run into the fact that math.isnan() is only in 2.6 and
later :-)

Workaround, assuming an earlier "from math import *":

try:
isnan(0.0)
except NameError:
def isnan(x): x != x

Of course you are still stuck with float('nan') failing on Windows.
I have no quick and easy workaround for that one.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


hai

2010-10-19 Thread Viji Kumar S S
 http://123maza.com/35/demand120/
-- 
http://mail.python.org/mailman/listinfo/python-list


Python default search paths

2010-10-19 Thread swapnil
Python allows adding user defined paths to the module search path by
setting PYTHONPATH environment variable. It also allows to alter the
location of standard python libraries using PYTHONHOME. But there is
no way to "only" have user defined paths to python's search paths
(sys.path)

This is useful for embedding applications where it might be desired
that only user-defined paths are searched for modules. But python
creates some default paths and adds it to sys.path.  Most of the times
it does not matter since PYTHONPATH paths are appended at the
beginning but this may sometimes result in unwanted behavior.

I think it would be a good idea to be able to say that you don't need
any default search paths. In this case if Python gives error if
PYTHONPATH is not set-  I think that would be reasonable. Since
otherwise sys.path would be empty!!

Please provide feedback for this feature request.
-- 
http://mail.python.org/mailman/listinfo/python-list


overriding a property

2010-10-19 Thread Lucasm
Hi,

A question. Is it possible to dynamically override a property?

class A(object):
@property
def return_five(self):
return 5

I would like to override the property for an instance of A to say the
string 'bla'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: overriding a property

2010-10-19 Thread Benjamin Peterson
Lucasm  gmail.com> writes:


> I would like to override the property for an instance of A to say the
> string 'bla'.

A.return_five = "blah"




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


Re: overriding a property

2010-10-19 Thread John Posner

On 10/19/2010 9:39 AM, Lucasm wrote:

Hi,

A question. Is it possible to dynamically override a property?

class A(object):
 @property
 def return_five(self):
 return 5

I would like to override the property for an instance of A to say the
string 'bla'.


Is this the sort of thing you're looking for ...

#-
import inspect

class A(object):
@property
def return_five(self):
try:
# get name of this function ...
frm = inspect.getframeinfo(inspect.currentframe())
# ... and use it as dict key
return self.__dict__[frm.function]

except KeyError:
# attr not set in instance
return 5

a = A()
print "one:", a.return_five

b = A()
b.__dict__['return_five'] = 'bla'
print "two:", b.return_five

c = A()
print "three:", c.return_five
#-

The output is:

  one: 5
  two: bla
  three: 5

If you don't want to fool around with the inspect module, you can 
hard-code the function name as the instance's dict key:


   return self.__dict__['return_five']

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


Re: overriding a property

2010-10-19 Thread Steven D'Aprano
On Tue, 19 Oct 2010 06:39:56 -0700, Lucasm wrote:

> Hi,
> 
> A question. Is it possible to dynamically override a property?
> 
> class A(object):
> @property
> def return_five(self):
> return 5
> 
> I would like to override the property for an instance of A to say the
> string 'bla'.


>>> class A(object):
... _five = 5  # class attribute shared by all instances
... @property
... def return_five(self):
... return self._five
...
>>>
>>> a = A()
>>> a._five = 'bla'  # set an instance attribute
>>> b = A()
>>> print a.return_five
bla
>>> print b.return_five
5



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


Re: Python default search paths

2010-10-19 Thread Steven D'Aprano
On Tue, 19 Oct 2010 06:25:30 -0700, swapnil wrote:

> Python allows adding user defined paths to the module search path by
> setting PYTHONPATH environment variable. It also allows to alter the
> location of standard python libraries using PYTHONHOME. But there is no
> way to "only" have user defined paths to python's search paths
> (sys.path)

import sys
sys.path = ['.', 'only', 'user/defined/paths']

Put that in the file given by PYTHONSTARTUP.


> This is useful for embedding applications where it might be desired that
> only user-defined paths are searched for modules.

I doubt that very much. I expect that many things will break if Python 
can't find (e.g.) the sys module. But you might be lucky.



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


Python3: Is this a bug in urllib?

2010-10-19 Thread Johannes Bauer
Hi,

I've experienced the following behavior with Python3 of which I do not
know if it's a bug or not. On two Python3.1 implementations, Python's
urllib hangs when encountering a HTTP 301 (Redirect).

The code to reproduce is a one-liner (actually, two-liner), Python from
Ubuntu tree:

Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from urllib import request; request.URLopener().open("http://google.de";)

Also occurs on another Python version (Gentoo):

Python 3.1.2 (release31-maint, Jun  9 2010, 23:58:21)
[GCC 4.3.4] on linux2

The exchanged HTTP is:

GET http://google.de HTTP/1.1
Accept-Encoding: identity
Host: google.de
User-Agent: Python-urllib/3.1

HTTP/1.1 301 Moved Permanently
Via: 1.1 IMMPWISA01
Connection: Keep-Alive
Proxy-Connection: Keep-Alive
Content-Length: 218
Expires: Thu, 18 Nov 2010 15:18:40 GMT
Date: Tue, 19 Oct 2010 15:18:40 GMT
Location: http://www.google.de/
Content-Type: text/html; charset=UTF-8
Server: gws
Cache-Control: public, max-age=2592000
X-XSS-Protection: 1; mode=block


301 Moved
301 Moved
The document has moved
http://www.google.de/";>here.


Although the content might indicate looping forever, it just hangs with
no web traffic whatsoever (the TCP connection stays open, however).

When interrupting with Ctrl-C, this is the calltrace:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python3.1/urllib/request.py", line 1454, in open
return getattr(self, name)(url)
  File "/usr/lib/python3.1/urllib/request.py", line 1628, in open_http
return self._open_generic_http(http.client.HTTPConnection, url, data)
  File "/usr/lib/python3.1/urllib/request.py", line 1624, in
_open_generic_http
response.status, response.reason, response.msg, data)
  File "/usr/lib/python3.1/urllib/request.py", line 1644, in http_error
return self.http_error_default(url, fp, errcode, errmsg, headers)
  File "/usr/lib/python3.1/urllib/request.py", line 1648, in
http_error_default
void = fp.read()
  File "/usr/lib/python3.1/socket.py", line 214, in readinto
return self._sock.recv_into(b)
KeyboardInterrupt

Can anyone tell me if this is a bug or expected behavior?

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: Deferring a function call

2010-10-19 Thread TomF

Thanks for the ideas, everyone.

functools.partial and lambda expressions seem like a more pythonic way 
of doing what I want.  I don't know whether they're actually more 
efficient or better, but at least they eliminate the need to carry args 
around separately.


I'd forgotten Python has a sched module in its standard library.  It 
may be overkill for what I want to do but I'll take a look.


-Tom

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


Re: Python3: Is this a bug in urllib?

2010-10-19 Thread Nitin Pawar
the content is in a loop because it is getting redirected again and again

and the interrupt exception is perfectly ok when you press ctrl +c

On Tue, Oct 19, 2010 at 10:17 PM, Johannes Bauer wrote:

> Hi,
>
> I've experienced the following behavior with Python3 of which I do not
> know if it's a bug or not. On two Python3.1 implementations, Python's
> urllib hangs when encountering a HTTP 301 (Redirect).
>
> The code to reproduce is a one-liner (actually, two-liner), Python from
> Ubuntu tree:
>
> Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from urllib import request; request.URLopener().open("http://google.de
> ")
>
> Also occurs on another Python version (Gentoo):
>
> Python 3.1.2 (release31-maint, Jun  9 2010, 23:58:21)
> [GCC 4.3.4] on linux2
>
> The exchanged HTTP is:
>
> GET http://google.de HTTP/1.1
> Accept-Encoding: identity
> Host: google.de
> User-Agent: Python-urllib/3.1
>
> HTTP/1.1 301 Moved Permanently
> Via: 1.1 IMMPWISA01
> Connection: Keep-Alive
> Proxy-Connection: Keep-Alive
> Content-Length: 218
> Expires: Thu, 18 Nov 2010 15:18:40 GMT
> Date: Tue, 19 Oct 2010 15:18:40 GMT
> Location: http://www.google.de/
> Content-Type: text/html; charset=UTF-8
> Server: gws
> Cache-Control: public, max-age=2592000
> X-XSS-Protection: 1; mode=block
>
>  content="text/html;charset=utf-8">
> 301 Moved
> 301 Moved
> The document has moved
> http://www.google.de/";>here.
> 
>
> Although the content might indicate looping forever, it just hangs with
> no web traffic whatsoever (the TCP connection stays open, however).
>
> When interrupting with Ctrl-C, this is the calltrace:
>
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "/usr/lib/python3.1/urllib/request.py", line 1454, in open
>return getattr(self, name)(url)
>  File "/usr/lib/python3.1/urllib/request.py", line 1628, in open_http
>return self._open_generic_http(http.client.HTTPConnection, url, data)
>  File "/usr/lib/python3.1/urllib/request.py", line 1624, in
> _open_generic_http
>response.status, response.reason, response.msg, data)
>  File "/usr/lib/python3.1/urllib/request.py", line 1644, in http_error
>return self.http_error_default(url, fp, errcode, errmsg, headers)
>  File "/usr/lib/python3.1/urllib/request.py", line 1648, in
> http_error_default
>void = fp.read()
>  File "/usr/lib/python3.1/socket.py", line 214, in readinto
>return self._sock.recv_into(b)
> KeyboardInterrupt
>
> Can anyone tell me if this is a bug or expected behavior?
>
> 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
>



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


Re: Python default search paths

2010-10-19 Thread Jed Smith
On Tue, Oct 19, 2010 at 12:35 PM, Steven D'Aprano
 wrote:
> On Tue, 19 Oct 2010 06:25:30 -0700, swapnil wrote:
>> This is useful for embedding applications where it might be desired that
>> only user-defined paths are searched for modules.
>
> I doubt that very much. I expect that many things will break if Python
> can't find (e.g.) the sys module. But you might be lucky.

sys is a bad example, because it is built-in and always available[1],
even if the path is destroyed.

I have personally done what OP is trying to do. It is not only
possible (but interesting) to give Python access only to your own
modules. It's similar to working in C without libc, and is just as
feasible and doable. Running with -vv is very useful here, so you can
see what Python does behind the scenes--the default site scripts
actually import quite a bit before handing off to you, and even if
path is wiped, those will continue to work (i.e., os; go interactive,
import sys, sys.path = [], then try importing os and, say, cgi).

Python doesn't expect to run this way so there's a few things you have
to work around, but I expect there's more than a few apps that operate
just like this.

[1]: http://docs.python.org/library/sys.html

-- 
Jed Smith
j...@jedsmith.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyCharm

2010-10-19 Thread CoffeeKid
On Oct 15, 4:06 am, Kai Diefenbach  wrote:
> On 2010-10-13 23:36:31 +0200, Robert H said:

> It sucks.
>
> http://regebro.wordpress.com/2010/10/14/python-ide-code-completion-test
>
> Kai

Kai,

Your video is childish and silly.  A lot of IDE's use +
to invoke code completion.  You purposely did not use it and chose to
slap your keys and anger and confusion.  You should have said you like
Wing IDE better because it has popup code completion while PyCharm
uses a key stoke for it.

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


annoying CL echo in interactive python / ipython

2010-10-19 Thread kj



Under some parent shells, both my interactive python as well as
ipython, produce an unwanted echoing of the input line.  E.g.

>>> 1 + 1
1 + 1
2
>>>

What's worse, upon exiting the interactive python/ipython session,
the terminal is left in echo mode:

>>> 
% date 
date
Tue Oct 19 13:27:47 EDT 2010
% stty -echo
% date
Tue Oct 19 13:27:50 EDT 2010

It's basically the same story for ipython.

(If I run stty -echo before running either python or ipython, I
still get the echo when I'm in them.  So the problem is not a
pre-existing terminal setting.)

(As I said, this happens only under some shells (e.g. emacs shell),
so YMMV.)

Does anyone know how can I suppress this annoying feature?

TIA!

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


Re: pyqt4 Table Widget deleting c/c++ object

2010-10-19 Thread Andrew
On Oct 18, 2:26 pm, Andrew  wrote:
> I have two issues dealing with the table widget, though they may be
> interconnected. I'm not sure. Both delete the cell widgets off of my
> table but leave the rows, and then when I have the table update, it
> complains the c++ object has been deleted.
>
> # self.tableData.setCellWidget(rowCount, 0, trackItem)
> # RuntimeError: underlying C/C++ object has been deleted
>
> I have a list of a custom widget class that keeps track of several
> directories. Each class gets put into a row on the table. I have a set
> of radio buttons that will show me different views of the data: All,
> New, Done, Errors, Warnings.
> When I switch views, I clear my table, set the row count to 0, and
> then add back in only the widgets I want to see.
>
> Error 1:
> I load in the data initially, and then repopulate the table, and then
> re-size the window, instantly all listed rows are cleared, but the
> rows stay. This only happened on the diagonal re-size (bottom left
> corner); not the up and down, or side to side re-size. Attempting to
> repopulate the table, resulted in: underlying C/C++ object has been
> deleted. Though it will put in the correct number of rows required.
>
> Everything worked fine as long as I did not re-size the window.
>
> Error 2:
> I load in the data initially, and then repopulate the table, the table
> clears and then nothing happens. No error messages or even visible
> rows. After several more repopulates it with either crash or tell me:
> underlying C/C++ object has been deleted.
>
> I had error 1 two days ago, then without changing the code, I now get
> error 2. I do not have to re-size the window for it to break now.
>
> I am using python 2.7 with PyQt4 4.7.7
>
> Thanks for any insight,
> Andrew

Here is a working example of what I'm describing above.

http://dl.dropbox.com/u/11715751/trackSetLoader.rar

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


Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Jed Smith
On Tue, Oct 19, 2010 at 1:37 PM, kj  wrote:

> % stty -echo

That doesn't do what you think it does.

-- 
Jed Smith
j...@jedsmith.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO and game design questions

2010-10-19 Thread Ian Kelly
On Tue, Oct 19, 2010 at 5:37 AM, Dave Angel  wrote:

>  On 2:59 PM, dex wrote:
>
>> Using strong references, I have to remove room B from list of rooms,
>> and also remove door to room B, as it holds reference to room B. To do
>> that, I have to keep list of doors that lead to room B.
>>
>> Using weak references, I don't have to worry about removing all doors
>> to room B. They all now have a dead reference, which better models
>> actual situation. If part of mine collapses, or if a module on space
>> station is destroyed, the passage to that location does not magically
>> vanish - it's just obstructed.
>>
>> Can you please tell me if there's something wrong with my reasoning?
>>
>>  Simply replace room B with a "destroyed room" object.  That can be quite
> small, and you only need one, regardless of how many rooms are thus
> eliminated.
>

How does this avoid the problem of having to keep a list of doors that lead
to room B?  You can't just replace one object with another.  You would have
to replace every reference to B with a reference to the new object.  This is
no simpler than deleting the references or replacing them with None.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO and game design questions

2010-10-19 Thread Carl Banks
On Oct 19, 1:19 am, dex  wrote:
> > I'm not sure if it's a good idea to let an item disappear from your
> > inventory by a weak reference disappearing.  It seems a little shaky
> > to not know where your objects are being referenced, but that's yout
> > decision.
>
> OK, imagine a MUD, where players can "dig out" new rooms. Room A has a
> door that holds reference to newly created room B. By "using" a door,
> player is transported to room B. At later time someone destroys room
> B.
>
> Using strong references, I have to remove room B from list of rooms,
> and also remove door to room B, as it holds reference to room B. To do
> that, I have to keep list of doors that lead to room B.
>
> Using weak references, I don't have to worry about removing all doors
> to room B. They all now have a dead reference, which better models
> actual situation. If part of mine collapses, or if a module on space
> station is destroyed, the passage to that location does not magically
> vanish - it's just obstructed.
>
> Can you please tell me if there's something wrong with my reasoning?

Well, you're talking about particulars here whereas I am speaking in
general.  If something is "questionable" or even "bad" in general it
doesn't mean there are no particular cases for it.

Generally speaking: in a game there's presumably some conservation of
objects.  If you drop an item, does it disappear, or does it become an
object of the room?  Weak referencing won't help you in the latter
case because you have to take care of references at both ends anyway.
That's what I mean by shaky: it lets you forget about half of the
transaction, which might not be the best thing.  YMMV


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


Re: PyCharm

2010-10-19 Thread Albert Hopkins
On Tue, 2010-10-19 at 10:05 -0700, CoffeeKid wrote:
> Your video is childish

When you have someone called "Kid" calling you childish... that's pretty
low.

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


Script to capture stderr of subprocess

2010-10-19 Thread jslow...@gmail.com
We have a lot of curses-based console applications running on linux. I
would like to write a wrapper script that notifies us if the
application terminates unexpectedly. With my first, obviously naive
attempt, the subprocess dies instantly. STDIN and STDOUT will need to
connect to the terminal of course, since these are complex keyboard-
based applications. STDERR and the return code is what I would like to
capture. Actually, if it was possible, it would be nice to capture all
the bytes going between stdin and stdout in a file as well for
debugging purposes.

Could someone point me in the right direction here? I have a feeling
I"m missing something fundamental about how the Unix processes and
file descriptors work.

import os
import subprocess
import sys

cmd = ['/usr/local/bin/runcobol'] + sys.argv[1:]
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
proc.communicate()

if proc.returncode:
f = file('/tmp/boom.txt', 'w')
f.write(" ".join(cmd) + " returned unexpectedly.\n")
f.write(proc.stderr.read(-1))
f.close()
sys.exit(proc.returncode)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deferring a function call

2010-10-19 Thread Werner Thie
For me nothing beats using twisted ( http://www.twistedmatrix.com ) with 
its clean implementation of deferreds and a host of other useful things 
for simulations besides being the 'Swiss Army Knife' of networking in 
Python. If you throw in stackless ( http://www.stackless.com ) 
simulations with extremely high counts of participants and/or fine 
granularity distributed across multiple machines are fun to write, 
operate and maintain.


Werner


On 10/18/10 6:21 PM, TomF wrote:

I'm writing a simple simulator, and I want to schedule an action to
occur at a later time. Basically, at some later point I want to call a
function f(a, b, c). But the values of a, b and c are determined at the
current time.

One way way to do this is to keep a list of entries of the form [[TIME,
FN, ARGS]...] and at simulated time TIME do: apply(FN, ARGS)
Aside from the fact that apply is deprecated, it seems like there should
be a cleaner (possibly more Pythonic) way to do this. Ideas?

-Tom



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


Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread kj
In  Jed Smith 
 writes:

>On Tue, Oct 19, 2010 at 1:37 PM, kj  wrote:

>> % stty -echo

>That doesn't do what you think it does.

Gee, thanks.  That really helped.  I'll go talk to my guru now,
and meditate over this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Unicode questions

2010-10-19 Thread Tobiah
I've been reading about the Unicode today.
I'm only vaguely understanding what it is
and how it works.

Please correct my understanding where it is lacking. 
Unicode is really just a database of character information
such as the name, unicode section, possible 
numeric value etc.  These points of information
are indexed by standard, never changing numeric
indexes, so that 0x2CF might point to some 
character information set, that all the world
can agree on.  The actual image that gets 
displayed in response to the integer is generally
assigned and agreed upon, but it is up to the
software responding to the unicode value to define
and generate the actual image that will represent that
character.

Now for the mysterious encodings.  There is the UTF-{8,16,32}
which only seem to indicate what the binary representation
of the unicode character points is going to be.  Then there
are 100 or so other encoding, many of which are language
specific.  ASCII encoding happens to be a 1-1 mapping up
to 127, but then there are others for various languages etc.
I was thinking maybe this special case and the others were lookup 
mappings, where a
particular language user could work with characters perhaps
in the range of 0-255 like we do for ASCII, but then when
decoding, to share with others, the plain unicode representation
would be shared?  Why can't we just say "unicode is unicode"
and just share files the way ASCII users do.  Just have a huge
ASCII style table that everyone sticks to.  Please enlighten
my vague and probably ill-formed conception of this whole thing.

Thanks,

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


Re: Script to capture stderr of subprocess

2010-10-19 Thread Arnaud Delobelle
"jslow...@gmail.com"  writes:

> We have a lot of curses-based console applications running on linux. I
> would like to write a wrapper script that notifies us if the
> application terminates unexpectedly. With my first, obviously naive
> attempt, the subprocess dies instantly. STDIN and STDOUT will need to
> connect to the terminal of course, since these are complex keyboard-
> based applications. STDERR and the return code is what I would like to
> capture. Actually, if it was possible, it would be nice to capture all
> the bytes going between stdin and stdout in a file as well for
> debugging purposes.
>
> Could someone point me in the right direction here? I have a feeling
> I"m missing something fundamental about how the Unix processes and
> file descriptors work.
>
> import os
> import subprocess
> import sys
>
> cmd = ['/usr/local/bin/runcobol'] + sys.argv[1:]
> proc = subprocess.Popen(cmd, stderr=subprocess.PIPE)
> proc.communicate()

If you want to capture what was sent to stderr, (which you probably do,
as you opened the process with stderr=subprocess.PIPE) you need to do
this:

stdoutdata, stderrdata = proc.communicate()

>
> if proc.returncode:
> f = file('/tmp/boom.txt', 'w')
> f.write(" ".join(cmd) + " returned unexpectedly.\n")
> f.write(proc.stderr.read(-1))

Now use this instead:

  f.write(stderrdata)

> f.close()
> sys.exit(proc.returncode)

Now it should work.  After you use proc.communicate(), proc.stderr has
been read and there is nothing left on it!  Its content has been put in
the data returned by proc.communicate as shown above.

HTH

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


Re: Starting Python in XP Pro

2010-10-19 Thread Grant Andrew
1. Okay, I can open the interpreter and do math.  If only I needed the
answer to 6*7 I'd be great.  But, to your point, Python is installed and
working.

2.  When I went to the shortcut and hit properties, the path was

Target: C:\Python26\Lib\idlelib\idle.bat
Start in: C:\Python26\

I cd'd to C:\Python26\ at the command prompt and ran Lib\idlelib\idle.bat.

It just reprints C:\Python26\ with no error or message.  Looks like this:

C:\Python26>Lib\idlelib\idle.bat
C:\Python26>

3.  I created a simple file in Wordpad that prints a few lines.  It is
called Print.py but I'm not sure where the 'code' folder is.  I'm not
familiar enough with Python to locate a file from the Interpreter and open
it.

4.  I also tried editing the PATH variable, which did have both versions in
it, but with no success - same error.


Thanks for your help...

Grant


On Sun, Oct 17, 2010 at 4:17 AM, Dave Angel  wrote:

>  On 10/16/2010 11:27 PM, Grant Andrew wrote:
>
>> I hear that...God knows if I had a more complete question, I'd type it -
>> basically, when I click the IDLE GUI icon from the Start Menu, there is a
>> flash of a command prompt loading, then nothing happens.
>>
>> I've tried a number of things at the command prompt over the last two
>> weeks
>> and five versions.  I went to ActiveState because I was thinking I had not
>> configured something properly in the Python.org versions, however, the
>> behavior is the same.
>>
>> I ran C:\>C:\python26\lib\idlelib\idle.py at the command prompt and that
>> returned:
>>
>> 
>>
>
> You probably need to start with fundamentals.  That means using a command
> prompt.  As you've noticed, many times a program started from the start menu
> doesn't leave its command window open long enough to read the messages.
>
> I'm afraid I can't really help with Idle;  I've never tried using it, till
> today.  When I start if from ActiveState's menu, it flashes and exits for me
> as well.  Perhaps because we both have Thinkpads.  I notice the IBMTools
> directory in your traceback.  Perhaps there's an old version of TCL there
> that's interfering with the one Idle needs.  To start debugging it, figure
> out what the menu shortcut is doing, and do it yourself from a command
> window.  In my case,  StartIdle-right-click->properties->shortcut shows me:
>
> Target  C:\Progfiles\ActivePython26\Lib\idlelib\idle.bat
> Start in:  c:\progfiles\activePython26
>
> So you CD to the latter directory (or rather, to your equivalent one), and
> type lib\idlelib\idle.bat
>
> When I do that, I get an error message: "IDLE's subprocess didn't make
> connection.  Either IDLE can't start a subprocess or personal firewall
> software is blocking."
>
> But let's get your python itself working.  ActivePython's install adds
> itself to your path, so you should be able to just type
> python
>  or   python26
>
> at the C: prompt, and get a Python interpreter prompt.  Then do something
> like
> >>> print 3*4
>
> to see if it's working.
>
> Next, write a small xxx.py  program, in your code directory, and NOT in the
> Python install directory.  From that code directory, type
> python  xxx.py
>
> or whatever you called it.  Let us know if it works.
>
> Only then should you worry about associations.  You can check them with
> assoc and ftype, but people tell me that's not reliable if there is more
> than one user on the machine, or specifically if you have created
> user-specific associations, which take precedence over the ones in assoc and
> ftype.
>
> DaveA
>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Jed Smith
On Tue, Oct 19, 2010 at 2:35 PM, kj  wrote:
> In  Jed Smith 
>  writes:
>
>>On Tue, Oct 19, 2010 at 1:37 PM, kj  wrote:
>
>>> % stty -echo
>
>>That doesn't do what you think it does.
>
> Gee, thanks.  That really helped.  I'll go talk to my guru now,
> and meditate over this.

You're right, I could have been more clear. I was nudging you to go
read the man page of stty(1), but since you won't and want to get
snarky instead, I will for you:

> echo (-echo)
> Echo back (do not echo back) every character typed.

I'm going to guess that the percent sign in your prompt indicates that
you're using zsh(1).  With my minimally-customized zsh, the echo
option is reset every time the prompt is displayed. That means you can
type "stty -echo", push CR, the echo option is cleared, then zsh
immediately sets it before you get to type again. Therefore, you
cannot observe its *actual* behavior, and you assumed it had something
to do with what you're after. Am I on the right track?

Start bash, run stty -echo, then type. That is the ACTUAL behavior of
that option.

As to your original issue, your readline configuration is most likely
the problem. I consider it very unlikely that Python has anything to
do with it. I have no idea why fiddling with your terminal affects
readline, but there is a lot that I do not understand about readline.

-- 
Jed Smith
j...@jedsmith.org
-- 
http://mail.python.org/mailman/listinfo/python-list


proper way to add data dir in buit distribution

2010-10-19 Thread Auré Gourrier
Hi all,

Once again I turn to this list for help.
I'm trying to build a ditribution for my python package (Python 2.4).
The package has the following structure:

root
   |- __init__.py
   |- module1.py
   |- ...
   |-moduleN.py
   |-subpackage1.py
|- __init__.py
|- module1.py
|- ...
|- moduleN.py
   |-subpackage2.py
|- __init__.py
|- module1.py
|- ...
|- moduleN.py 
|- datadir
 |- data1.ext
 |- ...
 |- dataN.ext

My setup script looks like:

---
from distutils.core import setup

setup(name='root',
  version='0.1.0',
  modemetadata = 'metadatavalue'
  package_dir = {'root': ''},
  packages = ['root',
  'subpackage1',
  'subpackage2'])


My problem is including the data contained in root/subpackage2/dir in the 
distribution.

I tried using the package_data keyword but couldn't get it right (?). There are 
quite a few posts around and they are very contradictory as to whether or not 
this works... sic !

Then, I wrote a script MANIFEST.in dile containing:

include root/subpackage2/dir/*

This worked fine for creating the source distribution for Win32 (.zip) using:

python setup.py sdist

but not for the (Win32) build distribution:

python setup.py bdist_wininst

Can anyone point me in the right direction ? Any help would be much appreciated 
!

Cheers,

Auré



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


Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith  writes:

> On Tue, Oct 19, 2010 at 1:37 PM, kj  wrote:
>
>> % stty -echo
>
> That doesn't do what you think it does.

Really?  Turning off tty echo sounds exactly like what he wants.

Emacs shell echoes characters for you, just like interactive shells do.
When you press enter, the characters are sent to a pseudo-terminal, and
if the pty echoes them, the input string will be printed twice, as the
OP observes.  It is hard to tell what is going wrong in his setup and
whether it has anything to do with tty echoing, but it's a valid guess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode questions

2010-10-19 Thread Petite Abeille

On Oct 19, 2010, at 9:02 PM, Tobiah wrote:

> Please enlighten my vague and probably ill-formed conception of this whole 
> thing.

Hmmm... is there a question hidden somewhere in there or is it more open ended 
in nature? :)

In the meantime...

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know 
About Unicode and Character Sets (No Excuses!)
http://www.joelonsoftware.com/articles/Unicode.html

Characters vs. Bytes
http://www.tbray.org/ongoing/When/200x/2003/04/26/UTF
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: annoying CL echo in interactive python / ipython

2010-10-19 Thread Hrvoje Niksic
Jed Smith  writes:

>> echo (-echo)
>> Echo back (do not echo back) every character typed.
>
> I'm going to guess that the percent sign in your prompt indicates that
> you're using zsh(1).  With my minimally-customized zsh, the echo
> option is reset every time the prompt is displayed. That means you can
> type "stty -echo", push CR, the echo option is cleared, then zsh
> immediately sets it before you get to type again.

But are you running zsh in an emacs shell window?  Emacs shell is not a
terminal emulator, it lets emacs do the editing, and only sends it to
the shell when enter is pressed.  To avoid clashing with readline and
equivalent (ZLE in case of zsh), emacs presents itself as a dumb
terminal, which should make zsh turn ZLE off.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode questions

2010-10-19 Thread Hrvoje Niksic
Tobiah  writes:

> would be shared?  Why can't we just say "unicode is unicode"
> and just share files the way ASCII users do.  Just have a huge
> ASCII style table that everyone sticks to.

I'm not sure that I understand you correctly, but UCS-2 and UCS-4
encodings are that kind of thing.  Many people prefer UTF-8 because of
convenient backward compatibility with ASCII (and space economy when
dealing with mostly-ascii text).
-- 
http://mail.python.org/mailman/listinfo/python-list


pylint -- should I just ignore it sometimes?

2010-10-19 Thread Seebs
So, I'm messing around with pylint.  Quite a lot of what it says
is quite reasonable, makes sense to me, and all that.

There's a few exceptions.

One:  I am a big, big, fan of idiomatic short names where appropriate.
For instance:
catch , e:
I don't want a long, verbose, name -- "e" is about as much in need of
a long and descriptive name as the stereotypical "i" one would use as
a loop index (in a language without iterators).  Should I just ignore
that, or is it really more Pythonic to say something like:
catch KeyError, 
exception_resulting_from_the_use_of_a_key_not_defined_for_the_dictionary_in_which_it_was_looked_up:

Secondly:  I am getting a couple of hits on things like "Too many instance
attributes (8/7) or "Too many branches (14/12)".  In the cases in question,
it doesn't seem to me that the number of instance attributes is particularly
devastatingly complicated, because the instances in question are, by design,
sort of data stores; they carry a handful of precomputed results that are
then reused to populate templates.

So am I going to be laughed out of the room if I just let a class have
eight instance attributes, or use a short name for a 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: Starting Python in XP Pro

2010-10-19 Thread Sridhar Ratnakumar
Hi Grant,

Typing the following opens IDLE (albeit after a short delay; the command will 
immediately return regardless) for me:

  C:\> C:\Python26\lib\idlelib\idle.bat

IDLE is also installed in the Start Menu for ActivePython.

You need at least ActivePython 2.6.6.15 or 2.7.0.2 for this to work.

-srid

On 2010-10-19, at 12:06 PM, Grant Andrew wrote:

> 1. Okay, I can open the interpreter and do math.  If only I needed the answer 
> to 6*7 I'd be great.  But, to your point, Python is installed and working.
> 
> 2.  When I went to the shortcut and hit properties, the path was 
> 
> Target: C:\Python26\Lib\idlelib\idle.bat
> Start in: C:\Python26\
> 
> I cd'd to C:\Python26\ at the command prompt and ran Lib\idlelib\idle.bat.
> 
> It just reprints C:\Python26\ with no error or message.  Looks like this:
> 
> C:\Python26>Lib\idlelib\idle.bat
> C:\Python26>
> 
> 3.  I created a simple file in Wordpad that prints a few lines.  It is called 
> Print.py but I'm not sure where the 'code' folder is.  I'm not familiar 
> enough with Python to locate a file from the Interpreter and open it.  
> 
> 4.  I also tried editing the PATH variable, which did have both versions in 
> it, but with no success - same error.  
> 
> 
> Thanks for your help...
> 
> Grant
> 
> 
> On Sun, Oct 17, 2010 at 4:17 AM, Dave Angel  wrote:
>  On 10/16/2010 11:27 PM, Grant Andrew wrote:
> I hear that...God knows if I had a more complete question, I'd type it -
> basically, when I click the IDLE GUI icon from the Start Menu, there is a
> flash of a command prompt loading, then nothing happens.
> 
> I've tried a number of things at the command prompt over the last two weeks
> and five versions.  I went to ActiveState because I was thinking I had not
> configured something properly in the Python.org versions, however, the
> behavior is the same.
> 
> I ran C:\>C:\python26\lib\idlelib\idle.py at the command prompt and that
> returned:
> 
> 
> 
> You probably need to start with fundamentals.  That means using a command 
> prompt.  As you've noticed, many times a program started from the start menu 
> doesn't leave its command window open long enough to read the messages.
> 
> I'm afraid I can't really help with Idle;  I've never tried using it, till 
> today.  When I start if from ActiveState's menu, it flashes and exits for me 
> as well.  Perhaps because we both have Thinkpads.  I notice the IBMTools 
> directory in your traceback.  Perhaps there's an old version of TCL there 
> that's interfering with the one Idle needs.  To start debugging it, figure 
> out what the menu shortcut is doing, and do it yourself from a command 
> window.  In my case,  StartIdle-right-click->properties->shortcut shows me:
> 
> Target  C:\Progfiles\ActivePython26\Lib\idlelib\idle.bat
> Start in:  c:\progfiles\activePython26
> 
> So you CD to the latter directory (or rather, to your equivalent one), and 
> type lib\idlelib\idle.bat
> 
> When I do that, I get an error message: "IDLE's subprocess didn't make 
> connection.  Either IDLE can't start a subprocess or personal firewall 
> software is blocking."
> 
> But let's get your python itself working.  ActivePython's install adds itself 
> to your path, so you should be able to just type
> python
>  or   python26
> 
> at the C: prompt, and get a Python interpreter prompt.  Then do something like
> >>> print 3*4
> 
> to see if it's working.
> 
> Next, write a small xxx.py  program, in your code directory, and NOT in the 
> Python install directory.  From that code directory, type
> python  xxx.py
> 
> or whatever you called it.  Let us know if it works.
> 
> Only then should you worry about associations.  You can check them with assoc 
> and ftype, but people tell me that's not reliable if there is more than one 
> user on the machine, or specifically if you have created user-specific 
> associations, which take precedence over the ones in assoc and ftype.
> 
> DaveA
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Unicode questions

2010-10-19 Thread Chris Rebert
On Tue, Oct 19, 2010 at 12:02 PM, Tobiah  wrote:
> I've been reading about the Unicode today.
> I'm only vaguely understanding what it is
> and how it works.

Petite Abeille already pointed to Joel's excellent primer on the
subject; I can only second their endorsement of his article.

> Please correct my understanding where it is lacking.

> Now for the mysterious encodings.  There is the UTF-{8,16,32}
> which only seem to indicate what the binary representation
> of the unicode character points is going to be.  Then there
> are 100 or so other encoding, many of which are language
> specific.  ASCII encoding happens to be a 1-1 mapping up
> to 127, but then there are others for various languages etc.
> I was thinking maybe this special case and the others were lookup
> mappings, where a
> particular language user could work with characters perhaps
> in the range of 0-255 like we do for ASCII, but then when
> decoding, to share with others, the plain unicode representation
> would be shared?

There is no such thing as "plain Unicode representation". The closest
thing would be an abstract sequence of Unicode codepoints (ala
Python's `unicode` type), but this is way too abstract to be used for
sharing/interchange, because storing anything in a file or sending it
over a network ultimately involves serialization to binary, which is
not directly defined for such an abstract representation (Indeed, this
is exactly what encodings are: mappings between abstract codepoints
and concrete binary; the problem is, there's more than one of them).

Python's `unicode` type (and analogous types in other languages) is a
nice abstraction, but at the C level it's actually using some
(implementation-defined, IIRC) encoding to represent itself in memory;
and so when you leave Python, you also leave this implicit, hidden
choice of encoding behind and must instead be quite explicit.

>  Why can't we just say "unicode is unicode"
> and just share files the way ASCII users do.

Because just "Unicode" itself is not a scheme for encoding characters
as a stream of binary. Unicode /does/ define many encodings, and these
encodings are such schemes; /but/ none of them is *THE* One True
Unambiguous Canonical "Unicode" encoding scheme. Hence, one must be
specific and specify "UTF-8", or "UTF-32", or whatever.

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


Re: Unicode questions

2010-10-19 Thread Tobiah
> There is no such thing as "plain Unicode representation". The closest
> thing would be an abstract sequence of Unicode codepoints (ala Python's
> `unicode` type), but this is way too abstract to be used for
> sharing/interchange, because storing anything in a file or sending it
> over a network ultimately involves serialization to binary, which is not
> directly defined for such an abstract representation (Indeed, this is
> exactly what encodings are: mappings between abstract codepoints and
> concrete binary; the problem is, there's more than one of them).

Ok, so the encoding is just the binary representation scheme for
a conceptual list of unicode points.  So why so many?  I get that
someone might want big-endian, and I see the various virtues of
the UTF strains, but why isn't a handful of these representations
enough?  Languages may vary widely but as far as I know, computers
really don't that much.  big/little endian is the only problem I
can think of.  A byte is a byte.  So why so many encoding schemes?
Do some provide advantages to certain human languages?

Thanks,

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


Re: Unicode questions

2010-10-19 Thread Petite Abeille

On Oct 19, 2010, at 10:31 PM, Tobiah wrote:

> So why so many encoding schemes?

http://en.wikipedia.org/wiki/Space-time_tradeoff

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


Re: Unicode questions

2010-10-19 Thread Chris Rebert
On Tue, Oct 19, 2010 at 1:31 PM, Tobiah  wrote:
>> There is no such thing as "plain Unicode representation". The closest
>> thing would be an abstract sequence of Unicode codepoints (ala Python's
>> `unicode` type), but this is way too abstract to be used for
>> sharing/interchange, because storing anything in a file or sending it
>> over a network ultimately involves serialization to binary, which is not
>> directly defined for such an abstract representation (Indeed, this is
>> exactly what encodings are: mappings between abstract codepoints and
>> concrete binary; the problem is, there's more than one of them).
>
> Ok, so the encoding is just the binary representation scheme for
> a conceptual list of unicode points.  So why so many?  I get that
> someone might want big-endian, and I see the various virtues of
> the UTF strains, but why isn't a handful of these representations
> enough?  Languages may vary widely but as far as I know, computers
> really don't that much.  big/little endian is the only problem I
> can think of.  A byte is a byte.  So why so many encoding schemes?
> Do some provide advantages to certain human languages?

UTF-8 has the virtue of being backward-compatible with ASCII.

UTF-16 has all codepoints in the Basic Multilingual Plane take up
exactly 2 bytes; all others take up 4 bytes. The Unicode people
originally thought they would only include modern scripts, so 2 bytes
would be enough to encode all characters. However, they later
broadened their scope, thus the complication of "surrogate pairs" was
introduced.

UTF-32 has *all* Unicode codepoints take up exactly 4 bytes. This
slightly simplifies processing, but wastes a lot of space for e.g.
English texts.

And then there are a whole bunch of national encodings defined for
backward compatibility, but they typically only encode a portion of
all the Unicode codepoints.

More info: http://en.wikipedia.org/wiki/Comparison_of_Unicode_encodings

Cheers,
Chris
--
Essentially, blame backward compatibility and finite storage space.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-10-19 Thread Steven D'Aprano
On Tue, 19 Oct 2010 19:57:36 +, Seebs wrote:

> So, I'm messing around with pylint.  Quite a lot of what it says is
> quite reasonable, makes sense to me, and all that.
> 
> There's a few exceptions.
> 
> One:  I am a big, big, fan of idiomatic short names where appropriate.
> For instance:
>   catch , e:

That would be except, not catch.


> I don't want a long, verbose, name -- "e" is about as much in need of a
> long and descriptive name as the stereotypical "i" one would use as a
> loop index (in a language without iterators).  Should I just ignore
> that, or is it really more Pythonic to say something like:
>   catch KeyError,
>   
exception_resulting_from_the_use_of_a_key_not_defined_for_the_dictionary_in_which_it_was_looked_up:


Well, that name is 98 characters, which means it's impossible to use it 
without exceeding the 78 or 79 character per line limit, so I guess that 
since there's no other alternative between 1 character and 98, you'll 
just have to break down and ignore pylint.


> So am I going to be laughed out of the room if I just let a class have
> eight instance attributes, or use a short name for a caught exception?

Unfortunately, pylint is always right. Without exception. Like Microsoft 
Word's grammar checker. As we all know, computers are much more capable 
of capturing fine and subtle distinctions of meaning than we are, so we 
should always follow their advice.

*wink*


Perhaps you should have a read of PEP 8, the recommended style guide.

http://www.python.org/dev/peps/pep-0008/

Take particular note of what it says about inconsistency.



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


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

2010-10-19 Thread Alexander Kapps

On 19.10.2010 21:57, Seebs wrote:

So, I'm messing around with pylint.  Quite a lot of what it says
is quite reasonable, makes sense to me, and all that.

There's a few exceptions.

One:  I am a big, big, fan of idiomatic short names where appropriate.
For instance:
catch, e:
I don't want a long, verbose, name -- "e" is about as much in need of
a long and descriptive name as the stereotypical "i" one would use as
a loop index (in a language without iterators).  Should I just ignore
that, or is it really more Pythonic to say something like:
catch KeyError, 
exception_resulting_from_the_use_of_a_key_not_defined_for_the_dictionary_in_which_it_was_looked_up:


catch KeyError, exc
catch KeyError, exception


Secondly:  I am getting a couple of hits on things like "Too many instance
attributes (8/7) or "Too many branches (14/12)".  In the cases in question,
it doesn't seem to me that the number of instance attributes is particularly
devastatingly complicated, because the instances in question are, by design,
sort of data stores; they carry a handful of precomputed results that are
then reused to populate templates.

So am I going to be laughed out of the room if I just let a class have
eight instance attributes, or use a short name for a caught exception?

-s


Pylint gives *hints* about *possible* problems or bad style. I 
personally think it's good practice to take care of all of them and 
carefully think if you or pylint is right. Once you decided that you 
are right, you can configure pylint to not complain about certain 
aspects. See man pylint for more.

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


get python bit version as in (32 or 64)

2010-10-19 Thread Vincent Davis
How do I get the bit version of the installed python. In my case, osx
python2.7 binary installed. I know it runs 64 bt as I can see it in
activity monitor. but how do I ask python?
sys.version
'2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 5493)]'

-- 
Thanks
Vincent Davis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get python bit version as in (32 or 64)

2010-10-19 Thread Philip Semanchuk

On Oct 19, 2010, at 5:18 PM, Vincent Davis wrote:

> How do I get the bit version of the installed python. In my case, osx
> python2.7 binary installed. I know it runs 64 bt as I can see it in
> activity monitor. but how do I ask python?
> sys.version
> '2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 5493)]'


I don't think there's an official way to do this. The canonical way appears to 
be to test the value of sys.maxint and see whether or not it is a 32- or 64-bit 
long.

See here for more details:

http://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode



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


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

2010-10-19 Thread Shawn Milochik
Just to be pedantic (or maybe even helpful), the use of the comma
after the exception is deprecated in favor of 'as.'

So:

except ValueError as ex:

not:

except ValueError, ex:

I don't know how far back in Python versions this syntax reaches, but
if yours supports it then it's probably a good idea to get into the
habit.
This way, you can catch multiple exceptions in a tuple without
confusing the interpreter:

except ValueError, IndexError as ex:

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


Re: pyqt4 Table Widget deleting c/c++ object

2010-10-19 Thread David Boddie
On Monday 18 October 2010 23:26, Andrew wrote:

> I have two issues dealing with the table widget, though they may be
> interconnected. I'm not sure. Both delete the cell widgets off of my
> table but leave the rows, and then when I have the table update, it
> complains the c++ object has been deleted.
> 
> # self.tableData.setCellWidget(rowCount, 0, trackItem)
> # RuntimeError: underlying C/C++ object has been deleted

This is because you pass your widgets to this method and later ask
the table to clear the contents of the table. When it does so, it
deletes the underlying widgets, leaving only Python wrappers.

The documentation mentions that the table takes ownership of the
widget:

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtablewidget.html#setCellWidget

> I have a list of a custom widget class that keeps track of several
> directories. Each class gets put into a row on the table. I have a set
> of radio buttons that will show me different views of the data: All,
> New, Done, Errors, Warnings.
> When I switch views, I clear my table, set the row count to 0, and
> then add back in only the widgets I want to see.
> 
> Error 1:
> I load in the data initially, and then repopulate the table, and then
> re-size the window, instantly all listed rows are cleared, but the
> rows stay. This only happened on the diagonal re-size (bottom left
> corner); not the up and down, or side to side re-size. Attempting to
> repopulate the table, resulted in: underlying C/C++ object has been
> deleted. Though it will put in the correct number of rows required.
> 
> Everything worked fine as long as I did not re-size the window.

This may only be a symptom of the behaviour and not a guarantee that
the code was working correctly up until the point when the resize
occurred.

> Error 2:
> I load in the data initially, and then repopulate the table, the table
> clears and then nothing happens. No error messages or even visible
> rows. After several more repopulates it with either crash or tell me:
> underlying C/C++ object has been deleted.
> 
> I had error 1 two days ago, then without changing the code, I now get
> error 2. I do not have to re-size the window for it to break now.

I recommend that you create a list of non-widget data structures in
your parsePath() method and create widgets on the fly in your addToTable()
method. If you need to retain information when you repopulate the table
then update the data structures that correspond to the widgets just before
you clear the table.

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


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

2010-10-19 Thread Seebs
On 2010-10-19, Steven D'Aprano  wrote:
> On Tue, 19 Oct 2010 19:57:36 +, Seebs wrote:
>> One:  I am a big, big, fan of idiomatic short names where appropriate.
>> For instance:
>>  catch , e:

> That would be except, not catch.

Er, yeah, that.

> Well, that name is 98 characters, which means it's impossible to use it 
> without exceeding the 78 or 79 character per line limit, so I guess that 
> since there's no other alternative between 1 character and 98, you'll 
> just have to break down and ignore pylint.

:)

> Perhaps you should have a read of PEP 8, the recommended style guide.

Will do.

-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: get python bit version as in (32 or 64)

2010-10-19 Thread Hexamorph

On 19.10.2010 23:18, Vincent Davis wrote:

How do I get the bit version of the installed python. In my case, osx
python2.7 binary installed. I know it runs 64 bt as I can see it in
activity monitor. but how do I ask python?
sys.version
'2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 5493)]'



In [1]: import platform

In [2]: platform.architecture()
Out[2]: ('32bit', 'ELF')

In [3]:

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


Re: OO and game design questions

2010-10-19 Thread Terry Reedy

On 10/19/2010 1:46 PM, Ian Kelly wrote:

On Tue, Oct 19, 2010 at 5:37 AM, Dave Angel mailto:da...@ieee.org>> wrote:

  On 2:59 PM, dex wrote:

Using strong references, I have to remove room B from list of rooms,
and also remove door to room B, as it holds reference to room B.
To do
that, I have to keep list of doors that lead to room B.

Using weak references, I don't have to worry about removing all
doors
to room B. They all now have a dead reference, which better models
actual situation. If part of mine collapses, or if a module on space
station is destroyed, the passage to that location does not
magically
vanish - it's just obstructed.

Can you please tell me if there's something wrong with my reasoning?

Simply replace room B with a "destroyed room" object.  That can be
quite small, and you only need one, regardless of how many rooms are
thus eliminated.


How does this avoid the problem of having to keep a list of doors that
lead to room B?  You can't just replace one object with another.  You
would have to replace every reference to B with a reference to the new
object.  This is no simpler than deleting the references or replacing
them with None.


One should rather *change* (not replace) the room into a 'destroyed 
room' or 'collapsed passage' or whatever, that cannot be entered. The 
keeps the room around but allows it to be repaired, rebuilt, cleared, or 
whatever.


--
Terry Jan Reedy

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


Re: get python bit version as in (32 or 64)

2010-10-19 Thread Vincent Davis
On Tue, Oct 19, 2010 at 3:29 PM, Philip Semanchuk  wrote:
>
> On Oct 19, 2010, at 5:18 PM, Vincent Davis wrote:
>
>> How do I get the bit version of the installed python. In my case, osx
>> python2.7 binary installed. I know it runs 64 bt as I can see it in
>> activity monitor. but how do I ask python?
>> sys.version
>> '2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 
>> 5493)]'
>
>
> I don't think there's an official way to do this. The canonical way appears 
> to be to test the value of sys.maxint and see whether or not it is a 32- or 
> 64-bit long.
>
> See here for more details:
>
> http://stackoverflow.com/questions/1405913/how-do-i-determine-if-my-python-shell-is-executing-in-32bit-or-64bit-mode.

Great thanks
Vincent
>
>
>
> Cheers
> Philip
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Thanks
Vincent Davis
720-301-3003
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-10-19 Thread Seebs
On 2010-10-19, Shawn Milochik  wrote:
> Just to be pedantic (or maybe even helpful), the use of the comma
> after the exception is deprecated in favor of 'as.'

Not in code that has to run on older Pythons.

I'm pretty sure I have to work with everything from 2.4 to 2.6 or so.

That reminds me, though.  Speaking of deprecation, I have:
from string import Template
(see PEP 292 or so?), and pylint says "Uses of a deprecated module 'string'",
but I don't know of a way to get Template except by doing that.

-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: Reading Outlook .msg file using Python

2010-10-19 Thread John Henry
On Oct 17, 4:45 am, Tim Golden  wrote:
> On 17/10/2010 6:39 AM, John Henry wrote:
>
>
>
> > On Oct 12, 10:31 am, Tim Golden  wrote:
> >> On 12/10/2010 4:59 PM, John Henry wrote:
>
> >>> According to:
>
> >>>http://support.microsoft.com/kb/813745
>
> >>> I need to reset my Outlook registry keys.  Unfortunately, I don't have
> >>> my Office Install CD with me.  This would have to wait.
>
> >> Thanks for the information; I'm keen to see if you're able
> >> to use the solution I posted once this fix is in place.
>
> >> TJG
>
> > Okay, after fixing the Outlook reg entries as described above, I am
> > able to go further.  Now, the code stops at:
>
> > message = mapi.OpenIMsgOnIStg (mapi_session, None, storage, None, 0,
> > mapi.MAPI_UNICODE)
>
> > with an error message:
>
> > pywintypes.com_error: (-2147221242, 'OLE error 0x80040106', None,
> > None)
>
> Strange. That's UNKNOWN_FLAGS. Try the call without the MAPI_UNICODE,
> ie make the last param zero. Maybe there's something with Outlook 2002...
> I've never tried it myself.
>
> TJG

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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading Outlook .msg file using Python

2010-10-19 Thread John Henry
On Oct 17, 4:45 am, Tim Golden  wrote:
> On 17/10/2010 6:39 AM, John Henry wrote:
>
>
>
> > On Oct 12, 10:31 am, Tim Golden  wrote:
> >> On 12/10/2010 4:59 PM, John Henry wrote:
>
> >>> According to:
>
> >>>http://support.microsoft.com/kb/813745
>
> >>> I need to reset my Outlook registry keys.  Unfortunately, I don't have
> >>> my Office Install CD with me.  This would have to wait.
>
> >> Thanks for the information; I'm keen to see if you're able
> >> to use the solution I posted once this fix is in place.
>
> >> TJG
>
> > Okay, after fixing the Outlook reg entries as described above, I am
> > able to go further.  Now, the code stops at:
>
> > message = mapi.OpenIMsgOnIStg (mapi_session, None, storage, None, 0,
> > mapi.MAPI_UNICODE)
>
> > with an error message:
>
> > pywintypes.com_error: (-2147221242, 'OLE error 0x80040106', None,
> > None)
>
> Strange. That's UNKNOWN_FLAGS. Try the call without the MAPI_UNICODE,
> ie make the last param zero. Maybe there's something with Outlook 2002...
> I've never tried it myself.
>
> TJG

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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading Outlook .msg file using Python

2010-10-19 Thread John Henry
On Oct 19, 2:46 pm, John Henry  wrote:
> On Oct 17, 4:45 am, Tim Golden  wrote:
>
>
>
> > On 17/10/2010 6:39 AM, John Henry wrote:
>
> > > On Oct 12, 10:31 am, Tim Golden  wrote:
> > >> On 12/10/2010 4:59 PM, John Henry wrote:
>
> > >>> According to:
>
> > >>>http://support.microsoft.com/kb/813745
>
> > >>> I need to reset my Outlook registry keys.  Unfortunately, I don't have
> > >>> my Office Install CD with me.  This would have to wait.
>
> > >> Thanks for the information; I'm keen to see if you're able
> > >> to use the solution I posted once this fix is in place.
>
> > >> TJG
>
> > > Okay, after fixing the Outlook reg entries as described above, I am
> > > able to go further.  Now, the code stops at:
>
> > > message = mapi.OpenIMsgOnIStg (mapi_session, None, storage, None, 0,
> > > mapi.MAPI_UNICODE)
>
> > > with an error message:
>
> > > pywintypes.com_error: (-2147221242, 'OLE error 0x80040106', None,
> > > None)
>
> > Strange. That's UNKNOWN_FLAGS. Try the call without the MAPI_UNICODE,
> > ie make the last param zero. Maybe there's something with Outlook 2002...
> > I've never tried it myself.
>
> > TJG
>
> 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

This flag means the mapi.MAPI_UNICODE flag.
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-10-19 Thread Terry Reedy

On 10/19/2010 3:57 PM, Seebs wrote:

So, I'm messing around with pylint.  Quite a lot of what it says
is quite reasonable, makes sense to me, and all that.

There's a few exceptions.

...

So am I going to be laughed out of the room if I just let a class have
eight instance attributes, or use a short name for a caught exception?


No, at least not be me.

Terry Jan Reedy

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


Re: get python bit version as in (32 or 64)

2010-10-19 Thread Philip Semanchuk

On Oct 19, 2010, at 5:38 PM, Hexamorph wrote:

> On 19.10.2010 23:18, Vincent Davis wrote:
>> How do I get the bit version of the installed python. In my case, osx
>> python2.7 binary installed. I know it runs 64 bt as I can see it in
>> activity monitor. but how do I ask python?
>> sys.version
>> '2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 
>> 5493)]'
>> 
> 
> In [1]: import platform
> 
> In [2]: platform.architecture()
> Out[2]: ('32bit', 'ELF')
> 
> In [3]:


Looks a lot better than my suggestion!



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


Re: Getting returncode of a command executed with Popen through xterm

2010-10-19 Thread AmFreak

Am 19.10.2010, 10:10 Uhr, schrieb Diez B. Roggisch :


amfr...@web.de writes:


Hi,

i have a program that have to execute linux commands. I do it like this:

retcode = Popen(["xterm", "-e", command],stdin=PIPE, stdout=PIPE,
stderr=PIPE)

I have to use xterm because some commands need further input from the
user after they are executed.
But when i use xterm i can't get the returncode or the errormessage
from a command:

print retcode.returncode# always 0
print retcode.stderr.read() # always empty
print retcode.stdout.read() # always empty

The same code works without xterm. As i understand it, if i use xterm
the retcode refers to the xterm window (process).
But is there a way i can get the returncode and errormessage of the
command i sent to xterm ?


You could create a python-wrapper-script that will store the result and
streams in files. Like this


command = ["callwrapper", "--dest-key=",  
"the_real_command"]

Popen(["xterm", "-e", command])

The dest-key will be used to create files named .status,
.stdout, .stderr so that you can read from
them afterwards.

Diez



Thanks for the answer,

but i really don't know how to do it - i never wrote a wrapper, how do i  
get the status, stdout and stderr ?
Can you elaborate that further or do you maybe have a link that could help  
me ?

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


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

2010-10-19 Thread Martin P. Hellwig

On 10/19/10 20:57, Seebs wrote:

So, I'm messing around with pylint.  Quite a lot of what it says
is quite reasonable, makes sense to me, and all that.

There's a few exceptions.

Well, as with all styles IMHO, if there is a _good_ reason to break it, 
then by all means do, but you might want to consider putting in a 
comment why you did that and add the #pylint: disable-msg= 
on that line. If that is overkill, why not just comply to the standard 
and avoid all the fuzz?


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


Re: Unicode questions

2010-10-19 Thread Terry Reedy

On 10/19/2010 4:31 PM, Tobiah wrote:

There is no such thing as "plain Unicode representation". The closest
thing would be an abstract sequence of Unicode codepoints (ala Python's
`unicode` type), but this is way too abstract to be used for
sharing/interchange, because storing anything in a file or sending it
over a network ultimately involves serialization to binary, which is not
directly defined for such an abstract representation (Indeed, this is
exactly what encodings are: mappings between abstract codepoints and
concrete binary; the problem is, there's more than one of them).


Ok, so the encoding is just the binary representation scheme for
a conceptual list of unicode points.  So why so many?  I get that
someone might want big-endian, and I see the various virtues of
the UTF strains, but why isn't a handful of these representations
enough?  Languages may vary widely but as far as I know, computers
really don't that much.  big/little endian is the only problem I
can think of.  A byte is a byte.  So why so many encoding schemes?
Do some provide advantages to certain human languages?


The hundred or so language-specific encodings all pre-date unicode and 
are *not* unicode encodings. They are still used because of inertia and 
local optimization.


There are currently about 10 unicode codepoints, with space for 
about 1,000,000. The unicode standard specifies exactly 2 internal 
representations of codepoints using either 16 or 32 bit words. The 
latter uses one word per codepoint, the former usually uses one word but 
has to use two for codepoints above 2**16-1. The standard also specifies 
about 7 byte-oriented transer formats, UTF-8,16,32 with big and little 
endian variations. As far as I know, these (and a few other variations) 
are the only encodings that encode all unicode chars (codepoints)


--
Terry Jan Reedy

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


Re: Starting Python in XP Pro

2010-10-19 Thread Grant Andrew
Success - I worked with a friend who is Python-fluent to diagnose this issue
and it turns out that in addition to the PATH variable, there were TCL and
TK variables that were pointing toward an old install of Python.

With these references pointed toward the correct folders in the current
install, all is well.

Now I can get to the work of learning Python, instead of bleeding through
the eyes.

Thanks for all of the help!!

Grant


On Sun, Oct 17, 2010 at 12:12 PM, Dennis Lee Bieber
wrote:

> On Sat, 16 Oct 2010 21:27:11 -0600, Grant Andrew 
> declaimed the following in gmane.comp.python.general:
>
> >
> > I ran C:\>C:\python26\lib\idlelib\idle.py at the command prompt and that
> > returned:
> >
> 
>
> > {C:\IBMTOOLS\Python22\tcl\tcl8.4} C:/IBMTOOLS/Python22/tcl/tcl8.5
> > C:/Python2
> > 6/lib/tcl8.5 C:/lib/tcl8.5 C:/lib/tcl8.5 C:/library C:/library
> > C:/tcl8.5.8/libra
> > ry C:/tcl8.5.8/library
> >
> And there is your answer... Your system apparently came with Python
> 2.2 installed by IBM and IT is on the search path AHEAD of the Python2.6
> stuff.
>
>You probably need to edit the PATH environment variable for user
> account to not reference the factory installed Python/tcl
>
>Since my system didn't have a factory Python, I was able to put my
> install on the system PATH rather than the user PATH. (Hmm, I need to
> edit the system PATH -- regina is no longer on C:, and I seem to have
> duplicates of Roxio paths; only the last two items are my user account
> path)
>
> PATH=e:\Python25\; E:\GNAT\2008\bin; C:\WINDOWS\system32; C:\WINDOWS;
> C:\WINDOWS\System32\Wbem; C:\Program Files\SciTE; C:\Program
> Files\Java\jre1.6.0_03\bin ;C:\Program Files\Java\jdk1.6.0_03\bin;
> C:\Program Files\Common Files\Adobe\AGL; C:\Tcl\bin; C:\Program
> Files\Common Files\Roxio Shared\9.0\DLLShared\; C:\Program Files\Common
> Files\Roxio Shared\DLLShared\; c:\Regina; C:\Program
> Files\TortoiseSVN\bin; C:\PROGRA~1\MySQL\MySQL Server 5.0\bin;
> E:\GNAT\GtkAda\bin;C:\MSSQL7\BINN;c:\PROGRA~1
> \sdb\programs\bin; c:\PROGRA~1\sdb\programs\pgm; e:\python25\scripts;
> C:\WINDOWS\system32\WindowsPowerShell\v1.0; C:\Program Files\Common
> Files\Roxio Shared\DLLShared\; C:\Program Files\Common Files\Roxio
> Shared\9.0\DLLShared\; C:\Program Files\QuickTime\QTSystem\;
> C:\WINDOWS\system32\WindowsPowerShell\v1.0; c:\bin; e:\regina
> --
>Wulfraed Dennis Lee Bieber AF6VN
>wlfr...@ix.netcom.comHTTP://wlfraed.home.netcom.com/
>
> --
> 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-19 Thread Terry Reedy

On 10/19/2010 5:43 PM, Seebs wrote:


That reminds me, though.  Speaking of deprecation, I have:
from string import Template
(see PEP 292 or so?), and pylint says "Uses of a deprecated module 'string'",
but I don't know of a way to get Template except by doing that.


A buggy PyLint is passing on bad (obsolete, deprecated ;-) info: In 3.1

>>> import string
>>> dir(string)
['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', 
'__doc__', '__file__', '__name__', '__package__', '_multimap', '_re', 
'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 
'digits', 'hexdigits', 'maketrans', 'octdigits', 'printable', 
'punctuation', 'whitespace']


--
Terry Jan Reedy

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


Re: Starting Python in XP Pro

2010-10-19 Thread Dave Angel

 On 10/19/2010 3:06 PM, Grant Andrew wrote:

1. Okay, I can open the interpreter and do math.  If only I needed the
answer to 6*7 I'd be great.  But, to your point, Python is installed and
working.

2.  When I went to the shortcut and hit properties, the path was

Target: C:\Python26\Lib\idlelib\idle.bat
Start in: C:\Python26\

I cd'd to C:\Python26\ at the command prompt and ran Lib\idlelib\idle.bat.

It just reprints C:\Python26\ with no error or message.  Looks like this:

C:\Python26>Lib\idlelib\idle.bat
C:\Python26>

3.  I created a simple file in Wordpad that prints a few lines.  It is
called Print.py but I'm not sure where the 'code' folder is.  I'm not
familiar enough with Python to locate a file from the Interpreter and open
it.

4.  I also tried editing the PATH variable, which did have both versions in
it, but with no success - same error.


Thanks for your help...

Grant



(You top-posted, so I'm removing all the stuff that's now out of order)

Your PATH should never have two versions of the same program system in 
it.  So if two different installs are in your system PATH, you should 
(using the control panel) remove the one you're not using.  Remember 
that existing programs aren't affected by changes in the system PATH.


The code directory is wherever you write your .py file(s).  The point is 
it should not be in the middle of the installation directory, but 
somewhere else you chose.


I use
m:\programming\python\sources

and then make a subdirectory under there.  Only when a script is working 
reliably do I copy it to a place on my PATH, like m:\t\bin   Once I do, 
it's as accessible as any other executable on the PATH.


Wordpad creates rtf files by default, which are useless to the python 
interpreter.  You want a text file.  You can do it with the SaveAs 
dialog, by changing the "Save as type" from "Rich Text Format" to "Text 
Document".


However, it'd be easier to just use a text editor, such as Notepad.  Or 
one of dozens of other text editors, most free, that you can install.


Anyway, once you've got a text file called   print.py, in the 
c:\sourceCode directory, try the following:


c:\someOtherPlace> cd \sourceCode
c:\sourceCode> python print.py

and see if it loads and runs correctly.

If that works, then you can try typing:

c:\sourceCode> print.py

and if that works, you can try:

c:\sourceCode> print

Note that there's already a print.exe program in Windows, in the 
system32 directory, so this might not be a good name for this particular 
test.


If this all works, and Idle doesn't, someone else will have to help.

DaveA

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


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

2010-10-19 Thread Seebs
On 2010-10-19, Martin P. Hellwig  wrote:
> Well, as with all styles IMHO, if there is a _good_ reason to break it, 
> then by all means do, but you might want to consider putting in a 
> comment why you did that and add the #pylint: disable-msg= 
> on that line. If that is overkill, why not just comply to the standard 
> and avoid all the fuzz?

Well, part of what I'm trying to understand is why the standard in question
says what it says.  I'm pretty much mystified by a claim that something with
seven instance attributes is "too complicated".  For instance, I've got a
class which represents (approximately) a C function, for use in writing
various wrappers related to it.  It has name, return type, args, default
values, a list of arguments which need various modifications, a default
return value, and so on... And it ends up with, apparently, 10 instance
attributes.

I can't tell whether there's actually a general consensus that classes
should never be nearly that complicated, or whether pylint is being a little
dogmatic here -- I haven't seen enough other Python to be sure.  I'm
used to having objects with anywhere from two or three to a dozen or more
attributes, depending on what kind of thing they model.  It seems like a
very odd measure of complexity; is it really that unusual for objects to have
more than seven meaningful attributes?

-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-19 Thread Ben Finney
Seebs  writes:

> So, I'm messing around with pylint.  Quite a lot of what it says
> is quite reasonable, makes sense to me, and all that.
>
> There's a few exceptions.

While the exceptions will no doubt lead to fascinating discussions, I'll
offer a somewhat related piece of advice:

If you're going to ignore a message from pylint, do so by explicitly
disabling it in the config file for your project. That way, you can even
write a comment in the config file explaining why; and you can re-visit
the decision later.

Most importantly, the output isn't cluttered with messages you're
habitually ignoring.

Tools like pylint are far more useful if every message they emit is
something that you must deal with, rather than ignore every time you see
it. That way, it's feasible to get the output to no messages at all, and
have a defensible reason for every disabled message.

-- 
 \  “I moved into an all-electric house. I forgot and left the |
  `\   porch light on all day. When I got home the front door wouldn't |
_o__)open.” —Steven Wright |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get python bit version as in (32 or 64)

2010-10-19 Thread Vincent Davis
On Tue, Oct 19, 2010 at 3:55 PM, Philip Semanchuk  wrote:
>
> On Oct 19, 2010, at 5:38 PM, Hexamorph wrote:
>
>> On 19.10.2010 23:18, Vincent Davis wrote:
>>> How do I get the bit version of the installed python. In my case, osx
>>> python2.7 binary installed. I know it runs 64 bt as I can see it in
>>> activity monitor. but how do I ask python?
>>> sys.version
>>> '2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 
>>> 5493)]'
>>>
>>
>> In [1]: import platform
>>
>> In [2]: platform.architecture()
>> Out[2]: ('32bit', 'ELF')
>>
>> In [3]:
>
>
> Looks a lot better than my suggestion!
Yes that looks like the right way of doing it. Interesting though that
platform.machine()=i386 and not something about 64.
>>> print platform.machine()
i386
>>> print platform.architecture()
('64bit', '')
>>> import sys; sys.maxint
9223372036854775807

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



-- 
Thanks
Vincent Davis
720-301-3003
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2010-10-19 Thread Martin P. Hellwig

On 10/19/10 23:36, Seebs wrote:


It seems like a
very odd measure of complexity; is it really that unusual for objects to have
more than seven meaningful attributes?

Speaking without context here, so take it with as much salt as required 
;-), it is not that unusual. However there are some things to consider, 
for example are all these attributes related to each other? If so 
wouldn't it be more pythonic to have one attribute which is a dictionary 
and store your stuff in there?


I follow pylint pretty strict and only tend to ignore it when making it 
lint-friendly would mean making it less readable or less logically.


As everything pylint is a really useful tool especially when you just 
start writing in python and it can give you valuable clues on how to 
improve your programming. So just take it as hints that there might be 
ways to write it better, have a think about it, perhaps ask as you have 
done, and happily ignore it if all else fails :-)


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


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

2010-10-19 Thread Alexander Kapps

On 20.10.2010 00:36, Seebs wrote:

On 2010-10-19, Martin P. Hellwig  wrote:

Well, as with all styles IMHO, if there is a _good_ reason to break it,
then by all means do, but you might want to consider putting in a
comment why you did that and add the #pylint: disable-msg=
on that line. If that is overkill, why not just comply to the standard
and avoid all the fuzz?


Well, part of what I'm trying to understand is why the standard in question
says what it says.  I'm pretty much mystified by a claim that something with
seven instance attributes is "too complicated".  For instance, I've got a
class which represents (approximately) a C function, for use in writing
various wrappers related to it.  It has name, return type, args, default
values, a list of arguments which need various modifications, a default
return value, and so on... And it ends up with, apparently, 10 instance
attributes.

I can't tell whether there's actually a general consensus that classes
should never be nearly that complicated, or whether pylint is being a little
dogmatic here -- I haven't seen enough other Python to be sure.  I'm
used to having objects with anywhere from two or three to a dozen or more
attributes, depending on what kind of thing they model.  It seems like a
very odd measure of complexity; is it really that unusual for objects to have
more than seven meaningful attributes?

-s


The general idea is, that modules, classes, methods, and functions 
should be small so they are better reusable, manageable and 
understandable. If you have a huge class or function with many 
attributes or local variables, it's often a sign, that your 
class/function does to much and you better refactor this into 
smaller pieces. There isn't and there can't be a general consensus 
about /how/ small some part should be.


If pylint complains about too many variables or such, take it as a 
hint to rethink your design. If you say, my design is good, then 
feel free to ignore the warning.


If your classes wrap some existing datastructure and pyling 
complains, take it as a hint (just a hint, not more) that maybe your 
underlying datastructure is to complex.


But there are no general rules. In the end you (the programmer) has 
to decide how the code or the data is structured, pylint can only 
give you hints, that there *may* be a problem.


I don't know why "the standard" (what standard?) says what it says, 
but I guess, it's the result of long time experiences and analysis 
of existing code. Trust them, unless you are sure to know better.

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


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

2010-10-19 Thread Seebs
On 2010-10-19, Martin P. Hellwig  wrote:
> Speaking without context here, so take it with as much salt as required 
> ;-), it is not that unusual. However there are some things to consider, 
> for example are all these attributes related to each other? If so 
> wouldn't it be more pythonic to have one attribute which is a dictionary 
> and store your stuff in there?

I don't know.  Does "pythonic" mean "needlessly verbose"?  :)

I did, in an early draft, have something that basically came down to:

self.foo = {}
self.foo['a'] = a()
self.foo['b'] = b()

and then I realized that I could just write:
self.a = a()
self.b = b()

and spend a lot less extra typing on repeating something that, by virtue
of being repeated constantly, was therefore meaningless.  It wasn't creating
a meaningful distinction, it wasn't showing a meaningful relationship...
All these things are attributes of the thing itself, not attributes of its
dictionary.

> As everything pylint is a really useful tool especially when you just 
> start writing in python and it can give you valuable clues on how to 
> improve your programming. So just take it as hints that there might be 
> ways to write it better, have a think about it, perhaps ask as you have 
> done, and happily ignore it if all else fails :-)

Part of the trick is I'm trying to figure out when the problem is that my
intuition about what makes code "readable" contradicts the norms of the python
community, and when the problem is just that pylint is being dogmatic where
real programmers would likely exercise judgement.

-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-19 Thread Seebs
On 2010-10-19, Ben Finney  wrote:
> Tools like pylint are far more useful if every message they emit is
> something that you must deal with, rather than ignore every time you see
> it. That way, it's feasible to get the output to no messages at all, and
> have a defensible reason for every disabled message.

That makes sense -- we do the same thing with warnings in C, usually.

I'll see whether I can find ways to, say, suppress a message for a specific
line rather than in general.  (Though I have no idea what line number to
use for a warning about too many instance attributes...)

-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-19 Thread Seebs
On 2010-10-19, Alexander Kapps  wrote:
> The general idea is, that modules, classes, methods, and functions 
> should be small so they are better reusable, manageable and 
> understandable.

Makes sense.

> If you have a huge class or function with many 
> attributes or local variables, it's often a sign, that your 
> class/function does to much and you better refactor this into 
> smaller pieces.

That is often practical, but it can involve tradeoffs -- there can be
a great deal of additional complexity from the interactions between the
refactored pieces.

I tend to refactor mostly if the pieces have some kind of value outside
their original context.  In some cases, a process is just, well, sorta long,
but there's no relevance to breaking the components out -- they're not
separately useful anywhere.

> I don't know why "the standard" (what standard?) says what it says, 
> but I guess, it's the result of long time experiences and analysis 
> of existing code. Trust them, unless you are sure to know better.

Well, one of the reasons I'm asking is to find out, from experienced
developers, how trustworthy the pylint people are, and what the target
audience is...  Should I be treating this the way I'd treat a list of
coding style rules handed down by a first year CS teacher, which are great
rules for first year CS students, or the way I'd be treating a corporate
style document which is a mandated part of continued employment?

-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: OO and game design questions

2010-10-19 Thread Dave Angel

 On 2:59 PM, Terry Reedy wrote:

On 10/19/2010 1:46 PM, Ian Kelly wrote:

On Tue, Oct 19, 2010 at 5:37 AM, Dave Angel mailto:da...@ieee.org>> wrote:




Simply replace room B with a "destroyed room" object.  That can be
quite small, and you only need one, regardless of how many rooms are
thus eliminated.


How does this avoid the problem of having to keep a list of doors that
lead to room B?  You can't just replace one object with another.  You
would have to replace every reference to B with a reference to the new
object.  This is no simpler than deleting the references or replacing
them with None.


One should rather *change* (not replace) the room into a 'destroyed 
room' or 'collapsed passage' or whatever, that cannot be entered. The 
keeps the room around but allows it to be repaired, rebuilt, cleared, 
or whatever.


Thanks, that is what I was trying to say.  In the same sense that 
emptying a list makes it quite small, if it's a general purpose object, 
you just want to remove all the attributes.


DaveA

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


Re: Fastest way to detect a non-ASCII character in a list of strings.

2010-10-19 Thread Dun Peal
On Mon, Oct 18, 2010 at 1:41 AM, Stefan Behnel  wrote:
> Or, a bit shorter, using Cython 0.13:
>
>    def only_allowed_characters(list strings):
>        cdef unicode s
>        return any((c < 31 or c > 127)
>                   for s in strings for c in s)

Very cool, this caused me to look up the 0.13 release notes:

http://wiki.cython.org/ReleaseNotes-0.13

So they support generator expressions inside all() et al now... Makes
you wonder how long till they support them generally ;-)

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


merge list of tuples with list

2010-10-19 Thread Daniel Wagner
Hello Everyone,

I'm new in this group and I hope it is ok to directly ask a question.

My short question: I'm searching for a nice way to merge a list of
tuples with another tuple or list. Short example:
a = [(1,2,3), (4,5,6)]
b = (7,8)

After the merging I would like to have an output like:
a = [(1,2,3,7), (4,5,6)]

It was possible for me to create this output using a "for i in a"
technique but I think this isn't a very nice way and there should
exist a solution using the map(), zip()-functions

I appreciate any hints how to solve this problem efficiently.

Greetings,
Daniel Wagner

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


Re: merge list of tuples with list

2010-10-19 Thread James Mills
On Wed, Oct 20, 2010 at 10:16 AM, Daniel Wagner
 wrote:
> My short question: I'm searching for a nice way to merge a list of
> tuples with another tuple or list. Short example:
> a = [(1,2,3), (4,5,6)]
> b = (7,8)
>
> After the merging I would like to have an output like:
> a = [(1,2,3,7), (4,5,6)]

What happens with the 8 in the 2nd tuple b ?

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Print to an IPP printer (pkipplib?)

2010-10-19 Thread Дамјан Георгиевски
> I've found the module pkipplib which seems to work well for things
> like
> interrogating an IPP (CUPS) server.  But is there a way to send a
> print job to an IPP print queue? [and no, the local system knows
> nothing about
> the print architecture so popenlp is not an option].  I just want
> to send the data from a file handle to a remote IPP queue as a print
> job.

Isn't IPP based on HTTP?
I think you just need a HTTP POST or PUT to send the print job

-- 
дамјан ((( http://damjan.softver.org.mk/ )))

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it." - Brian W. Kernighan

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


Re: get python bit version as in (32 or 64)

2010-10-19 Thread Ned Deily
In article 
,
 Vincent Davis  wrote:
> On Tue, Oct 19, 2010 at 3:55 PM, Philip Semanchuk  
> wrote:
> > On Oct 19, 2010, at 5:38 PM, Hexamorph wrote:
> >> On 19.10.2010 23:18, Vincent Davis wrote:
> >>> How do I get the bit version of the installed python. In my case, osx
> >>> python2.7 binary installed. I know it runs 64 bt as I can see it in
> >>> activity monitor. but how do I ask python?
> >>> sys.version
> >>> '2.7 (r27:82508, Jul  3 2010, 21:12:11) \n[GCC 4.0.1 (Apple Inc. build 
> >>> 5493)]'
> >>>
> >>
> >> In [1]: import platform
> >>
> >> In [2]: platform.architecture()
> >> Out[2]: ('32bit', 'ELF')
> >>
> >> In [3]:
> >
> >
> > Looks a lot better than my suggestion!

It looks better but, unfortunately, it doesn't work correctly on OS X 
where a universal build can have both 32-bit and 64-bit executables in 
the same file.

$ arch -x86_64 /usr/local/bin/python2.7 -c 'import sys,platform; 
print(sys.maxint,platform.architecture())'
(9223372036854775807, ('64bit', ''))
$ arch -i386 /usr/local/bin/python2.7 -c 'import sys,platform; 
print(sys.maxint,platform.architecture())'
(2147483647, ('64bit', ''))

At the moment, the sys.maxint trick is the simplest reliable test for 
Python 2 on OS X.  For Python 3, substitute sys.maxsize.

> Yes that looks like the right way of doing it. Interesting though that
> platform.machine()=i386 and not something about 64.
> >>> print platform.machine()
> i386
> >>> print platform.architecture()
> ('64bit', '')
> >>> import sys; sys.maxint
> 9223372036854775807

Currently on OS X (10.6 and earlier), uname returns 'i386' for any Intel 
platform, 32-bit only or 32-bit /64-bit capable.

$ uname -p
i386

-- 
 Ned Deily,
 n...@acm.org

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


Re: OO and game design questions

2010-10-19 Thread Martin Gregorie
On Tue, 19 Oct 2010 19:49:20 -0400, Dave Angel wrote:

> Thanks, that is what I was trying to say.  In the same sense that
> emptying a list makes it quite small, if it's a general purpose object,
> you just want to remove all the attributes.
>
I think a 'place' (to generalise it) is quite a small object in any case. 
All it needs to contain is a few lists:
- a list of exits, which in some implementations might be simply
  references to other places, but might usefully be objects with
  two sides, each having an appearance and a link to the place 
  where that side appears.
- a list of fixed objects which only serve to describe the place.
- a list of mobile objects that actors can pick up and move
- a list of actors who happen to be there.

plus a describePlace() method and add(), remove() and getItem() methods 
for each list. It may be possible to use a single list for all types of 
object, in which case the object itself would be very small indeed.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Code smells: too many parameters, too many attributes (was: pylint -- should I just ignore it sometimes?)

2010-10-19 Thread Ben Finney
Seebs  writes:

> I'm pretty much mystified by a claim that something with seven
> instance attributes is "too complicated".

It's a code smell. Many discrete attributes is a sign that the design
can be improved by combining related attributes into a complex type.

It's pretty much the same smell, with the same range of solutions, as
too many parameters for a function.

http://www.c2.com/cgi/wiki?TooManyParameters>
http://www.refactoring.com/catalog/introduceParameterObject.html>

-- 
 \ “Science is a way of trying not to fool yourself. The first |
  `\ principle is that you must not fool yourself, and you are the |
_o__)   easiest person to fool.” —Richard P. Feynman, 1964 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread Daniel Wagner
On Oct 19, 8:35 pm, James Mills  wrote:
> On Wed, Oct 20, 2010 at 10:16 AM, Daniel Wagner
>
>  wrote:
> > My short question: I'm searching for a nice way to merge a list of
> > tuples with another tuple or list. Short example:
> > a = [(1,2,3), (4,5,6)]
> > b = (7,8)
>
> > After the merging I would like to have an output like:
> > a = [(1,2,3,7), (4,5,6)]
>
> What happens with the 8 in the 2nd tuple b ?

O, I'm sorry! This was a bad typo:
the output should look like:
a = [(1,2,3,7), (4,5,6,8)]

Greetings,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread Paul Rubin
Daniel Wagner  writes:
>> > My short question: I'm searching for a nice way to merge a list of
>> > tuples with another tuple or list. Short example:
>> > a = [(1,2,3), (4,5,6)]
>> > b = (7,8) ...
> the output should look like:
> a = [(1,2,3,7), (4,5,6,8)]

That is not really in the spirit of tuples, which are basically supposed
to be of fixed size (like C structs).  But you could write:

  >>> [x+(y,) for x,y in zip(a,b)]
  [(1, 2, 3, 7), (4, 5, 6, 8)]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code smells: too many parameters, too many attributes (was: pylint -- should I just ignore it sometimes?)

2010-10-19 Thread Seebs
On 2010-10-20, Ben Finney  wrote:
> It's a code smell. Many discrete attributes is a sign that the design
> can be improved by combining related attributes into a complex type.

Ahh.

I think that makes sense.  In this case, I don't think it's worth it,
but I can see why it would be in some cases.  There are cases where there's
a thing that really DOES have that many attributes, but I've seen lots
of cases where it made sense to subdivide them.

-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: annoying CL echo in interactive python / ipython

2010-10-19 Thread Jed Smith
On Tue, Oct 19, 2010 at 3:33 PM, Hrvoje Niksic  wrote:
> Jed Smith  writes:
>
>>>     echo (-echo)
>>>                 Echo back (do not echo back) every character typed.
>>
>> I'm going to guess that the percent sign in your prompt indicates that
>> you're using zsh(1).  With my minimally-customized zsh, the echo
>> option is reset every time the prompt is displayed. That means you can
>> type "stty -echo", push CR, the echo option is cleared, then zsh
>> immediately sets it before you get to type again.
>
> But are you running zsh in an emacs shell window?  Emacs shell is not a
> terminal emulator, it lets emacs do the editing, and only sends it to
> the shell when enter is pressed.  To avoid clashing with readline and
> equivalent (ZLE in case of zsh), emacs presents itself as a dumb
> terminal, which should make zsh turn ZLE off.

I'll take your word for it, as I don't use emacs. That makes sense,
though, as while researching this question I did find documentation
that suggests zsh disables ZLE under emacs.

OP, it sounds like in this circumstance, then, that you want
interactive Python without readline (which means a recompile, and from
a quick Google it sounds like it might not work). I'd leave readline
in the system Python and just tell emacs to use my custom one without
it, if I were you.

(Or save the trouble and just run ipy in a separate xterm :>)

-- 
Jed Smith
j...@jedsmith.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread MRAB

On 20/10/2010 02:26, Paul Rubin wrote:

Daniel Wagner  writes:

My short question: I'm searching for a nice way to merge a list of
tuples with another tuple or list. Short example:
a = [(1,2,3), (4,5,6)]
b = (7,8) ...

the output should look like:
a = [(1,2,3,7), (4,5,6,8)]


That is not really in the spirit of tuples, which are basically supposed
to be of fixed size (like C structs).  But you could write:

   >>>  [x+(y,) for x,y in zip(a,b)]
   [(1, 2, 3, 7), (4, 5, 6, 8)]


In Python 2.x:

zip(*zip(*a) + [b])

In Python 3.x:

list(zip(*list(zip(*a)) + [b]))
--
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread Daniel Wagner
I used the following code to add a single fixed value to both tuples.
But this is still not what I want...
>>>a = [(1,2,3), (4,5,6)]
>>>b = 1
>>>a = map(tuple, map(lambda x: x + [1], map(list, a)))
>>>a
[(1, 2, 3, 1), (4, 5, 6, 1)]

What I need is:
>>>a = [(1,2,3), (4,5,6)]
>>>b = (7,8)
>>> a = CODE
>>>a
[(1,2,3,7), (4,5,6,8)]

Greetings,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread Daniel Wagner
SOLVED! I just found it out

> I'm searching for a nice way to merge a list of
> tuples with another tuple or list. Short example:
> a = [(1,2,3), (4,5,6)]
> b = (7,8)
>
> After the merging I would like to have an output like:
> a = [(1,2,3,7), (4,5,6)]

The following code solves the problem:
>>> a = [(1,2,3), (4,5,6)]
>>> b = [7,8]
>>> a = map(tuple, map(lambda x: x + [b.pop(0)] , map(list, a)))
>>> a
[(1, 2, 3, 7), (4, 5, 6, 8)]

Any more efficient ways or suggestions are still welcome!

Greetings,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spreadsheet-style dependency tracking

2010-10-19 Thread Lawrence D'Oliveiro
In message 
, Carl 
Banks wrote:

> On Oct 18, 4:15 pm, Lawrence D'Oliveiro 
> wrote:
>
>> In message
>> <42d82f8a-4ee6-44a7-914d-86dfc21f1...@a36g2000yqc.googlegroups.com>,
>> Fuzzyman wrote:
>>
>>> Allowing calculations to complete even in the presence of cycles can be
>>> very useful.
>>
>> But then the answer is no longer completely deterministic.
> 
> Yes it is ...

No, because it will change depending on the iteration number. And if the 
computation doesn’t converge, this is a recipe for oscillations, including 
chaotic ones.

Hmmm, I wonder how much of Wall Street’s crash-proneness can be blamed on 
dependency cycles in damned Excel spreadsheets...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: merge list of tuples with list

2010-10-19 Thread James Mills
On Wed, Oct 20, 2010 at 1:33 PM, Daniel Wagner
 wrote:
> Any more efficient ways or suggestions are still welcome!

Did you not see Paul Rubin's solution:

>>> [x+(y,) for x,y in zip(a,b)]
 [(1, 2, 3, 7), (4, 5, 6, 8)]

I think this is much nicer and probably more efficient.

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >