Re: return None

2005-07-23 Thread Terry Reedy

Ximo [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Can I do a function which don't return anything?

No, if you mean like subroutines.

 The question is that, if I do a function that have a return or without 
 return, it returns always None, but i want that it doesnt return me 
 nothing

Why?  An answer to that would help you maybe get better answers here.

Terry J. Reedy



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


Re: tuple to string?

2005-07-23 Thread Reinhold Birkenfeld
John Machin wrote:
 Reinhold Birkenfeld wrote:
 Berthold Höllmann wrote:
 
Francois De Serres [EMAIL PROTECTED] writes:


hiho,

what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D)
to the string 'spam'?

. t = (0x73, 0x70, 0x61, 0x6D)
. ''.join('%c' % c for c in t)
'spam'
 
 
 Or:
 
 t = (0x73, 0x70, 0x61, 0x6D)
 ('%c' * len(t)) % t
 
 You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-)

Ah, ok. Didn't want to lookup the precedence rules...

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

unit test nested functions

2005-07-23 Thread Andy
How can you unit test nested functions?  Or do you have to pull them out to 
unit test them, which basically means I will never use nested functions.

Also, same thing with private member functions protected by __.  Seems like 
there is a conflict there between using these features and unit testing.

Andy


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


Re: return None

2005-07-23 Thread Fuzzyman
Grant Edwards wrote:
[snip..]
 Personally, I don't really like the idea that falling off the
 botton of a function implicitly returns None.  It's just not
 explicit enough for me.  My preference would be that if the
 function didn't execute a return statement, then it didn't
 return anyting and attempting to use a return value would be an
 error.

 I suppose there probably is code out there that depends on the
 implicit return None at the end of every function, so it's
 too late to change things now.


Yeah - I frequently rely on that behaviour, but purely our of laziness.

Best Regards,

Fuzzy
http://www.voidspace.org.uk/python


 --
 Grant Edwards   grante Yow!  Is it FUN to be
   at   a MIDGET?
visi.com

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


Re: PEP on path module for standard library

2005-07-23 Thread George Sakkis
Andrew Dalke [EMAIL PROTECTED] wrote:

 [snipped]

  Take for example the case where a PhoneNumber class is subclass
  of int. According to LSP, it is perfectly ok to add phone numbers
  together, subtract them, etc, but the result, even if it's a valid
  phone number, just doesn't make sense.

 Mmm, I don't think an integer is a good model of a phone number.
 For example, in the US
   00148762040828
 will ring a mobile number in Sweden while
   148762040828
 will give a this isn't a valid phone number message.

That's why phone numbers would be a subset of integers, i.e. not every integer 
would correspond to a
valid number, but with the exception of numbers starting with zeros, all valid 
numbers would be an
integers. Regardless, this was not my point; the point was that adding two 
phone numbers or
subtracting them never makes sense semantically.

 [snipped]

  I just noted that conceptually a path is a composite object consisting of
  many properties (dirname, extension, etc.) and its string representation
  is just one of them. Still, I'm not suggesting that a 'pure' solution is
  better that a more practical that covers most usual cases.

 For some reason I think that

   path.dirname()

 is better than

   path.dirname

 Python has properties now so the implementation of the latter is
 trivial - put a @property on the line before the def dirname(self):.

Sorry, I used the term 'property' in the broad sense, as the whole exposed API, 
not the specific
python feature; I've no strong preference between path.dirname and 
path.dirname().

 I think that the string representation of a path is so important that
 it *is* the path.

There are (at least) two frequently used path string representations, the 
absolute and the relative
to the working directory. Which one *is* the path ? Depending on the 
application, one of them woud
be more natural choice than the other.

 I trust my intuition on this, I just don't know how to justify it, or
 correct it if I'm wrong.

My intuition also happens to support subclassing string, but for practical 
reasons rather than
conceptual.

George


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


Re: return None

2005-07-23 Thread Erik Max Francis
Grant Edwards wrote:

 Personally, I don't really like the idea that falling off the
 botton of a function implicitly returns None.  It's just not
 explicit enough for me.  My preference would be that if the
 function didn't execute a return statement, then it didn't
 return anyting and attempting to use a return value would be an
 error.

That's not a bad idea.  I tend to prefer self-documenting code whenever 
possible anyway, so if I a method ends that I don't intend to have a 
useful return value, I don't have a return statement with an argument, 
and if I intend a method that returns a useful value to return one that 
might be None, I do so expliclitly, rather than having the logic fall 
off the end of the function, making it unclear what was intended in the 
first place.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   Grab a club and join the chorus / Evolution is a state of mind
   -- Oleta Adams
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-23 Thread Andrew Dalke
George Sakkis wrote:
 That's why phone numbers would be a subset of integers, i.e. not every
 integer would correspond to a valid number, but with the exception of
 numbers starting with zeros, all valid numbers would be an integers.

But it's that exception which violates the LSP.

With numbers, if x==y then (x,y) = (y,x) makes no difference.
If phone numbers are integers then 001... == 01... but swapping
those two numbers makes a difference.  Hence they cannot be modeled
as integers.

 Regardless, this was not my point; the point was that adding
 two phone numbers or subtracting them never makes sense semantically.

I agree. But modeling them as integers doesn't make sense either.
Your example of adding phone numbers depends on them being represented
as integers.  Since that representation doesn't work, it makes sense
that addition of phone number is suspect.

 There are (at least) two frequently used path string representations,
 the absolute and the relative to the working directory. Which one *is*
 the path ? Depending on the application, one of them woud be more
 natural choice than the other.

Both.  I don't know why one is more natural than the other.

 I trust my intuition on this, I just don't know how to justify it, or
 correct it if I'm wrong.
 
 My intuition also happens to support subclassing string, but for
 practical reasons rather than conceptual.

As you may have read elsewhere in this thread, I give some examples
of why subclassing from string fits best with existing code.

Even if there was no code base, I think deriving from string is the
right approach.  I have a hard time figuring out why though.  I think
if the lowest level Python/C interface used a get the filename
interface then perhaps it wouldn't make a difference.  Which means
I'm also more guided by practical reasons than conceptual.

Andrew
[EMAIL PROTECTED]

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


Re: Difference between and '

2005-07-23 Thread Steven D'Aprano
On Fri, 22 Jul 2005 08:38:28 -0400, Peter Hansen wrote:

 Steven D'Aprano wrote:
 It may shock some people to learn that difference in the sense of 
 mathematical subtraction is not the only meaning of the word, but there 
 it is. One wouldn't, I hope, misunderstand What is the difference 
 between spaghetti marinara and spaghetti pescatora? and attempt to 
 subtract one from the other, since subtraction is not defined for 
 foodstuffs.
 
   sum(ord(c) for c in 'spaghetti marinara') - sum(ord(c) for c in 
 spaghetti pescatora)
 -119
 
 Works for me... ;-)

Yes, but if you had thought about the problem a little longer, you would
have removed the spaghetti from both, since they just cancel each other.
Although that does assume that the commutative law holds for pasta
products.

Personally, I prefer this answer:

 import sets
 sets.Set(spaghetti marinara) - sets.Set(spaghetti pescatora)
Set(['m', 'n'])



-- 
Steven.


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


Re: tuple to string?

2005-07-23 Thread Steven D'Aprano
On Fri, 22 Jul 2005 06:07:28 -0700, Robert Kern wrote:

 Francois De Serres wrote:
 hiho,
 
 what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D) to 
 the string 'spam'?
 
 In [1]: t = (0x73, 0x70, 0x61, 0x6D)
 
 In [2]: ''.join(chr(x) for x in t)
 Out[2]: 'spam'

I get a syntax error when I try that. I guess anyone who hasn't started
using Python 2.4 will also get the same error.

Since t is just a tuple, there isn't a big advantage as far as I can
see to build up and dispose of the generator machinery just for grabbing
the next item in a tuple. So a list comprehension will work just as well,
and in older versions of Python:

''.join([chr(x) for x in (0x73, 0x70, 0x61, 0x6D)])

For an even more version-independent method:

L = []
for n in (0x73, 0x70, 0x61, 0x6D):
L.append(chr(n))
print ''.join(L)


or even:

 ''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D)))
'spam'



-- 
Steven.

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


Re: unit test nested functions

2005-07-23 Thread Andrew Dalke
Andy wrote:
 How can you unit test nested functions?

I can't think of a good way.  When I write a nested function it's because
the function uses variables from the scope of the function in which it's
embedded, which means it makes little sense to test it independent of the
larger function.

My tests in that case are only of the enclosing function.

 Or do you have to pull them out to
 unit test them, which basically means I will never use nested functions.

You don't test every line in a function by itself, right?  Nor
every loop in a function.  It should be possible to test the outer
function enough that the implementation detail - of using an inner
function - doesn't make much difference.

 Also, same thing with private member functions protected by __.  Seems
 like there is a conflict there between using these features and unit
 testing.

In that case the spec defined that the real function name is of
the form _CLASSNAME__METHODNAME.  For example

 class Spam:
...   def __sing(self):
... print I don't see any Vikings.
... 
 spam = Spam()
 spam._Spam__sing()
I don't see any Vikings.
 

I've found though that the double-leading-underscore is overkill.
Using a single underscore is enough of a hint that the given
method shouldn't be called directly.

Then again, I don't write enough deep hierarchies where I need
to worry about a subclass implementation using the same private
name as a superclass.
Andrew
[EMAIL PROTECTED]

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


Re: is this possible?

2005-07-23 Thread Steven D'Aprano
On Fri, 22 Jul 2005 07:59:42 -0700, scrimp wrote:

 I am using reportlab not to generate PDF files, 

Isn't that amazing! I'm also using reportlab not to generate PDF files
too! I installed the program, and it just sits there, not generating as
many PDF files as I don't want for as long as I don't want them.

:-)

 but I want to be able
 to print them without having to install acrobat reader. I looked
 through the users guide and found nothing about printing to a printer
 (programmatically). I want to be able to automate the printing of
 reports when they are available. Does anyone know how this is done
 using reportlab? thanks!

As others have suggested, if you have to deal with PDF files without
Acrobat, you could use ghostscript. Also pre-installed on many versions
of Linux, and probably other Unixes as well, is pdf2ps which will convert
the PDF file to a pure postscript file, which you can then print to any
printer which understands postscript.

If you are using Windows, you can possibly find open source or free
software to do these things. Google is your friend: www.google.com
But the chances are you'll have to install *something* -- compared to even
the most impoverished Linux distro, Windows is very much batteries not
included, and while Python does come with many batteries, a full-blown
postscript interpreter is not one of them.



-- 
Steven.

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


Neat access to db query results

2005-07-23 Thread Paj
Hi,

I often wish for a really high-level way to access db results, being
willing to forego some efficiency. I came up with a class you can use
like:

  cur = db.cursor()
  cur.execute('select abc, def from blah')
  for row in dbcur_iter(cur):
print row['abc'], row['def']

Here's the class:

  class dbcur_iter:
def __init__(self, cur):
  self.cur = cur
  self.names = [x[0] for x in cur.description]
def __iter__(self):
  return self
def next(self):
  x = cur.fetchone()
  if x is None:
raise StopIteration
  return dict(zip(self.names, x))

Hope you find it useful! Do send me any feedback.

Paul

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


Getting a dictionary from an object

2005-07-23 Thread Thanos Tsouanas
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists.  Is there one?

Thanks in advance.

class dictobj(dict):

class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.

def __init__(self, obj):
self.obj = obj
def __getitem__(self, key):
return self.obj.__getattribute__(key)

-- 
Thanos Tsouanas  .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Bruno Desthuilliers
Thanos Tsouanas a écrit :
 Hello.
 
 I would like to have a quick way to create dicts from object, so that a
 call to foo['bar'] would return obj.bar.
 
 The following works, but I would prefer to use a built-in way if one
 exists.  Is there one?
 
 Thanks in advance.
 
 class dictobj(dict):
 
 class dictobj(dict):
 A dictionary d with an object attached to it,
   which treats d['foo'] as d.obj.foo.
 
 def __init__(self, obj):
 self.obj = obj
 def __getitem__(self, key):
 return self.obj.__getattribute__(key)

I'd replace this last line with:
   return getattr(self.obj, key)


Now given your specs, I don't see what's wrong with your solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Paolino
Thanos Tsouanas wrote:
 Hello.
 
 I would like to have a quick way to create dicts from object, so that a
 call to foo['bar'] would return obj.bar.
 
 The following works, but I would prefer to use a built-in way if one
 exists.  Is there one?
 

 class dictobj(dict):
 
 class dictobj(dict):
 A dictionary d with an object attached to it,
   which treats d['foo'] as d.obj.foo.
 
 def __init__(self, obj):
 self.obj = obj
 def __getitem__(self, key):
 return self.obj.__getattribute__(key)
use getattr(self.obj,key) possibly, as __getattribute__ gets total 
control on attribute access





___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


SPE Ide Crash

2005-07-23 Thread linuxfreak
Hi Stani,

Downloaded your latest SPE editor 0.7.4.m . I'm running wxPython 2.6.1
on a Fedora Core 4 machine. The IDE is great but guess what it crashes
without warning. Was typing some code and boom the whole thing
disappeared without a trace. Thought should let you know

All you guys using this IDE has it ever crashed on you like this???

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


Re: Separation of Code in CGI App

2005-07-23 Thread Bruno Desthuilliers
Rob Cowie a écrit :
 Hi,
 
 I need to create a planner/calendar system using python cgi scripts. It
 is my first CGI app (beyond a few tutorial examples).
 
(snip)

You may want to have a look at the cgi_app mini-framework:
- http://thraxil.org/code/cgi_app/

It's a port of a Perl framework, and it has some unpythonic flavour in 
some points (but that can be easily corrected), and it can work with CGI 
and mod_python. It's quite easy to get started with, and the source 
being really small (about 1kloc IIRC), it's quite easy to customize to 
your own needs (I rolled my own mod_python-only/SimpleTAL-only version 
in half a day...).

You also have the choice between 2 template systems, one that's dirty as 
can be IMHO (htmltmpl) and one that is quite nice (SimpleTAL). The only 
wart with SimpleTAL is that it requires every input to be unicode, but 
that's easy to solve also (I wrote a wrapper class that handle this 
quite transparently - it's still QD but works well so far, I can 
publish it if anyone is interested).

My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aliasing an object's __str__ to a different method

2005-07-23 Thread Paolino
Little less ugly:
In [12]:class A(object):
: def __str__(self):return self.__str__()
: def str(self):return 'ciao'
: def setStr(self):self.__str__=self.str
:

In [13]:a=A()

In [14]:a.setStr()

In [15]:str(a)
Out[15]:'ciao'

The point is str(ob) builtin looks like calling 
ob.__class__.__str__(ob).Prolly Python-dev is the good place to ask about.







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


[path-PEP] Path inherits from basestring again

2005-07-23 Thread Reinhold Birkenfeld
Hi,

the arguments in the previous thread were convincing enough, so I made the
Path class inherit from str/unicode again.

It still can be found in CVS: 
/python/nondist/sandbox/path/{path.py,test_path.py}

One thing is still different, though: a Path instance won't compare to a regular
string.

Other minor differences, as requested on python-dev, are:

* size property - getsize() method.
* atime/mtime/ctime properties - atime()/mtime()/ctime() methods

* dirname() method - directory property
* no parent property
* basename() method - basename property
* no name property

* listdir() method - children() method
* there is still a listdir() method, but with the semantics of os.listdir
* dirs() method - subdirs() method
* joinpath() method - added alias joinwith()
* splitall() method - parts() method

* Default constructor: Path() == Path(os.curdir)
* staticmethod Path.getcwd() - Path.cwd()

* bytes() / lines() / text() - read_file_{bytes,lines,text} methods
* write_{bytes,lines,text} - write_file_{bytes,lines,text} methods

These may be removed though.

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


Re: Getting a dictionary from an object

2005-07-23 Thread Thanos Tsouanas
On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote:
 use getattr(self.obj,key) possibly, as __getattribute__ gets total 
 control on attribute access

Thanks, but what do you mean by 'total control'?

-- 
Thanos Tsouanas  .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Thanos Tsouanas
On Sat, Jul 23, 2005 at 11:30:19AM +0200, Bruno Desthuilliers wrote:
 Thanos Tsouanas a écrit :
  class dictobj(dict):
  
  class dictobj(dict):
  A dictionary d with an object attached to it,
  which treats d['foo'] as d.obj.foo.
  
  def __init__(self, obj):
  self.obj = obj
  def __getitem__(self, key):
  return self.obj.__getattribute__(key)
 
 I'd replace this last line with:
return getattr(self.obj, key)
 
 Now given your specs, I don't see what's wrong with your solution.

I just dont want to use my class, if one already exists in the
libraries (or any other way to achieve the same thing), that's all ;)

Thanks for the tip.

-- 
Thanos Tsouanas  .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Returned mail: see transcript for details

2005-07-23 Thread Mail Administrator
The original message was included as attachment

This part of message has been infected and was deleted!
Dr.Web(R) Daemon report:
infected with Win32.HLLM.MyDoom.49

---
Dr.Web(R) Antivirus Service:  http://www.drweb.com/
---
-- 
http://mail.python.org/mailman/listinfo/python-list

Retrive file name from the window's file path

2005-07-23 Thread praba kar
Dear All,
   I am using Python 2.4 in the linux platform.
At present I am working on webbased file manager.
When I try to upload a file from the linux cgi
script easily fetch the file name by the
filefield.filename.  But When I try to upload
a file from the windows machine It won't
retrieve the file instead of retrieved
full path (C:\\WINDOWS\my.gif).

   And at the same I couldn't know how to
get file name from window's file path
C:\\WINDOWS\my.gif.  I try to workout these
things by os.path.basename().os.path.splitext().
Kindly let me how to handle these situation

prabahar



__
How much free photo storage do you get? Store your friends 'n family snaps for 
FREE with Yahoo! Photos http://in.photos.yahoo.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple to string?

2005-07-23 Thread Scott David Daniels
Steven D'Aprano wrote:
 On Fri, 22 Jul 2005 06:07:28 -0700, Robert Kern wrote:
 ... or even:
 
''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D)))
 
 'spam'

This is exactly what is wrong with lambda.  It yearns for over-use.
This last should be:

 ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D)))

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Paolino
Thanos Tsouanas wrote:
 On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote:
 
use getattr(self.obj,key) possibly, as __getattribute__ gets total 
control on attribute access
 
 
 Thanks, but what do you mean by 'total control'?
 
Probably nothing to do with your question :(
But:
  class A(object):
...   def __getattr__(self,attr):
... return 'whatever'
...
  a=A()
  a.b
'whatever'
  getattr(a,'b')
'whatever'
  a.__getattribute__('b')
Traceback (most recent call last):
   File stdin, line 1, in ?
AttributeError: 'A' object has no attribute 'b'
 

This can probably touch you if your objects uses defualt searching for 
attributes.






___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aliasing an object's __str__ to a different method

2005-07-23 Thread Scott David Daniels
Jeffrey E. Forcier wrote:
 ...
 However, you appear to be correct, and the docs appear to be confused:
 class MyClass(object):
 def edit(self):
 return I'm in edit mode
 def setEdit(self):
 MyClass.__str__ = self.edit
 ...
 Either way, guess I will have to take another route. Your suggestion  is 
 what I'd had in mind, and does the job pretty well. I'm still  
 attempting to figure out the best approach to my overall problem,  
 however, so who knows where I will end up =)

Here is one more standard way to do this:

 class MyClass(object):
 ... # Common behavior goes here

 def setEdit(self):
 self.__class__ = MyEditClass

 def setView(self):
 self.__class__ = MyViewClass


 class MyEditClass(MyClass):
 def __repr__(self):
 return I, %s, am being edited % super(
   MyEditClass, self).__repr__()

 class MyViewClass(MyClass):
 def __repr__(self):
 return I, %s, am being viewed % super(
   MyViewClass, self).__repr__()


Be a little careful about the structure of the subclasses (MyViewClass
and MyEditClass) since they can wink into and out of existence, and
all will go well.  Plus, you can easily override base behavior in the
subclasses differentially.

Note: for this example, you could also define the methods like:

 class MyEditClass(MyClass):
 def __repr__(self):
 return I, %s, am being edited % MyClass.__repr__(self)

When to use super rather than direct access to the superclass is an
involved discussion.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Bruno Desthuilliers
Thanos Tsouanas a écrit :
 On Sat, Jul 23, 2005 at 12:06:57PM +0200, Paolino wrote:
 
use getattr(self.obj,key) possibly, as __getattribute__ gets total 
control on attribute access
 
 
 Thanks, but what do you mean by 'total control'?

mode=screamin jay hawkins
__getattribute__ is really some kind of an evil black voodoo mumbo jumbo 
juju magic method...
/mode

More seriously:
__getattr__() (if defined) is called when and if the 'normal' attribute 
lookup process failed. It's main use is to delegate attribute access to 
a proxied/wrapped/decorated object.
__getattribute__() (if defined) completely override the attribute lookup 
process - so it gets full control over attribute access.

This does not directly concern what you're doing now, but still, for a 
number of reasons, the canonical pythonic way to do named attribute 
access is with the builtin getattr() function, that will call on the 
appropriate lookup mechanism.

As a general rule, '__magic__' methods are implementation, not API, so 
you shouldn't call on them directly unless you have a relly god 
reason to do so.

HTH
Bruno

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


Re: Reading network interface data in linux

2005-07-23 Thread Jorgen Grahn
On Wed, 13 Jul 2005 11:09:57 +0300, Edvard Majakari [EMAIL PROTECTED] wrote:

 Suppose one wants to fetch the following data from given network interface,
 say, eth0:

 Ethinf('eth0').addr()
 '192.168.1.42/24'
...
 Ethstat('eth0').rx_bytes()
 14325235341223
...
 One could implement modules by installing eg. ethtool and reading speed/duplex
 information by parsing ethtool output, but it is ugly way to do it, prone to
 errors, requires launching a process as well as installation of ethtool.

On the other hand, I have a hunch that the interface that ethtool uses is
unstable, changes between major kernel versions, varies with the kind of
hardware you have, etc.

If that is the case, you might want to keep parsing ethtool's output. Letting
/them/ worry about tracking kernel changes would actually be the most stable
solution.  The ethtool authors are kernel developers, and probably know all
that stuff.

Or convince the ethtool authors to release future ethtool versions as a
Python module with an optional command-line interface ;-)

/Jorgen

-- 
  // Jorgen Grahn jgrahn@   Ph'nglui mglw'nafh Cthulhu
\X/algonet.se   R'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Windows Porting Help Requested

2005-07-23 Thread Raymond L. Buvel
I am preparing to release an extension module that interfaces Python to
the Class Library for Numbers (http://www.ginac.de/CLN/).  This module
will provide Python types for arbitrary precision floating point
numbers, rational numbers, and their complex counterparts.  The module
also includes most of the functions found in the Python math and cmath
libraries.

This module will be useful in applications where gmpy
(http://gmpy.sourceforge.net/) doesn't have enough capability (e.g.
extended precision trig, complex numbers, etc.).

I would like to make this module available to Windows users but have
neither the development environment nor the interest to get the module
to build for the standard Python distribution.  I am requesting the help
of a developer who is familiar with building extension modules and
understands C++ porting issues.

I don't think my code is the issue, since it builds with distutils.
However, it depends on two libraries (CLN and GMP) that look like they
have porting issues to a Windows platform.  I suspect they can be made
to work with some of the GNU tools on Windows.  The challenge is making
an extension module that contains all the required parts for the
standard Python distribution.

If you are a developer with the required skills and the time, I would
appreciate your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Steven D'Aprano
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:

 Hello.
 
 I would like to have a quick way to create dicts from object, so that a
 call to foo['bar'] would return obj.bar.

That looks rather confusing to me. Why not just call obj.bar, since it
doesn't look like you are actually using the dictionary at all?

 The following works, but I would prefer to use a built-in way if one
 exists.  Is there one?
 
 Thanks in advance.
 
 class dictobj(dict):
 
 class dictobj(dict):
 A dictionary d with an object attached to it,
   which treats d['foo'] as d.obj.foo.
 
 def __init__(self, obj):
 self.obj = obj
 def __getitem__(self, key):
 return self.obj.__getattribute__(key)

I don't think this is particularly useful behaviour. How do you use it?

py D = dictobj(hello world)
py D
{}
py D.obj
'hello world'
py D[food] = spam
py D
{'food': 'spam'}
py D[food]
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 5, in __getitem__
AttributeError: 'str' object has no attribute 'food'


-- 
Steven.


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


Re: find a specified dictionary in a list

2005-07-23 Thread Steven D'Aprano
On Fri, 22 Jul 2005 12:42:04 +, Odd-R. wrote:

 On 2005-07-22, John Machin [EMAIL PROTECTED] wrote:
 Odd-R. wrote:
 I have this list:
 
 [{'i': 'milk', 'oid': 1}, {'i': 'butter', 'oid': 2},{'i':'cake','oid':3}]
 
 All the dictionaries of this list are of the same form, and all the oids
 are distinct. If I have an oid and the list, how is the simplest way of
 getting the dictionary that holds this oid?

Instead of keeping a list of dictionaries, keep a dict of dicts, indexed
by the oid:

D = {1: {'i': 'milk'}, 2: {'i': 'butter'}, 3: {'i': 'cake'}}

Then you can extract a dictionary with a single call:

thedict = D[oid]

or just grab the item you want directly:

food = D[oid]['i']


No mess, no fuss. Ninety percent of the work is choosing your data
structures correctly.


 Something like this:

 def oidfinder(an_oid, the_list):
  for d in the_list:
  if d['oid'] == an_oid:
  return d
  return None
  # These are not the oids you are looking for.
 
 Thank you for your help, but I was hoping for an even simpler
 solution, as I am suppose to use it in a
 tal:block tal:define=p python: sentence.

I don't understand what that means. Can you explain please?


-- 
Steven.

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


Re: PEP on path module for standard library

2005-07-23 Thread paul
Michael Hoffman wrote:
 Reinhold Birkenfeld wrote:
  Probably as Terry said: a path is both a list and a string.

[...]

 One way to divide this is solely based on path separators:

 ['c:', 'windows', 'system32:altstream', 'test.dir',
 'myfile.txt.zip:altstream']

I would argue that any proposed solution has to work with VMS
pathnames. ;-)

 The current stdlib solution, os.path.splitext(os.path.splitext(filename)
 [0])[0] is extremely clunky, and I have long desired something better.
 (OK, using filename.split(os.extsep) works a little better, but you get
 the idea.)

And also with unusual (eg. RISC OS) filename extensions.

To do any justice to the existing solutions, any PEP should review at
least the following projects:

 * The path module (of course):
   http://www.jorendorff.com/articles/python/path/

 * The py.path module (or at least the ideas for it):
   http://codespeak.net/py/current/doc/future.html

 * itools.uri
   http://www.ikaaro.org/itools

 * Results from the Object-Oriented File System Virtualisation
   project in the Summer of Code programme:
   http://wiki.python.org/moin/SummerOfCode

And I hope that the latter project is reviewing some of the other work,
if only to avoid the framework proliferation that people keep
complaining about.

Paul

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


Re: tuple to string?

2005-07-23 Thread John Machin
Steven D'Aprano wrote:

 
 
''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D)))
 
 'spam'

Why the verbal diarrhoea? What's wrong with the (already posted)

''.join(map(chr, (0x73, 0x70, 0x61, 0x6D)))

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


Re: tuple to string?

2005-07-23 Thread John Machin
Reinhold Birkenfeld wrote:
 John Machin wrote:
 
Reinhold Birkenfeld wrote:

Berthold Höllmann wrote:


Francois De Serres [EMAIL PROTECTED] writes:



hiho,

what's the clean way to translate the tuple (0x73, 0x70, 0x61, 0x6D)
to the string 'spam'?

. t = (0x73, 0x70, 0x61, 0x6D)
. ''.join('%c' % c for c in t)
'spam'


Or:

t = (0x73, 0x70, 0x61, 0x6D)
('%c' * len(t)) % t

You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-)
 
 
 Ah, ok. Didn't want to lookup the precedence rules...


Look up the precedence rules? Are you aware of any language where * / 
and % _don't_ have the same precedence??
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: tuple to string?

2005-07-23 Thread Robert Kern
John Machin wrote:
 Reinhold Birkenfeld wrote:

Ah, ok. Didn't want to lookup the precedence rules...
 
 Look up the precedence rules? Are you aware of any language where * / 
 and % _don't_ have the same precedence??

Given that % is somewhat more esoteric, I certainly have never committed 
to memory its position in a precedence hierarchy of *any* language.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Peter Hansen
Reinhold Birkenfeld wrote:
 One thing is still different, though: a Path instance won't compare to a 
 regular
 string.

Could you please expand on what this means?  Are you referring to doing 
 and = type operations on Paths and strings, or == and != or all those 
or something else entirely?

 Other minor differences, as requested on python-dev, are:
 
 * size property - getsize() method.
 * atime/mtime/ctime properties - atime()/mtime()/ctime() methods

What does this mean?  The .size property and a getsize() method both 
already exist (in my copy of path.py anyway) and do the same thing. 
Same with the other ones mentioned above.  Is someone working from an 
out-of-date copy of path.py?

 * dirs() method - subdirs() method

Given that .files() exists, and returns a list of the files contained in 
a path which represents a folder, why would one want to use subdirs() 
instead of just dirs() to do the same operation for contained folders?
If subdirs() is preferred, then I suggest subfiles() as well.  Otherwise 
the change seems arbitrary and ill-conceived.

 * joinpath() method - added alias joinwith()
 * splitall() method - parts() method

This reminds me of the *one* advantage I can think of for not 
subclassing basestring, though it still doesn't make the difference in 
my mind:  strings already have split(), so Jason had to go with 
splitpath() for the basic split operation to avoid a conflict.  A 
minor wart I guess.

 * Default constructor: Path() == Path(os.curdir)

To construct an empty path then one can still do Path('') ?

 * staticmethod Path.getcwd() - Path.cwd()
 
 * bytes() / lines() / text() - read_file_{bytes,lines,text} methods
 * write_{bytes,lines,text} - write_file_{bytes,lines,text} methods

Under Linux isn't it possible to open and read from directories much as 
with files?  If that's true, the above would seem to conflict with that 
in some way.  As with the the .subdirs() suggestion above, these changes 
seem to me somewhat arbitrary.  .bytes() and friends have felt quite 
friendly in actual use, and I suspect .read_file_bytes() will feel quite 
unwieldy.  Not a show-stopper however.

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


Re: PEP on path module for standard library

2005-07-23 Thread Peter Hansen
George Sakkis wrote:
 Andrew Dalke [EMAIL PROTECTED] wrote:
I think that the string representation of a path is so important that
it *is* the path.
 
 There are (at least) two frequently used path string representations, 
  the absolute and the relative to the working directory. Which one
  *is* the path ? Depending on the application, one of them woud
 be more natural choice than the other.

Sorry, George, but that's now how it works.

Whether using the regular string-based Python paths or the new path 
module, a path *is* either absolute or relative, but cannot be both at 
the same time.

This is therefore not an issue of representation but one of state.

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Robert Kern
Peter Hansen wrote:

 Under Linux isn't it possible to open and read from directories much as 
 with files?

Not really, no.

Python 2.3.4 (#2, Jan  5 2005, 08:24:51)
[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2
Type help, copyright, credits or license for more information.
  d = open('/usr/bin')
Traceback (most recent call last):
   File stdin, line 1, in ?
IOError: [Errno 21] Is a directory
 

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Aliasing an object's __str__ to a different method

2005-07-23 Thread Jeffrey E. Forcier
Thanks for all the additional replies thus far!

Apparently the issue, as stated implicitly or explicitly by most of  
you, is that new-style class instances essentially defer their magic  
methods to the class's static versions of same. This is good to know :)

Ironically, the reason I'm using new-style classes is that I only  
read up on them very recently, and was attempting to get myself into  
the habit of inheriting from 'object' by default. Go figure.

Anyway, to take a step back, the *actual* actual reason for my  
investigation into this issue is that I'm attempting to create a  
collection of classes representing HTML page/form elements, many of  
which are represented differently depending on whether they're in a  
view or edit state.

And ideally I wanted to be able to hold a collection of these objects  
and toggle them all to one state or the other, then bandy them about  
as if they were strings, e.g. mixing them with literal strings via str 
(obj).

Clearly there are at least a handful of ways to accomplish this, but  
the one that came to mind first was, as I said at the beginning, to  
define both behaviors on each object and then have the ability to  
point __str__ to one or the other. I suppose now I need to figure out  
which is more important, that ease-of-use of overriding __str__ or  
whatever benefits new-style classes give (something I'm still a bit  
unclear on).

Thanks again,
Jeff

--
Jeffrey E. Forcier
Junior Developer, Research and Development
Stroz Friedberg, LLC
15 Maiden Lane, 12th Floor
New York, NY 10038
[main]212-981-6540 [direct]212-981-6546
http://www.strozllc.com

This message is for the named person's use only.  It may contain
confidential, proprietary or legally privileged information. No right to
confidential or privileged treatment of this message is waived or lost
by any error in transmission.  If you have received this message in
error, please immediately notify the sender by e-mail or by telephone at
212.981.6540, delete the message and all copies from your system and
destroy any hard copies.  You must not, directly or indirectly, use,
disclose, distribute, print or copy any part of this message if you are
not the intended recipient.

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


Re: Using python to runother programs

2005-07-23 Thread gene tani
this isn't really enough data to go on.  What operating system (sounds
like win2k/XP), does Crystal reports and unnamed accounting software
have COM hooks?

Look at Simon Brunning posts:

http://www.brunningonline.net/simon/blog/archives/000652.html
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003

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


Lists pointers

2005-07-23 Thread Jan Danielsson
Hello all,

   I have written a simple whiteboard application. In my application, I
want to be able to set draw attributes. This part works. I have a
dictionary object which contains stuff like:
self.attr['Pen.Color'] = ...
self.attr['Pen.Thickness'] = ...

   Now, the problem is that I want to be able to store attributes in a
list so they'll be easily accessed using the function keys. I.e. I have
the current attributes which I want to be able to store or retrieve
in/from a list,

The problem is that I have initialized the list like this:

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
   self.storedAttr.append(self.drawAttr)

   I know what the problem is; they are all referencing the *same*
dictionary object. So, my question is: How do I initialize a list of
dictionary objects, where each list entry is its own object (which is a
copy from the self.drawAttr object).

Also, how do I store/restore entries to the list?

   I have found the copy module, and it's copy method. I assume this
would work:

for i in range(0, 10):
   self.storedAttr.append(copy.copy(self.drawAttr))

   However, the concept of deep copy confuses me. Do I want it, or
don't I want it? I repeat: the attributes object is a simple dictionary.

Thankful for any advice.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Reinhold Birkenfeld
Peter Hansen wrote:
 Reinhold Birkenfeld wrote:
 One thing is still different, though: a Path instance won't compare to a 
 regular
 string.
 
 Could you please expand on what this means?  Are you referring to doing 
  and = type operations on Paths and strings, or == and != or all those 
 or something else entirely?

All of these. Do you need them?

 Other minor differences, as requested on python-dev, are:
 
 * size property - getsize() method.
 * atime/mtime/ctime properties - atime()/mtime()/ctime() methods
 
 What does this mean?  The .size property and a getsize() method both 
 already exist (in my copy of path.py anyway) and do the same thing. 
 Same with the other ones mentioned above.  Is someone working from an 
 out-of-date copy of path.py?

No. But the size of a file is somewhat volatile, and does not feel like
a property of the path to it. Remember: the path is not the file. Same
goes with the xtime() methods.

Different is the basename/directory/etc.: as long as the path stays the same,
these properties will stay the same.

 * dirs() method - subdirs() method
 
 Given that .files() exists, and returns a list of the files contained in 
 a path which represents a folder, why would one want to use subdirs() 
 instead of just dirs() to do the same operation for contained folders?
 If subdirs() is preferred, then I suggest subfiles() as well.  Otherwise 
 the change seems arbitrary and ill-conceived.

Well, I think that's right. Will change back to dirs().

 * joinpath() method - added alias joinwith()
 * splitall() method - parts() method
 
 This reminds me of the *one* advantage I can think of for not 
 subclassing basestring, though it still doesn't make the difference in 
 my mind:  strings already have split(), so Jason had to go with 
 splitpath() for the basic split operation to avoid a conflict.  A 
 minor wart I guess.

At the moment, I think about overriding certain string methods that make
absolutely no sense on a path and raising an exception from them.

 * Default constructor: Path() == Path(os.curdir)
 
 To construct an empty path then one can still do Path('') ?

Yes.

 * staticmethod Path.getcwd() - Path.cwd()
 
 * bytes() / lines() / text() - read_file_{bytes,lines,text} methods
 * write_{bytes,lines,text} - write_file_{bytes,lines,text} methods
 
 Under Linux isn't it possible to open and read from directories much as 
 with files?  If that's true, the above would seem to conflict with that 
 in some way.  As with the the .subdirs() suggestion above, these changes 
 seem to me somewhat arbitrary.  .bytes() and friends have felt quite 
 friendly in actual use, and I suspect .read_file_bytes() will feel quite 
 unwieldy.  Not a show-stopper however.

It has even been suggested to throw them out, as they don't have so much to
do with a path per se. When the interface is too burdened, we'll have less
chance to be accepted. Renaming these makes clear that they are not operations
on the path, but on a file the path points to.

Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to 
demonstrate
that they do not read or write a stream; how about that?

Reinhold

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


Regarding Webbrowser Module in Python

2005-07-23 Thread M Kamran Azam

Hi all,

My query goes like this.

I have two htm files.One is media_try_home.htm and the second one is 
media_try.htm.I am attaching these files to my mail so that you guys can 
understand the problem.


Now, first simply open the media_try_home.htm and press PLAY THE FILE 
button.A video clip is opened.(Both the files should be in the same 
directory).


Using webbrowser,  I can first open the first file like this:

webbrowser.open_new(c:\Myfolder\media_try_home.htm).

But I want to play the second file directly using webbrowser but that 
doesn't work when I use the following :


webbrowser.open_new  
(file:///c:\media_try.htm?start=60end=70location=mms%3A%2F%2Fedrul-develop.softeco.it%2F23%2F2004%2F12%2F23_20041218223000.wmvsubmit=PLAY+THE+FILE)


If I simply paste this link in the browser, then it works direclty, 
bypassing the first file.


May be it's due to the fact that file:/// is an ftp?Any ideas or clues 
what can  I do to play the second file directly?


Thanks in anticipation,

Kamran

Title: Documento senza titolo





PLAY WINDOWS MEDIA FILE

   
 
   Start
   

seconds
 
 
   End
   

seconds
 
 
   Location
   
 
   
   
   


 




Title: Documento senza titolo







	
	
	
	
	
	
	


  







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

Re: Neat access to db query results

2005-07-23 Thread gene tani
There's a few places to stash apps, libraries, or small code snippets
so they can be search engined, if you provide some inline comments,
unit/functional tests, and examples of how to use/known limitations:
Vaults Parnassus, dmoz, ActiveState cookbook

http://aspn.activestate.com/ASPN/Cookbook/Python
http://www.pypackage.org/packages
http://dmoz.org/Computers/Programming/Languages/Python/Modules/
http://www.vex.net/parnassus/

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


Re: What is your favorite Python web framework?

2005-07-23 Thread Dark Cowherd
Hi,
I have also been looking around to start web development.
Almost everybody says - Zope h steep learning curve, so looking
at alternatives. But to people have got past that curve. Is Zope worth
it.

My applications would be data entry heavy. Think inventory and accounting apps. 

Would going past the learning curve allow me to write applications like that.



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


problem with property docstrings

2005-07-23 Thread Michael Muller

I've observed something strange about property docstrings and I'm
wondering if anyone here can clarify what's going on:  if I create a class
derived from property, the docstrings of the instances end up being that
of the derived class, not the docstring passed into the property
constructor.  Example:

class MyProp(property):
MyProp docstring
class Foo:
p = MyProp(None, None, None, property p docstring)
 Foo.p.__doc__
'MyProp docstring'

Can anyone explain why this is?  Is this a bug?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lists pointers

2005-07-23 Thread [EMAIL PROTECTED]
Jan Danielsson wrote:
 Hello all,

I have written a simple whiteboard application. In my application, I
 want to be able to set draw attributes. This part works. I have a
 dictionary object which contains stuff like:
 self.attr['Pen.Color'] = ...
 self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
 list so they'll be easily accessed using the function keys. I.e. I have
 the current attributes which I want to be able to store or retrieve
 in/from a list,

 The problem is that I have initialized the list like this:

 self.drawAttr = { blah, blah, blah.. }
 self.storedAttr = [ ]
 for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
 dictionary object. So, my question is: How do I initialize a list of
 dictionary objects, where each list entry is its own object (which is a
 copy from the self.drawAttr object).

 Also, how do I store/restore entries to the list?

I have found the copy module, and it's copy method. I assume this
 would work:

 for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of deep copy confuses me. Do I want it, or
 don't I want it? I repeat: the attributes object is a simple dictionary.

 Thankful for any advice.

The easiest way to do it would be to create a new dictionary object for
each iteration of your loop.  In this scenario, you would not need to
use the copy module.

In other words:

self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append({ blah, blah, blah.. })

I hope this helps!

Regards,

Michael Loritsch

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


Re: What is your favorite Python web framework?

2005-07-23 Thread Benji York
Dark Cowherd wrote:
 My applications would be data entry heavy. Think inventory and accounting 
 apps. 
 
 Would going past the [Zope] learning curve allow me to write applications 
 like that.

You might want to look at Zope 3, there are several niceties for 
automatically (or semi-automatically if you prefer) generating input 
forms, validating them, applying the results to an object, etc.
--
Benji York


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


Re: unit test nested functions

2005-07-23 Thread Raymond Hettinger
[Andy]
 How can you unit test nested functions?  Or do you have to pull them out to
 unit test them, which basically means I will never use nested functions.

Several commons use cases (closures and factory functions) ultimately
expose the inner function through the return value.  If that is the
case, the answer is simple, call the enclosing function and then run
the test on the result.

If the inner function never gets exposed, an argument could be made
that you don't want to write a test for it -- that the inner function
is just an implementation detail.  This is black box testing and
consistent with a test driven development approach.

For whitebox testing, you could make an inner function visible by
binding it to the enclosing function's attribute namespace.

   def f(x):
   def g(y):
  . . .
   f.g = g# make g visible as an attribute of f
   . . .


Raymond

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


Re: unit test nested functions

2005-07-23 Thread Benji York
Raymond Hettinger wrote:
 [Andy]
How can you unit test nested functions? 

 For whitebox testing, you could make an inner function visible by
 binding it to the enclosing function's attribute namespace.
 
def f(x):
def g(y):
   . . .
f.g = g# make g visible as an attribute of f
. . .

Note that when using this technique, f.g will not be bound until after 
you call the function:

  def f(x):
... def g(y):
... pass
... f.g = g
...
  f
function f at 0xb7df3df4
  f.g
Traceback (most recent call last):
   File stdin, line 1, in ?
AttributeError: 'function' object has no attribute 'g'
  f(1)
  f.g
function g at 0xb7df3e2c
--
Benji York


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


Re: smtplib

2005-07-23 Thread Dark Cowherd
On 7/19/05, Alberto Vera [EMAIL PROTECTED] wrote:
 Hello:
  
 Do you know If the smtplib routine have been changed in last releases?
  
 I used this script:
  
 http://docs.python.org/lib/SMTP-example.html
  
 but it didn't work with the last release.
  
 Do you know any idea about this change?
  
 Regards
  
 --
 http://mail.python.org/mailman/listinfo/python-list
 
 
If you are using Windows there is no SMTP server running on localhost
by default so you may be getting an error. If you post the error you
are getting it may help

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


Friend wants to learn python

2005-07-23 Thread EnderLocke
I have a friend who wants to learn python programming. I learned off
the internet and have never used a book to learn it. What books do you
recommend?

Any suggestions would be appreciated.

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Peter Hansen
Reinhold Birkenfeld wrote:
 Peter Hansen wrote (on Paths not allowing comparison with strings):
Could you please expand on what this means?  Are you referring to doing 
 and = type operations on Paths and strings, or == and != or all those 
or something else entirely?
 
 All of these. Do you need them?

I believe so.  If they are going to be basestring subclasses, why should 
they be restricted in any particular way?  I suppose that if you wanted 
to compare a Path to a string, you could just wrap the string in a Path 
first, but if the Path is already a basestring subclass, why make 
someone jump through that particular hoop?

Other minor differences, as requested on python-dev, are:

* size property - getsize() method.
* atime/mtime/ctime properties - atime()/mtime()/ctime() methods

What does this mean?  The .size property and a getsize() method both 
already exist (in my copy of path.py anyway) and do the same thing. 
Same with the other ones mentioned above.  Is someone working from an 
out-of-date copy of path.py?
 
 No. But the size of a file is somewhat volatile, and does not feel like
 a property of the path to it. Remember: the path is not the file. Same
 goes with the xtime() methods.

Oh, so your original text was meant to imply that those properties *were 
being removed*.  That wasn't at all clear to me.

I understand the reasoning, but I'm unsure I agree with it.  I fully 
accept that the path is not the file, and yet I have a feeling this is a 
pedanticism: most of the time when one is dealing with the _file_ one is 
concerned with the content, and not much else.  When one is dealing with 
the _path_ one often wants to check the size, the modification time, and 
so forth.  For example, once one has the file open, one very rarely is 
interested in when it was last modified.

In other words, I feel once again that Jason's original intuition here 
was excellent, and that he chose practicality over purity in appropriate 
ways, in a very Pythonic fashion.  I confess to feeling that the 
suggested changes are being proposed by those who have never actually 
tried to put path.py to use in practical code, though I'm sure that's 
not the case for everyone making those suggestions.

Still, once again this doesn't seem a critical issue to me and I'm happy 
with either approach, if it means Path gets accepted in the stdlib.

 At the moment, I think about overriding certain string methods that make
 absolutely no sense on a path and raising an exception from them.

That would seem reasonable.  It seems best to be very tolerant about 
what makes no sense, though istitle() would surely be one of those to 
go first.  Also capitalize() (in spite of what Windows Explorer seems to 
do sometimes), center(), expandtabs(), ljust(), rjust(), splitlines(), 
title(), and zfill().  Hmm... maybe not zfill() actually.  I could 
imagine an actual (if rare) use for that.

.bytes() and friends have felt quite 
friendly in actual use, and I suspect .read_file_bytes() will feel quite 
unwieldy.  Not a show-stopper however.
 
 It has even been suggested to throw them out, as they don't have so much to
 do with a path per se. When the interface is too burdened, we'll have less
 chance to be accepted. Renaming these makes clear that they are not operations
 on the path, but on a file the path points to.

Here again I would claim the practicality over purity argument.  When 
one has a Path, it is very frequently because one intends to open a file 
object using it and do reads and writes (obviously).  Also very often, 
the type of reading and writing one wants to do is an all at once type 
of thing, as those methods support.  They're merely a convenience, to 
save one doing the Path(xxx).open('rb').read thing when one can merely 
do Path(xxx).bytes(), in much the same way that the whole justification 
for Path() is that it bundles useful and commonly used operations 
together into one place.

 Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to 
 demonstrate
 that they do not read or write a stream; how about that?

If they are there, they do exactly what they do, don't they?  And they 
do file.read() and file.write() operations, with slight nuances in the 
mode passed to open() or the way the data is manipulated.  Why would one 
want to hide that, making it even harder to tie these operations 
together with what is really going on under the covers?  I think the 
existing names, or at least ones with _read_ and _write_ in them 
somewhere are better than set/get alternatives.  It's just rare in 
Python to encounter names quite as cumbersome as _write_file_bytes().

It might be good for those involved to discuss and agree on the 
philosophy/principles behind using Path in the first place.  If it's one 
of pragmatism, then the arguments in favour of strictly differentiating 
between path- and file- related operations should probably not be given 
as much weight as those in favour of simple and convenient access 

Re: list implementation

2005-07-23 Thread Raymond Hettinger
  [sj]
  Thus, random access is an O(1) operation while insertion/deletion is an
  O(n) operation.

[Raymond Hettinger]
  Yes.

[Heikki Orsila aka host.invalid]
 Unfortunately no. Check Terry Reeds answer. Random access is O(1),
 insertion/deletion to front is O(n), and i/d to back is O(1). The back
 i/d operation has amortized O(1) cost.

Duh.  Excellent misreading of a simple answer to the OP's plain
question.  It is clear from his post that he already had a pretty
accurate guess about how lists were implemented and the consequent
performance implications.

What was needed was a confirmation of his guess and a pointer to
collections.deque() for O(1) insertion/deletion on the ends.  For O(1)
length changing ops in the middle, his suggestion of a linked list was
not off base.  IOW, a simple yes would have served.


Raymond


P.S.  Non-standard abbreviations like, i/d, are rarely helpful to your
readers.

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


consistency: extending arrays vs. multiplication ?

2005-07-23 Thread Soeren Sonnenburg
Hi all,

Just having started with python, I feel that simple array operations '*'
and '+' don't do multiplication/addition but instead extend/join an
array:

a=[1,2,3]
 b=[4,5,6]
 a+b
[1, 2, 3, 4, 5, 6]

instead of what I would have expected:
[5,7,9]

or

 2*a
[1, 2, 3, 1, 2, 3]

Well it is consistent to strings but tolerating string-operations to be
special is ok to me as a + b - 'ab' :)
Why not make it another function like a.stretch() or a.expand() and
a.extend() is there doing the same anyway and is more readable...

Putting this in a larger view: 
Ufuncs are very reasonable sin(a), etc ... all that won't work because
of that '+','*' syntax. Ok I can use numarray for that, but seeing its
PEP and a possible inclusion into python at some point that
inconsistency is giving me quite some headache...

Will that change in the future ? Or is this 100*[0] syntax put into
stone for all ages ?

Best,
Soeren.

PS: As I am very new to python please forgive/correct me!

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


Re: Python vs. Access VBA

2005-07-23 Thread Dark Cowherd
 better to go with SQLite.  Its cross platform and well proven.  I think
 Firebird will give you that too, though I have never used it.
 

Firebird is a great option, cross platform, it can work like access
without any server running, using embedded mode to a full blown server
which can handle terabytes of data.

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


Re: PEP on path module for standard library

2005-07-23 Thread Duncan Booth
Peter Hansen wrote:
 Just a note, though you probably know, that this is intended to be 
 written this way with path:
 
  p / q
 path(u'a/b/c/d')

I know, but it really doesn't look right to me.

I think that my fundamental problem with all of this is that by making path 
a subclass of str/unicode it inherits inappropriate definitions of some 
common operations, most obviously addition, iteration and subscripting. 

These operations have obvious meaning for paths which is not the same as 
the meaning for string. Therefore (in my opinion) the two ought to be 
distinct.

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


PostgreSQL Python vs PHP

2005-07-23 Thread Luis P. Mendes
Hi,

I don't know anything about PHP and I'm initiating right now with
PostgreSQL.

Could someone tell me the pros and cons of assessing the PostgreSQL
databases with Python vs. PHP?

I will need to build a database that has to be assessed by a dozen clients
via a web page in an intranet (possibly from outside, too).

Is Python more used on the client side and PHP on the server side?

I now Python, although I'm far from being an expert.


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


Re: unit test nested functions

2005-07-23 Thread Raymond Hettinger
  [Andy]
 How can you unit test nested functions?

[Raymond Hettinger]
  For whitebox testing, you could make an inner function visible by
  binding it to the enclosing function's attribute namespace.
 
 def f(x):
 def g(y):
. . .
 f.g = g# make g visible as an attribute of f
 . . .

[Benji York]
 Note that when using this technique, f.g will not be bound until after
 you call the function:

That is a feature, not a bug.  The inner function isn't even created
until the outer function is run.

 def f(x):
z = 30
def g(y):
return 10
return 20

 from dis import dis
 dis(f)
  2   0 LOAD_CONST   1 (30)
  3 STORE_FAST   1 (z)

  3   6 LOAD_CONST   2 (code object g at 00A33660,
file pyshell#37, line 3)
  9 MAKE_FUNCTION0
 12 STORE_FAST   2 (g)

  5  15 LOAD_CONST   3 (20)
 18 RETURN_VALUE

The MAKE_FUNCTION step is where g comes into existence.  That is a
run-time operation, not compile time.

If you are willing to be tricky, it is possible to write an accessor
function that goes into f.func_code.co_consts, finds the code object
whose co_name attribute is 'g', builds a wrapper function using
types.FunctionType, and returns the result for unittesting.  But that
is not for the faint of heart ;-)



Raymond

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


Friend wants to learn python

2005-07-23 Thread EnderLocke
I have a friend who wants to learn python programming. I learned off
the internet and have never used a book to learn it. What books do you
recommend?

Any suggestions would be appreciated.

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


How to realize ssh scp in Python

2005-07-23 Thread 陈阳
I would like to write a Python code like this:It can login a host by SSHafter login the host, use SCP to get a remote file, so it can deliver file to the host.then execute the programthen leave the hostFor example :STEP 1. ssh [EMAIL PROTECTED]STEP 2. Enter the password automatically STEP 3. run  scp -r [EMAIL PROTECTED]:/home/xxx/program .STEP 4. Enter the password for SCP automatically STEP 5. run ./programSTEP 6. run  exitI know telnetlib can help us with telnet, and how to deal with this SSH situation in Python?Thanks a lot for your help :)








需要一个2000兆的免费邮箱吗?网易免费邮箱是中国最多人使用的电子邮箱。





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

Re: Lists pointers

2005-07-23 Thread George Sakkis
[EMAIL PROTECTED] wrote:

 Jan Danielsson wrote:
  Hello all,
 
 I have written a simple whiteboard application. In my application, I
  want to be able to set draw attributes. This part works. I have a
  dictionary object which contains stuff like:
  self.attr['Pen.Color'] = ...
  self.attr['Pen.Thickness'] = ...
 
 Now, the problem is that I want to be able to store attributes in a
  list so they'll be easily accessed using the function keys. I.e. I have
  the current attributes which I want to be able to store or retrieve
  in/from a list,
 
  The problem is that I have initialized the list like this:
 
  self.drawAttr = { blah, blah, blah.. }
  self.storedAttr = [ ]
  for i in range(0, 10):
 self.storedAttr.append(self.drawAttr)
 
 I know what the problem is; they are all referencing the *same*
  dictionary object. So, my question is: How do I initialize a list of
  dictionary objects, where each list entry is its own object (which is a
  copy from the self.drawAttr object).
 
  Also, how do I store/restore entries to the list?
 
 I have found the copy module, and it's copy method. I assume this
  would work:
 
  for i in range(0, 10):
 self.storedAttr.append(copy.copy(self.drawAttr))
 
 However, the concept of deep copy confuses me. Do I want it, or
  don't I want it? I repeat: the attributes object is a simple dictionary.
 
  Thankful for any advice.

 The easiest way to do it would be to create a new dictionary object for
 each iteration of your loop.  In this scenario, you would not need to
 use the copy module.

 In other words:

 self.storedAttr = [ ]
 for i in range(0, 10):
 self.storedAttr.append({ blah, blah, blah.. })

And this would be equivalent to shallow copy. Whether you need a deep copy 
depends on what each
blah is. More specifically it depends on whether the values of the dictionary 
are mutable or not
(the keys are known to be immutable anyway). If they are immutable, a shallow 
copy is enough. If
not, check whether all dictionaries refer to the same values or separate copies 
of the values. Only
in the latter case you need deep copy.

HTH,

George


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


Re: Friend wants to learn python

2005-07-23 Thread Pietro Campesato
Maybe diveintopython.org can help

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


How to realize ssh scp by Python

2005-07-23 Thread 刚 王
I would like to write a Python code like this:It can login a host by SSHafter login the host, use SCP to get a remote file, so it can deliver file to the host.then execute the programthen leave the hostFor example :STEP 1. ssh _yyy at 123.45.67.89STEP 2. Enter the password automatically STEP 3. run " scp -r zzz at 123.45.67.90:/home/xxx/program ."STEP 4. Enter the password for SCP automatically STEP 5. run "./program"STEP 6. run " exit"I know telnetlib can help us with telnet, and how to deal with this SSH situation in Python?Thanks a lot for your help :)__赶快注册雅虎超大容量免费邮箱?http://cn.mail.yahoo.com-- 
http://mail.python.org/mailman/listinfo/python-list

Re: time.time() under load between two machines

2005-07-23 Thread Mike Meyer
[EMAIL PROTECTED] writes:

 I am seeing negative latencies of up to 1 second.  I am  using ntp to
 synchronize both machines at an interval of 2 seconds, so the clocks
 should be very much in sync (and are from what I have observed).  I
 agree that it is probably OS, perhaps I should hop over to a Microsoft
 newsgroup and pose the question, although I'm sure they will find a way
 to blame it on Python.

We're getting off topic here, but what are the two machines ntp
syncing to? Specifically, is one syncing to the other, or are they
both syncing to the same external source, or - worst case - are they
syncing to different external sources? Have you checked the drift file
on the two machines?

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PostgreSQL Python vs PHP

2005-07-23 Thread gene tani
To be honest, this is a pretty open-ended question.  Are there specific
issues (SQL injection/security, minimizing db connections, simplest
code, etc, your'e concerned with?)

To be more honest, googline Python vs. PHP raises lots of hits
http://wiki.w4py.org/pythonvsphp.html
http://www.redcor.ch/wikis/semi_intern/BasicReferenceOfMoreLanguages

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


Re: Getting a dictionary from an object

2005-07-23 Thread Mike Meyer
Steven D'Aprano [EMAIL PROTECTED] writes:
 On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
 Hello.
 
 I would like to have a quick way to create dicts from object, so that a
 call to foo['bar'] would return obj.bar.

 That looks rather confusing to me. Why not just call obj.bar, since it
 doesn't look like you are actually using the dictionary at all?

Well, I needed exactly this functionality last week. I have a
collection of (rather messy) classes that have a slew of attributes as
values. I would have used a dictionary for this, but I didn't write
the code.

I have to be able to display these objects (in HTML, if it matters),
and have as a requirement that the format string live in a database.

My solution didn't look to different from dictobj. There's some extra
mechanism to fetch the format string from the database, and some
formatting of the attribute based on meta-information in the object,
but it's the same basic idea.

 class dictobj(dict):
 
 class dictobj(dict):
 A dictionary d with an object attached to it,
  which treats d['foo'] as d.obj.foo.
 
 def __init__(self, obj):
 self.obj = obj
 def __getitem__(self, key):
 return self.obj.__getattribute__(key)

 I don't think this is particularly useful behaviour. How do you use it?

def __str__(self):
return self._format % self


mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PostgreSQL Python vs PHP

2005-07-23 Thread gene tani
ok, to make this less open-ended, you should mention what O/S and web
server you have in mind, whether the web and DB servers will be under
your admin (big diff betw python and PHP, as far as finding shared
server accounts at web hosts), what kinds of queries, concurrent
read/write volumes, transactions, dirtiness, etc. etc  Also if you
build your questions to this newsgroup on past threads you've read, you
will get absolute superb information, I guarantee it.

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


Re: PostgreSQL Python vs PHP

2005-07-23 Thread Luis P. Mendes
gene tani wrote:

 To be honest, this is a pretty open-ended question.  Are there specific
 issues (SQL injection/security, minimizing db connections, simplest
 code, etc, your'e concerned with?)
Simplest code with be an important factor, since the db will be used far
from max capabilities.  Ease of use of the web page by clients is also a
main factor.

I need to build it from the server and also client side.

For the client side I'll be using Python.

But for the server side, I would like to hear some opinions.  Is it worth
learning Php? 


 
 To be more honest, googline Python vs. PHP raises lots of hits
 http://wiki.w4py.org/pythonvsphp.html
nice link :-)

Thank you,

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Mike Meyer
Peter Hansen [EMAIL PROTECTED] writes:

 * staticmethod Path.getcwd() - Path.cwd()
 * bytes() / lines() / text() - read_file_{bytes,lines,text} methods
 * write_{bytes,lines,text} - write_file_{bytes,lines,text} methods
 Under Linux isn't it possible to open and read from directories much
 as with files?

The OS doesn't matter - python won't let you open a directory as a
file, even if the underlying OS will. The comment in
Objects/fileobject.c is:

/* On Unix, fopen will succeed for directories.
   In Python, there should be no file objects referring to
   directories, so we need a check.  */

I think - but I'm not positive, and don't have a Linux box handy to
check on - that this comment is false if your Unix is really Linux.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unit test nested functions

2005-07-23 Thread Benji York
Raymond Hettinger wrote:
 [Benji York]
 
Note that when using this technique, f.g will not be bound until after
you call the function:
 
 
 That is a feature, not a bug.  The inner function isn't even created
 until the outer function is run.

I'm fully aware of that.  I just didn't want the OP get bit by it.
--
Benji York


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


Re: PostgreSQL Python vs PHP

2005-07-23 Thread Luis P. Mendes
gene tani wrote:

 ok, to make this less open-ended, you should mention what O/S and web
 server you have in mind, whether the web and DB servers will be under
 your admin (big diff betw python and PHP, as far as finding shared
 server accounts at web hosts), what kinds of queries, concurrent
 read/write volumes, transactions, dirtiness, etc. etc  Also if you
 build your questions to this newsgroup on past threads you've read, you
 will get absolute superb information, I guarantee it.
I'll be using Apache, under Linux.
The db server will be under my admin.
A dozen clients acessing the db.
For the first project:
Three or four of them will be using queries mainly from three tables with:
table 1: 350 lines x 20 cols
table 2: 350 lines x 6 cols
table 3: 4200 lines x  5 cols
as an estimate.

Other clients will be very light users but need easy web interface for mouse
clicks only.

Thank you for your support and excuse me for my ignorance, but I'm starting
the project and would like to start it in the right direction.

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


Re: Copying attributes

2005-07-23 Thread Bengt Richter
On Thu, 21 Jul 2005 00:45:12 +0200, red [EMAIL PROTECTED] wrote:

Hi,

I'm writing a script for Blender and need to build a face array. My
engine needs that all faces must be triangles, so I convert quads to 
triangles by dividing them into two triangles. Here is the function:

def build_face_table(mesh):
   face_table = {}
# face_table = [] ??
Irrelevant nit: Why a dict? You seem to be building it with all the keys as 
integers of xrange(last_i),
in which case appending a face_table list to build it and later accessing 
face_table[key]
will go faster than your current dict. OTOH, if you will be deleting various 
elements later,
your dict may be best.

   i = 0
   for f in mesh.faces:
   if len(f.v) == 3:   # triangle
   face_table[i] = f
# face_table.append(f)  # no need for i counting
   i += 1
   elif len(f.v) == 4: # quad
   f1 = NMesh.Face()
   f2 = NMesh.Face()

   f1.mat = f.mat
## f1.normal = copy.deepcopy(f.normal)
   f1.normal = NMesh.Vert(f.normal[0], f.normal[1], 
 f.normal[2])
f is a quad at this point, right? So unless the quad is restricted to a plane, 
it couldn't
have a normal in general. Could that be it? BTW, if it is not a plane, one 
choice of diagonal
may be better than the other in getting two triangles that fit the underlying 
3D surface best.

If there is a normal, why wouldn't ft.normal = f.normal[::] work?
Is normal more than a 3-tuple or list to record unit vector components in some 
coordinate system?

   f1.v.append(f.v[0])
   f1.v.append(f.v[1])
   f1.v.append(f.v[2])
Why append, and is there restricted property magic behind f1.v so that plain old
f1.v = f.v[:3]
wouldn't work?
# or f1.v = [f.v[0], f.v[1], f.v[2]] if you want to be 
consistent with f2 below

   f2.mat = f.mat
# f2.normal = ?? # could this face be picked up later 
indirectly and cause the missing normal exception?

   f2.v.append(f.v[2])
   f2.v.append(f.v[3])
   f2.v.append(f.v[0])
Why appends? Does f2.v ever grow beyond 3 items? E.g.,
f2.v = [f.v[2], f.v[3], f.v[0]]  # are quad vertices 
listed clockwise or ccw and
 # are triangles in a 
sequence totally independent, or
 # is there some 
systematic vertex sharing in the order
 # that something might 
depend on, or benefit optimization-wise from?


   face_table[i] = f1
#face_table.append(f1) ??
   i += 1
   face_table[i] = f2
#face_table.append(f2) ??
   i += 1
   else:
   message = Can't build face from 2 vertices.
Why is len(f.v)4 not just a 3D surface point cluster, 
in which case it might
be possible to find an internal point to slice 
radiating triangles from. E.g.,
imagine an almost-plane small pentagon on a large 
sphere, and slice from its center
to each peripheral pair of vertices to make triangles.
   Draw.PupMenu(Face Table Error%t|+message)
   return
   return face_table
# do you need it as a dict? Unless you modify it, a list will get you
# the same elements as your dict by writing face_table[some_index]

If you need to iterate and have both index key and value, you can use your dict 
like
for i, face in sorted(face_table.items()): # leave out sorted call if 
order does not matter
# ...
or use the more efficient list version of face_table like
for i, face in enumerate(facetable): # will naturally be in sort order
# ...

Everything seems be ok, but i'm getting:

Traceback (most recent call last):
File string, line 169, in write
File string, line 102, in build_face_table
AttributeError: normal

I was wondering why? Though the face has an attribute called normal! 
Just simply test:

nv = f.normal

and it works! But why my new faces (f1 and f2) no?
Did it work on a quad face? What about putting in a debug print before places 
you use
f.normal, e.g.
assert hasattr(f, 'normal'), 'This f\n\n%r\n\ndid not have a 
normal attribute!!' % f

If f.repr doesn't give you enough info, you can format something better in the 
assert message string.

Greetings.

-- 
_red  _   __ _

BTW, I don't know Blender at all, just reading between the lines ;-)
Hope I triggered a useful 

Re: Lists pointers

2005-07-23 Thread Kay Schluehr
Jan Danielsson wrote:
 Hello all,

I have written a simple whiteboard application. In my application, I
 want to be able to set draw attributes. This part works. I have a
 dictionary object which contains stuff like:
 self.attr['Pen.Color'] = ...
 self.attr['Pen.Thickness'] = ...

Now, the problem is that I want to be able to store attributes in a
 list so they'll be easily accessed using the function keys. I.e. I have
 the current attributes which I want to be able to store or retrieve
 in/from a list,

 The problem is that I have initialized the list like this:

 self.drawAttr = { blah, blah, blah.. }
 self.storedAttr = [ ]
 for i in range(0, 10):
self.storedAttr.append(self.drawAttr)

I know what the problem is; they are all referencing the *same*
 dictionary object. So, my question is: How do I initialize a list of
 dictionary objects, where each list entry is its own object (which is a
 copy from the self.drawAttr object).

Hi Jan son of Daniel,

you might initialize self.storedAttr with empty dicts and fill them
later:

self.soredAttr = [{}]*10
for entry in self.storedAttr:
entry.update(self.drawAttr)


 Also, how do I store/restore entries to the list?

I have found the copy module, and it's copy method. I assume this
 would work:

 for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))

However, the concept of deep copy confuses me. Do I want it, or
 don't I want it? I repeat: the attributes object is a simple dictionary.

 Thankful for any advice.

A *shallow copy* creates a new dictionary and copies the references, a
*deep copy* tries to create a new reference for each existing object in
the dict. The disadvantage of deepcopy is that it does not work in many
cases:

 copy.deepcopy([lambda :None])
Traceback (most recent call last):
...
TypeError: function() takes at least 2 arguments (0 given)

As the docs tell:

This version does not copy types like module, class, function, method,
stack trace, stack frame, file, socket, window, array, or any similar
types.

I wonder if one couldn't pickle a module and reimport it in order to
create a copy of it ;)

IMO this is a weakness of the algorithm. One usually doesn't want to
duplicate a function so that a new reference of a function is not
needed because it is readonly and the algorithm could reuse the same
reference. For classes I don't if the assertion in the docs is actually
true?

 class A:pass
 copy.deepcopy(A)
class __main__.A at 0x01191990

 class A(object):
... def __init__(self):pass
... 
 copy.deepcopy(A)
class '__main__.A'
 

Regards,
Kay

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


Re: consistency: extending arrays vs. multiplication ?

2005-07-23 Thread Robert Kern
Soeren Sonnenburg wrote:
 Hi all,
 
 Just having started with python, I feel that simple array operations '*'
 and '+' don't do multiplication/addition but instead extend/join an
 array:
 
 a=[1,2,3]

This isn't an array. It is a list. If you want an array, use 
Numeric/numarray. If you want lists, use lists. Lists will never grow 
the kind of behavior you're asking for.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die.
   -- Richard Harter

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


Re: Friend wants to learn python

2005-07-23 Thread Martin P. Hellwig
EnderLocke wrote:
 I have a friend who wants to learn python programming. I learned off
 the internet and have never used a book to learn it. What books do you
 recommend?
 
 Any suggestions would be appreciated.
 

I recommend Learning Python 2nd Edition by Mark Lutz  David Ascher 
(O'Reilly) its reasonable easy to read no heavy language, but clear 
concept and examples.
It does not require any previous programming experience, although being 
comfortable with computer terms and knowing some basic concepts of 
programming does make you read faster through the book.
My overall conclusion was that the authors know what they are talking 
about and are honest in what they want to achieve.

When done with that the reader has enough experience to at least know 
where to go further to learn more about python.

-- 
mph

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


How can I get an sha1 hash in base32?

2005-07-23 Thread Elmo Mäntynen
I know how to make a hash(using mhash), but instead of encoded as hex I
want it in base32 for use with the bitzi catalog. python-bitzi is useful
but way too slow for just getting the hash of a file(am going to use it
elsewhere). Thanks.

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Reinhold Birkenfeld
Peter Hansen wrote:
 Reinhold Birkenfeld wrote:
 Peter Hansen wrote (on Paths not allowing comparison with strings):
Could you please expand on what this means?  Are you referring to doing 
 and = type operations on Paths and strings, or == and != or all those 
or something else entirely?
 
 All of these. Do you need them?
 
 I believe so.  If they are going to be basestring subclasses, why should 
 they be restricted in any particular way?  I suppose that if you wanted 
 to compare a Path to a string, you could just wrap the string in a Path 
 first, but if the Path is already a basestring subclass, why make 
 someone jump through that particular hoop?

Do you have a use case for the comparison? Paths should be compared only
with other paths.

Other minor differences, as requested on python-dev, are:

* size property - getsize() method.
* atime/mtime/ctime properties - atime()/mtime()/ctime() methods

What does this mean?  The .size property and a getsize() method both 
already exist (in my copy of path.py anyway) and do the same thing. 
Same with the other ones mentioned above.  Is someone working from an 
out-of-date copy of path.py?
 
 No. But the size of a file is somewhat volatile, and does not feel like
 a property of the path to it. Remember: the path is not the file. Same
 goes with the xtime() methods.
 
 Oh, so your original text was meant to imply that those properties *were 
 being removed*.  That wasn't at all clear to me.
 
 I understand the reasoning, but I'm unsure I agree with it.  I fully 
 accept that the path is not the file, and yet I have a feeling this is a 
 pedanticism: most of the time when one is dealing with the _file_ one is 
 concerned with the content, and not much else.  When one is dealing with 
 the _path_ one often wants to check the size, the modification time, and 
 so forth.  For example, once one has the file open, one very rarely is 
 interested in when it was last modified.

My line of thought is that a path may, but does not need to refer to an
existing, metadata-readable file. For this, I think a property is not
proper.

 In other words, I feel once again that Jason's original intuition here 
 was excellent, and that he chose practicality over purity in appropriate 
 ways, in a very Pythonic fashion.  I confess to feeling that the 
 suggested changes are being proposed by those who have never actually 
 tried to put path.py to use in practical code, though I'm sure that's 
 not the case for everyone making those suggestions.
 
 Still, once again this doesn't seem a critical issue to me and I'm happy 
 with either approach, if it means Path gets accepted in the stdlib.
 
 At the moment, I think about overriding certain string methods that make
 absolutely no sense on a path and raising an exception from them.
 
 That would seem reasonable.  It seems best to be very tolerant about 
 what makes no sense, though istitle() would surely be one of those to 
 go first.  Also capitalize() (in spite of what Windows Explorer seems to 
 do sometimes), center(), expandtabs(), ljust(), rjust(), splitlines(), 
 title(), and zfill().  Hmm... maybe not zfill() actually.  I could 
 imagine an actual (if rare) use for that.

I'll look into it. What about iteration and indexing? Should it support
for element in path or for char in path or nothing?

.bytes() and friends have felt quite 
friendly in actual use, and I suspect .read_file_bytes() will feel quite 
unwieldy.  Not a show-stopper however.
 
 It has even been suggested to throw them out, as they don't have so much to
 do with a path per se. When the interface is too burdened, we'll have less
 chance to be accepted. Renaming these makes clear that they are not 
 operations
 on the path, but on a file the path points to.
 
 Here again I would claim the practicality over purity argument.  When 
 one has a Path, it is very frequently because one intends to open a file 
 object using it and do reads and writes (obviously).  Also very often, 
 the type of reading and writing one wants to do is an all at once type 
 of thing, as those methods support.  They're merely a convenience, to 
 save one doing the Path(xxx).open('rb').read thing when one can merely 
 do Path(xxx).bytes(), in much the same way that the whole justification 
 for Path() is that it bundles useful and commonly used operations 
 together into one place.
 
 Phillip J. Eby suggested these to be set_file_xxx and get_file_xxx to 
 demonstrate
 that they do not read or write a stream; how about that?
 
 If they are there, they do exactly what they do, don't they?  And they 
 do file.read() and file.write() operations, with slight nuances in the 
 mode passed to open() or the way the data is manipulated.  Why would one 
 want to hide that, making it even harder to tie these operations 
 together with what is really going on under the covers?  I think the 
 existing names, or at least ones with _read_ and _write_ in them 
 somewhere are better than set/get alternatives. 

Re: Lists pointers

2005-07-23 Thread André Malo
* Kay Schluehr wrote:

 you might initialize self.storedAttr with empty dicts and fill them
 later:
 
 self.soredAttr = [{}]*10
 for entry in self.storedAttr:
 entry.update(self.drawAttr)

As a matter of fact, you're doing the same ;-)

In [1]: x = [{}] * 10

In [2]: x[0]['a'] = 1

In [3]: x[1]['b'] = 2

In [4]: x
Out[4]:
[{'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2},
 {'a': 1, 'b': 2}]

nd
-- 
Umfassendes Werk (auch fuer Umsteiger vom Apache 1.3)
  -- aus einer Rezension

http://pub.perlig.de/books.html#apache2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I get an sha1 hash in base32?

2005-07-23 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Elmo Mäntynen wrote:

 I know how to make a hash(using mhash), but instead of encoded as hex I
 want it in base32 for use with the bitzi catalog. python-bitzi is useful
 but way too slow for just getting the hash of a file(am going to use it
 elsewhere). Thanks.

Doesn't Bitzi calculate some kind of audio fingerprint?  Just a hash of
the file would result in very different hash values for different codecs,
bitrates etc. for the same audio data.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: consistency: extending arrays vs. multiplication ?

2005-07-23 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Soeren
Sonnenburg wrote:

 Just having started with python, I feel that simple array operations '*'
 and '+' don't do multiplication/addition but instead extend/join an
 array:
 
 a=[1,2,3]
 b=[4,5,6]
 a+b
 [1, 2, 3, 4, 5, 6]

Both operate on the lists themselves and not on their contents.  Quite
consistent if you ask me.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP on path module for standard library

2005-07-23 Thread Bengt Richter
On Sat, 23 Jul 2005 07:05:05 +1000, John Machin [EMAIL PROTECTED] wrote:

Daniel Dittmar wrote:
 Duncan Booth wrote:
 
  I would have expected a path object to be a sequence of path elements 
 rather than a sequence of characters. 
 
 
 Maybe it's nitpicking, but I don't think that a path object should be a 
 'sequence of path elements' in an iterator context.
 
 This means that
 
 for element in pathobject:
 
 has no intuitive meaning for me, so it shouldn't be allowed.

Try this:

A file-system is a maze of twisty little passages, all alike. Junction 
== directory. Cul-de-sac == file. Fortunately it is signposted. You are 
dropped off at one of the entrance points (current directory, say). 
You are given a route (a path) to your destination. The route consists 
of a list of intermediate destinations.

for element in pathobject:
follow_sign_post_to(element)

Exception-handling strategy: Don't forget to pack a big ball of string. 
Anecdotal evidence is that breadcrumbs are unreliable.

indulging what=my penchant for seeking the general behind the specific ;-) 

ISTM a path is essentially a representation of a script whose interpretation
by an orderly choice of interpreters finally leads to accessing to some entity,
typically a serial data representation, through an object, perhaps a local 
proxy,
that has standard methods for accessing the utimate object's desired info.

IOW, a path sequence is like a script text that has been .splitline()'d and
and the whole sequence fed to a local interpreter, which might chew through 
multiple
lines on its own, or might invoke interpreters on another network to deal with 
the
rest of the script, or might use local interpreters for various different kinds 
of
access (e.g., after seeing 'c:' vs 'http://' vs '/c' vs '//c' etc. on the 
platform
defining the interpretation of the head element).

Turning a single path string into a complete sequence of elements is not 
generally possible
unless you have local knowledge of the syntax of the entire tail beyond the the 
prefix
you have to deal with. Therefore, a local platform-dependent Pathobject class 
should, I think,
only recognize prefixes that it knows how to process or delegate processing 
for, leaving
the interpretation of the tail to the next Pathobject instance, however 
selected and/or
located.

So say (this is just a sketch, mind ;-)

po = Pathobject(string representation of whole path)

results in a po that splits out (perhaps by regex) a prefix, a first 
separator/delimiter,
and the remaining tail. E.g., in class Pathobject,
def __init__(self, pathstring=None)
if pathstring is None: #do useful default??
self.pathstring = pathstring
self.prefix, self.sep, self.tail = self.splitter(pathstring)
if self.prefix in self.registered_prefixes:
self.child = self.registered_prefixes[self.prefix](self.tail)
else:
self.child = []
self.opened_obj = None

Then the loop inside a local pathobject's open method po.open()
might go something like

def open(self, *mode, **kw):
if self.child:
self.opened_obj = self.child.open(self.tail, *mode, **kw)
else:
self.opened_obj = file(self.pathstring, *mode)
return self

And closing would just go to the immediately apparent opened object, and
if that had complex closing to do, it would be its responsibility to deal
with itself and its child-derived objects.

def close(self):
self.opened_object.close()


The point is that a given pathobject could produce a new or modified pathobject 
child
which might be parsing urls instead of windows file system path strings or could
yield an access object producing something entirely synthetic.

A synthetic capability could easily be introduced if the local element 
pathobject
instance looked for e.g., 'synthetic://' as a possible first element (prefix) 
string representation,
and then passed the tail to a subclass defining synthetic:// path 
interpretation.
E.g., 'synthetic://temp_free_diskspace' could be a platform-independent way to 
get such info as that.

Opening 'testdata:// ...' might be an interesting way to feed test suites, if 
pathobject subclasses
could be registered locally and found via the head element's string 
representation.'

One point from this is that a path string represents an ordered sequence of 
elements, but is heterogenous,
and therefore has potentially heterogenous syntax reflected in string tails 
with syntax that should be
interpreted differently from the prefix syntax.

Each successive element of a path string effectively requires an interpreter 
for that stage of access
pursuit, and the chain of processing may result in different path 
entities/objects/representations
on different systems, with different interpretations going on, sharing only 
that they are part of the
process of getting access to something and providing access services, if it's 
not a one-shot access.


Re: Getting a dictionary from an object

2005-07-23 Thread Thanos Tsouanas
On Sat, Jul 23, 2005 at 11:22:21PM +1000, Steven D'Aprano wrote:
 On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
  Hello.
  
  I would like to have a quick way to create dicts from object, so that a
  call to foo['bar'] would return obj.bar.
 
 That looks rather confusing to me. Why not just call obj.bar, since it
 doesn't look like you are actually using the dictionary at all?
 
  [...]
 
 I don't think this is particularly useful behaviour. How do you use it?

print foo %do

where do is a dictobj object...

-- 
Thanos Tsouanas  .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGTK or wxPython (not a flame war) on Windows

2005-07-23 Thread Marek Kubica
Hello!

 How well does PyGTK run on Windows (98, 2K, XP)? How stable is it? Will
 I be able to make an executable (using Py2Exe) of an application that
 uses PyGTK?

I _do_ like PyGTK on Windows. It works without problems.
You can find a ready to use py2exe script on
http://www.pythonwiki.de/PyGtk. You could also bundle the runtime DLLs with
your py2exe'd application, but I have never done this. You could try doing
this like described here:
http://aspn.activestate.com/ASPN/Mail/Message/py2exe-users/2476686 (use the
setup.py script from the wiki and start at (2) in the mail).

HTH.

greets,
Marek

PS: Yes, I admit it is harder than py2exe + wxPython but I still like
PyGTK.

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread John Roth

Reinhold Birkenfeld [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]


 I'll look into it. What about iteration and indexing? Should it support
 for element in path or for char in path or nothing?

I frankly can't think of a use for iterating over the characters in
the path, but I have a number of programs that check elements,
iterate over them and index them (frequently backwards).

I also like to know the number of elements, which seems to make
sense as len(path). Again, the number of characters in the path seems
to be utterly useless information - at least, I can't imagine a use for
it.

John Roth


 Reinhold 

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


Re: dictionary that discards old items

2005-07-23 Thread Bengt Richter
On 21 Jul 2005 19:29:32 -0700, Raymond Hettinger [EMAIL PROTECTED] wrote:

[Will McGugan]
 I need a collection class that behaves like a dictionary but when it
 reaches 'n' items it discards the oldest item so that the length never
 goes above 'n'. (Its for caching search results)


import collections

class Cache(dict):
def __init__(self, n, *args, **kwds):
self.n = n
self.queue = collections.deque()
dict.__init__(self, *args, **kwds)
def __setitem__(self, k, v):
self.queue.append(k)
dict.__setitem__(self, k, v)
if len(self)  self.n:
oldk = self.queue.popleft()
del self[oldk]

#  . . .
# make similar modifications to setdefault, __delitem__, fromkeys
# and other mutating methods as needed

# Example
c = Cache(3)
for w in 'the quick brown fox jumped over the lazy dog'.split():
c[w] = w[:1].upper()
print repr(c)


Minor comment: There is a potential name collision  problem for keyword 
n=something,
so what is considered best practice to avoid that? __n or such as the n arg?

  def foo(n, *args, **kw): print n, args, kw
 ...
  foo(1)
 1 () {}
  foo(n=5)
 5 () {}
  foo(3, n=5)
 Traceback (most recent call last):
   File stdin, line 1, in ?
 TypeError: foo() got multiple values for keyword argument 'n'
 

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython - DB Form generator unit

2005-07-23 Thread Peter Decker
On 7/19/05, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 Is anyone know about a DB form generator unit under wxPython ?
 What that's means ?
 
 I add information about a Query, or a ListOfDict, I set some other infos
 (Lookups, others), and it is generate a Form with edit boxes, listboxes,
 etc.
 Then I can fill up the form with a record's datas. User can modify them.
 After I can call Apply method, and every modifications are stored in a
 result.

You should look into Dabo. It is a framework for creating database
apps, and comes with a wizard that lets you create an app that
queries, updates, edits, adds and deletes records in a variety of
databases. What database are you using?

# p.d.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: return None

2005-07-23 Thread Christopher Subich
Grant Edwards wrote:
 Personally, I don't really like the idea that falling off the
 botton of a function implicitly returns None.  It's just not
 explicit enough for me.  My preference would be that if the
 function didn't execute a return statement, then it didn't
 return anyting and attempting to use a return value would be an
 error.

This is a bad idea.  Classically, distinguishing between functions that 
return things and functions that don't return things explicitly divides 
the callable object space.  From my CS101 class with its incredibly 
exciting dive into the world of useless pseudocode, callables that 
returned things were called 'functions' and callables that didn't were 
called 'procedures'.

Some languages do make this distinction; QBASIC, for example, had 
'gosub' separate from function calls.

What do you do for an early break from a function that still returns 
not-even-None [ReallyNone], return?  That looks and acts like a 'real' 
return statement, and the distinction between 
return-without-a-value-so-maybe-except and return-with-a-value is 
suddenly magnified to real importance.

Further, and I consider this a truly damning case, look at decorater.  A 
naive logging decorator could be defined like this:

def logger(func):
def new_func(*args, **kwargs):
   print '%s called with:' % func.__name__, args, kwargs
   retval = func(*args,**kwargs)
   print '%s returns:', retval
   return retval
return new_func

This logger works without modification for both value and non-value 
returning functions.  Its output isn't quite as pretty for non-value 
functions, but it works and the implementation is both simple and flexible.

With a function-schism, to keep its simple implementation 'logger' would 
have to be rewritten as 'flogger' (same as current-logger, for use on 
functions), and 'plogger' (for use on procedures).  The downside here is 
that if the function/method changed to or from a procedure, the 
decorator would have to be switched.

Alternatively, the logger decorator could be longer and explicitly catch 
the possible exception.  But why should we have to write like that, for 
a use-case that doesn't even represent a true error -- arguably not even 
an exceptional case?  Python's definitely not a BD language, talk of 
floggers aside.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aliasing an object's __str__ to a different method

2005-07-23 Thread Christopher Subich
Paolino wrote:
 Little less ugly:
 In [12]:class A(object):
: def __str__(self):return self.__str__()
: def str(self):return 'ciao'
: def setStr(self):self.__str__=self.str
:
 
 In [13]:a=A()
 
 In [14]:a.setStr()
 
 In [15]:str(a)
 Out[15]:'ciao'

Not quite bug-free, by my eye that'll infintely recur if you call str(A()).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a dictionary from an object

2005-07-23 Thread Steven Bethard
Thanos Tsouanas wrote:
 I would like to have a quick way to create dicts from object, so that a
 call to foo['bar'] would return obj.bar.
 
 The following works, but I would prefer to use a built-in way if one
 exists.  Is there one?

Maybe I'm not understanding your problem, but have you looked at the 
builtin vars()?

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


Re: PostgreSQL Python vs PHP

2005-07-23 Thread Ivan Voras
Luis P. Mendes wrote:

 I need to build it from the server and also client side.
 
 For the client side I'll be using Python.
 
 But for the server side, I would like to hear some opinions.  Is it worth
 learning Php? 

If you know Python and don't know PHP, there's little benefit from 
spending the time learning it.

But, PHP is extremely simple to work with and you can produce results 
VERY quickly. Part of the reason is that it's already intended to be a 
web-embedded language and doesn't reqire additonal frameworks, libraries 
or configuration like Python does. One thing that botheres me when using 
Python in php-like way is that the indentation is significant property 
becomes a nuisance when you intertwine HTML and code (which you 
shouldn't be doing anyway ;) ).

The benefit of Python is that is a much cleaner language with well 
defined interfaces and you'll probably maintain a large application 
easier if it's in Python.

There are no significant performance differences, and no really 
significant differences in programming approach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Copying attributes

2005-07-23 Thread Bengt Richter
On Sat, 23 Jul 2005 18:30:29 GMT, [EMAIL PROTECTED] (Bengt Richter) wrote:
[...]
Did it work on a quad face? What about putting in a debug print before places 
you use
f.normal, e.g.
assert hasattr(f, 'normal'), 'This f\n\n%r\n\ndid not have a 
 normal attribute!!' % f

If f.repr doesn't give you enough info, you can format something better in the 
assert message string.

f.__repr__ was what I meant (as called due to %r in format), sorry.

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is this possible?

2005-07-23 Thread Terry Hancock
On Saturday 23 July 2005 03:26 am, Steven D'Aprano wrote:
 On Fri, 22 Jul 2005 07:59:42 -0700, scrimp wrote:
 As others have suggested, if you have to deal with PDF files without
 Acrobat, you could use ghostscript. Also pre-installed on many versions
 of Linux, and probably other Unixes as well, is pdf2ps which will convert
 the PDF file to a pure postscript file, which you can then print to any
 printer which understands postscript.

IIRC, pdf2ps is a utility that comes with Ghostscript, and actually
does use it to do the transformation (that is, I think it's just a script
to run ghostscript with the appropriate options).

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: dictionary that discards old items

2005-07-23 Thread Steven Bethard
[Raymond Hettinger]
class Cache(dict):
   def __init__(self, n, *args, **kwds):
   self.n = n
   self.queue = collections.deque()
   dict.__init__(self, *args, **kwds)

[Bengt Richter]
 Minor comment: There is a potential name collision  problem for keyword 
 n=something,
 so what is considered best practice to avoid that? __n or such as the n arg?

I don't know what best practice is, but if you want to guarantee to 
avoid the name collision, you can write:

def __init__(*args, **kwargs):
 self = args[0]
 self.n = args[1]
 self.queue = collections.deque()
 dict.__init__(self, *args[2:], **kwargs)

It's not pretty though. ;)

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


Re: tuple to string?

2005-07-23 Thread Steven D'Aprano
On Sat, 23 Jul 2005 23:26:19 +1000, John Machin wrote:

 Steven D'Aprano wrote:
 
 
 
''.join(map(lambda n: chr(n), (0x73, 0x70, 0x61, 0x6D)))
 
 'spam'
 
 Why the verbal diarrhoea? 

One line is hardly verbal diarrhoea.

 What's wrong with the (already posted)
 
 ''.join(map(chr, (0x73, 0x70, 0x61, 0x6D)))
 
 ???

Nothing.

If I had seen the already posted solution using chr on its own without
lambda, I wouldn't have bothered posting the lambda solution. But I
didn't, so I did.

As another poster has already pointed out, lambda cries out for over-use,
and this was a perfect example of it.


-- 
Steven.

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


Re: tuple to string?

2005-07-23 Thread Steven D'Aprano
On Sat, 23 Jul 2005 23:31:04 +1000, John Machin wrote:

You don't need the sissy parentheses; '%c' * len(t) % t works just fine :-)
 
 
 Ah, ok. Didn't want to lookup the precedence rules...
 
 
 Look up the precedence rules? Are you aware of any language where * / 
 and % _don't_ have the same precedence??

Do languages like Pascal that don't have string formatting expressions, or
use the % operator, count?

How about languages like Forth that don't have precedence rules at all,
unless first come, first served is a precedence rule?

I'm not being academic here. I have used both these languages extensively,
admittedly many years ago.


-- 
Steven.

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


Re: [path-PEP] Path inherits from basestring again

2005-07-23 Thread Peter Hansen
Reinhold Birkenfeld wrote:
[on comparing Paths and stings]
 Do you have a use case for the comparison? Paths should be compared only
 with other paths.

I can think of lots, though I don't know that I've used any in my 
existing (somewhat limited) code that uses Path, but they all involve 
cases where I would expect, if comparisons were disallowed, to just wrap 
the string in a Path first, even though to me that seems like it should 
be an unnecessary step:

   if mypath.splitpath()[0] == 'c:/temp':

   if 'tests' in mypath.dirs():

   and lots of other uses which start by treating a Path as a string
   first, such as by doing .endswith('_unit.py')

Any of these could be resolved by ensuring both are Paths, but then I'm 
not sure there's much justification left for using a baseclass of 
basestring in the first place:

   if mypath.splitpath()[0] == Path('c:/temp'):

   if Path('tests') in mypath.dirs():

Question: would this latter one actually work?  Would this check items 
in the list using comparison or identity?  Identity would simply be 
wrong here.

[on removing properties in favour of methods for volatile data]
 My line of thought is that a path may, but does not need to refer to an
 existing, metadata-readable file. For this, I think a property is not
 proper.

Fair enough, though in either case an attempt to access that information 
leads to the same exception.  I can't make a strong argument in favour 
of properties (nor against them, really).

 What about iteration and indexing? Should it support
 for element in path or for char in path or nothing?

As John Roth suggests, the former seems a much more useful thing to do. 
  The latter is probably as rarely needed as it is with regular strings 
(which I believe is roughly never in Python).

[on .read_file_bytes() etc]
 I think it is not exactly bad that these names are somehow outstanding,
 as that demonstrates that something complex and special happens.

Point taken.  What about ditching the file part, since it is redundant 
and obvious that a file is in fact what is being accessed.  Thus: 
.read_bytes(), .read_text(), .write_lines() etc.

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


Re: return None

2005-07-23 Thread Christopher Subich
Christopher Subich wrote:
   print '%s returns:', retval
Not that it matters, but this line should be:
   print '%s returns:' % func.__name__, retval
-- 
http://mail.python.org/mailman/listinfo/python-list


what's wrong with my code using subprocess?

2005-07-23 Thread Qiangning Hong
I decide to seperate my data collection routine from my data analysis
and storage program to a seperate process, so I try to use the new
subprocess model in Python 2.4.

The main program spawns the subprocess and receives data from the
pipe.  When some event occurs (e.g. the user clicks the 'Stop' button
on GUI), the main program will send the subprocess a command to change
its behavior or ask it to exit.

However, my code (attached below) doesn't work.  Under Linux, the output is:
output
waiting subprocess exit
Traceback (most recent call last):
  File receiver.py, line 19, in ?
main()
  File receiver.py, line 13, in main
print p.stdin, 'exit'
IOError: [Errno 32] Broken pipe
/output

And Under Windows XP, p.wait() never returns:
output
waiting subprocess exit
[hanging here]
/output

What's wrong?  

# collector.py
import threading

class Main(object):
def __init__(self):
self.keep_going = True
self.t = threading.Thread(target=self.work)
self.t.start()

cmd = raw_input()
while cmd != 'exit':
cmd = raw_input()

self.keep_going = False
self.t.join()

def work(self):
while self.keep_going:
print '$' * 82

if __name__ == '__main__':
Main()


# receiver.py (the main program)
from subprocess import Popen, PIPE

def main():
p = Popen(['python', 'collector.py'], stdout=PIPE, stdin=PIPE)
count = 0
for line in p.stdout:
data = line.strip()
# process(data)
count += 1
if count = 1000:
print p.stdin, 'exit'
print 'waiting subprocess exit'
p.wait()

if __name__ == '__main__':
main()


-- 
Qiangning Hong

I'm usually annoyed by IDEs because, for instance, they don't use VIM
as an editor. Since I'm hooked to that, all IDEs I've used so far have
failed to impress me.
   -- Sybren Stuvel @ c.l.python

Get Firefox! http://www.spreadfirefox.com/?q=affiliatesamp;id=67907amp;t=1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lists pointers

2005-07-23 Thread Steven D'Aprano
On Sat, 23 Jul 2005 17:03:08 +0200, Jan Danielsson wrote:

 The problem is that I have initialized the list like this:
 
 self.drawAttr = { blah, blah, blah.. }
 self.storedAttr = [ ]
 for i in range(0, 10):
self.storedAttr.append(self.drawAttr)
 
I know what the problem is; they are all referencing the *same*
 dictionary object. So, my question is: How do I initialize a list of
 dictionary objects, where each list entry is its own object (which is a
 copy from the self.drawAttr object).

self.drawAttr = { blah, blah, blah.. }
self.storedAttr = [ ]
for i in range(0, 10):
self.storedAttr.append(self.drawAttr.copy())

You only need to worry about the difference between copy and deepcopy if
the objects inside the dict are complex objects like dicts and lists.

You also said that: I want to be able to store attributes in a list so
they'll be easily accessed using the function keys.

I don't think this is good usage. What happens when you change the
attributes in one place but forget to change it in the other?

A better solution would be to set up either a list or a mapping from
function key to attribute, rather than to a COPY of the attribute. Why
change things in two places rather than one?

Something like this:

# set up attributes before hand
self.attr['Pen.Color'] = 'blue'
self.attr['Pen.Thickness'] = 1
self.attr['Pen.State'] = 'down'
# etc
# now point the function keys to attributes
self.functionkeys = {'F1' = 'Pen.Color', 'F2' = 'Pen.Thickness', 
'F3' = 'Pen.State', ... }

Then, when you want to access the current value of some attribute, instead
of looking up a list:

# bad way
def get_attribute(fkey):
if fkey = 'F1':
return self.storedAttr[0]
elif fkey = 'F2':
return self.storedAttr[1]
...
elif fkey = 'F12':
return self.storedAttr[11]

you would do something like this:

# good way
def get_attribute(fkey):
return self.attr[self.functionkeys[fkey]]



 Also, how do I store/restore entries to the list?

That question is awfully open-ended. Can you be more specific?



I have found the copy module, and it's copy method. I assume this
 would work:
 
 for i in range(0, 10):
self.storedAttr.append(copy.copy(self.drawAttr))
 
However, the concept of deep copy confuses me. Do I want it, or
 don't I want it? I repeat: the attributes object is a simple dictionary.

That depends on what is inside your simple dictionary. For immutable
objects like ints, floats and strings, copy is sufficient:

 D1 = {1: 'hello', 2: 'there'}
 D1
{1: 'hello', 2: 'there'}
 D2 = D1.copy()
 D1[1] = 'go'
 D1
{1: 'go', 2: 'there'}
 D2
{1: 'hello', 2: 'there'}

See what happens when the values are mutable objects:

 DM1 = {1: [0,1], 2: [4, 5]}
 DM2 = DM1.copy()
 DM1[3] = [0,2]
 DM1
{1: [0, 1], 2: [4, 5], 3: [0, 2]}
 DM2
{1: [0, 1], 2: [4, 5]}

So far so good. But now look:

 DM1[1].append(999)
 DM1
{1: [0, 1, 999], 2: [4, 5], 3: [0, 2]}
 DM2
{1: [0, 1, 999], 2: [4, 5]}

The difference is that although copy makes a copy of the top level of the
dict, it DOESN'T make copies of the individual objects within the dict.  

This doesn't matter is the objects are immutable, but if they are lists or
other dicts, you can get surprises like the above.


-- 
Steven.

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


  1   2   >