Re: "0 in [True,False]" returns True

2005-12-14 Thread Antoon Pardon
Op 2005-12-13, Steve Holden schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Op 2005-12-13, Chris Mellon schreef <[EMAIL PROTECTED]>:
> [...]
>>>If you have a consistent API and you're checking for error values from
>>>your GTK functions, then you already have a lot more code than using 2
>>>varaibles will cost you. 10 lines, maybe.
>>>
>>>The fact that you think setting two variables is "too hard" but you're
>>>perfectly happy with checking for boolean types instead just testing
>>>truth values I think is a real problem.
>> 
>> 
>> These aren't just truth values. If I would have to go split in 
>> meaningfull truth values I would need at least three variables.
>> 
>> 
>>>You aren't saving yourself any
>>>performance. You're barely even saving yourself any typing, and you're
>>>making your code (intentionally, it seems) that much more compllicated
>>>and hard to understand.
>> 
>> 
>> There is nothing complicated or hard to understand.
>> 
> Nope, just a messy, hard to maintain misuse of a single variable for 
> multiple purposes.

No that variable has just one purpose, noting the state of the tube.

> Perfectly simple, perfectly easy to understand and 
> rather more bug-prone that a straightforward separation of state and 
> other data.

What you call other date is IMO just state information.

>> I find it odd that each time declaration are mentioned people here
>> react very rejecting and say that one of the features they love
>> about python is the freedom that a name is not limited to a variable
>> of one type, while when someone makes use of that freedom labeling
>> such code as code smell.
>> 
> There's a difference between using a single name to refer to values of 
> polymorphic types (which can therefore all be handled by the same code) 
> and using the same name to reference state information in one case (this 
>   item has no connected callback) and other data (the callback is to 
> such-and-such an object).
>
>> But lets make an effort to make the code more readable. What
>> about the following suggestion. I use a kind of EnumType with
>> two values: NotRegistered and Registerd. And the name of the
>> type is NotConnected. So I can then write
>> 
>>   if type(self.callback) is NotConnected.
>> 
>> Would that be selfdocumenting enough for you?
>> 
> It would be somewhat more self-documenting, but why not just use one 
> name to indicate the state and another, only meaningful in certain 
> states, to indicate the callback?

Why should I do that? Checking the type of a variable is conceptually
no different form testing set membership. So what I did, was just
bringing two disjoint sets togther and working with a variable from
that union. This is all in all a rather simple mathematical idea.
And I don't see why I should put certain information into a seperate
variable. It makes as much sense as working with numbers and using
a seperate variable to store whether a particular number is postive,
even or has some other characteristic. You don't seperate information
you can easily acquire from the variable itself. So why should I
seperate this information that is aquired just as easily?

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


Windows Services

2005-12-14 Thread Mondal
Hi,

Can anybody tell me how to develop Windows Services (which are actually
daemons) using Python. Also what protocol is most suitable for
developing a server-client application with the server running as a
Windows Service.

Thanks in advance

Bye

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


Re: IsString

2005-12-14 Thread Steven D'Aprano
Mike Meyer wrote:

>>So Python behaves demonstrably different from BOTH call by value and call
>>by reference. Consequently, it is neither of them.
> 
> 
> Right. *Python* behaves differently. That's not the same thing as
> Python's calling behaving differently. If you choose objects that are
> behave the same in both languages, Python behaves *exactly* like
> call-by-reference.

This would possibly be a valid argument if Python 
*only* had such objects that behaved the same in call 
by reference languages, but it doesn't. It also has 
objects which behave differently. Just because Python 
can, in certain restricted circumstances, act like call 
by reference doesn't mean it is call by reference, 
because there are a whole swag of circumstances where 
Python _can't_ act like call by reference.



> You can show the same difference in behavior between Python and C (for
> example) without using a function call.
> 
> Here's C:
> 
> #include 
> 
> main() {
>   int i, *ref ;
>   i = 1 ;
>   ref = &i ;  /* Save identity of i */
>   i = 2 ;
>   assert(ref == &i) ;
> }
> 
> This runs just fine; i is the same object throughout the program.
> 
> On the other hand, the equivalent Python:
> 
> 
i = 1
ref = id(i) # Save the identity of i
i = 2
assert ref == id(i)
>>>
> Traceback (most recent call last):
>   File "", line 1, in ?
> AssertionError
> 
> 
> Blows up - i is no longer the same object.

Your argument seems to me like some sort of reverse 
bizarro "looks like a duck" argument: since Python 
_doesn't_ behave like call by reference, it must _be_ 
call by reference.


> Python does call by reference, which means that it passes pointers to
> objects by value. 

You are confusing the underlying implementation in C 
with Python the language. I couldn't care less whether 
the underlying implementation allows call by reference 
or not. That is simply irrelevent to the question of 
whether Python does call by reference.

Python doesn't have a pointer object type. There is an 
implementation of Python written in pure Python. That 
demonstrates that there is at least one implementation 
of Python where it is demonstrably _not_ true that 
Python "passes pointers to objects by value".

What do you think that does to your argument?



-- 
Steven.

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


Re: "0 in [True,False]" returns True

2005-12-14 Thread Steve Holden
Antoon Pardon wrote:
> Op 2005-12-13, Steve Holden schreef <[EMAIL PROTECTED]>:
[...]
>>
>>>But lets make an effort to make the code more readable. What
>>>about the following suggestion. I use a kind of EnumType with
>>>two values: NotRegistered and Registerd. And the name of the
>>>type is NotConnected. So I can then write
>>>
>>>  if type(self.callback) is NotConnected.
>>>
>>>Would that be selfdocumenting enough for you?
>>>
>>
>>It would be somewhat more self-documenting, but why not just use one 
>>name to indicate the state and another, only meaningful in certain 
>>states, to indicate the callback?
> 
> 
> Why should I do that? Checking the type of a variable is conceptually
> no different form testing set membership. So what I did, was just
> bringing two disjoint sets togther and working with a variable from
> that union. This is all in all a rather simple mathematical idea.
> And I don't see why I should put certain information into a seperate
> variable. It makes as much sense as working with numbers and using
> a seperate variable to store whether a particular number is postive,
> even or has some other characteristic. You don't seperate information
> you can easily acquire from the variable itself. So why should I
> seperate this information that is aquired just as easily?
> 

Well, as you might argue, I'm not tryng to effect a change in your 
behaviour, I'm simply trying to point out how it could be made more 
rational.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Python C/API - *arg,**kwds variable argumnents

2005-12-14 Thread [EMAIL PROTECTED]
I am writing a C extension with python 2.3.5 and need constructs
similar to python
   func(*args, **kwds)
What's a neat way to do that?
I found pyrex has a __Pyx_GetStarArgs -
is there something I'm missing from the regular C/API maybe using one
of the PyArg_Parse.. calls ?

Thanks,
M.

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


Re: ActivePython and Amara

2005-12-14 Thread Steve Holden
Jay wrote:
> Ok, ok, i over-reacted. When first reading it seemed as an attack and i
> quickly put up a defense because i dont like being attacked for no
> reason. I was actually quite obnoxious and i apoligize.
> 
> And again, thx James for pointing that out.
> Once again, i apoligize for my actions and words and i will make sure
> it doesnt happen again. Lets just start off on a clean slate. :-)
> 
Sounds like an excellent idea.

So, what was that problem you were having?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: writing a Mail Server

2005-12-14 Thread Manlio Perillo
[EMAIL PROTECTED] ha scritto:
> Hello,
> I have to implement a mail server type program for a project using
> python. I have already implemented smtp and pop3 protocol to send and
> retrieve mail at the client side. I used an existing mail server
> account to test the code. Now, I need to write the functionality of the
> mail server end. My goal is to receive emails from a few accounts, look
> at the to addresses and forward it to different mailboxes. And,
> different users should be able to pick up mail from their mailboxes.
> I am new to python and from what I have learned, I need to use
> SimpleSocketServer. I am not clear about how it will get an email type
> file and then put it in the right mailbox.
> I don't need to do too much fancy address checking, spam filtering etc.
> 
> Is there a simple way to approach this? Will really appreciate the
> input.
> Thanks
> 

Twisted.


Regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "0 in [True,False]" returns True

2005-12-14 Thread bonono

Steve Holden wrote:
> >>It would be somewhat more self-documenting, but why not just use one
> >>name to indicate the state and another, only meaningful in certain
> >>states, to indicate the callback?
> >
> >
> > Why should I do that? Checking the type of a variable is conceptually
> > no different form testing set membership. So what I did, was just
> > bringing two disjoint sets togther and working with a variable from
> > that union. This is all in all a rather simple mathematical idea.
> > And I don't see why I should put certain information into a seperate
> > variable. It makes as much sense as working with numbers and using
> > a seperate variable to store whether a particular number is postive,
> > even or has some other characteristic. You don't seperate information
> > you can easily acquire from the variable itself. So why should I
> > seperate this information that is aquired just as easily?
> >
>
> Well, as you might argue, I'm not tryng to effect a change in your
> behaviour, I'm simply trying to point out how it could be made more
> rational.
>
What would be the difference in his usage and allowing Null in a RDBMS
column ? Or return NaN instead of raising exception for numeric
functions ?

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


Re: Still Loving Python

2005-12-14 Thread Steve Holden
Mike Meyer wrote:
> Peter Decker <[EMAIL PROTECTED]> writes:
> 
A GUI builder is more pleasant to work with, at least
with a good one like Delphi or Qt designer.
>>>
>>>That is your opinion, and I'm sure it's true for you. It isn't true
>>>for me.
>>
>>Why, then, do you disparage those who like to do things differently?
>>Why label visual tools as "evil"?
> 
> 
> I didn't label them as "evil" - I agreed with someone who did that
> :-).
> 
> 
>>Why this need to have everyone do things the way you do?
> 
> 
> Whatever makes you think I have this need? I said I hated them. I'm
> pretty sure I didn't say everyone should have to use them.
> 

Before we descend to the level of name calling :-), can I interject 
another, possibly heretical, point in favour of GUI builders that you 
might *both* be able to disagree with?

It isn't often done, but I quite like the idea of giving users the GUI 
builder so that they can specify their preferred task interface, at 
least to a first approximation.

With a good tool it's relatively easy to integrate application code 
after GUI clean-up. Users sometimes find this a more intuitive way of 
specifying what they want (and God knows, most users *need* better ways 
of specifying what they want ...)

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: "0 in [True,False]" returns True

2005-12-14 Thread Antoon Pardon
Op 2005-12-14, Steve Holden schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:

>>>It would be somewhat more self-documenting, but why not just use one 
>>>name to indicate the state and another, only meaningful in certain 
>>>states, to indicate the callback?
>> 
>> 
>> Why should I do that? Checking the type of a variable is conceptually
>> no different form testing set membership. So what I did, was just
>> bringing two disjoint sets togther and working with a variable from
>> that union. This is all in all a rather simple mathematical idea.
>> And I don't see why I should put certain information into a seperate
>> variable. It makes as much sense as working with numbers and using
>> a seperate variable to store whether a particular number is postive,
>> even or has some other characteristic. You don't seperate information
>> you can easily acquire from the variable itself. So why should I
>> seperate this information that is aquired just as easily?
>> 
>
> Well, as you might argue, I'm not tryng to effect a change in your 
> behaviour, I'm simply trying to point out how it could be made more 
> rational.

I guess we will just have to agree to disagree on what is more rational
in this case. Maybe it is just a case of what idiom one is used to.

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


Re: OO in Python? ^^

2005-12-14 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> Magnus Lycka wrote:
> 
>>The static typing means that you either have to make several
>>implementations of many algorithms, or you need to work with
>>those convoluted templates that were added to the language as
>>an afterthought.
> 
> I don't see this in Haskell.

No, I was refering to C++ when I talked about templates.

I don't really know Haskell, so I can't really compare it
to Python. A smarter compiler can certainly infer types from
the code and assemble several implementations of an
algorithm, but unless I'm confused, this makes it difficult
to do the kind of dynamic linking / late binding that we do in
Python. How do you compile a dynamic library without locking
library users to specific types?

I don't doubt that it's possible to make a statically typed
language much less assembly like than C++...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-14 Thread Laszlo Zsolt Nagy

>Try Pyro  http://pyro.sourceforge.net
>before rolling your own Python-specific protocol.
>  
>
You are right. I wanted to use pyro before, because it is well tested 
and it has nice features.
Unfortunately, it is not good for me. :-(

I already have my own classes. My objects are in object ownership trees, 
and they are referencing to each other (weakly and strongly). These 
classes have their own streaming methods, and they can be pickled 
safely. This is something that pyro cannot handle. It cannot handle 
these ownership object trees with weak references. Pyro can distribute 
distinct objects only, and it uses an 'object naming scheme'. This is 
not what I want. My objects do not have a name, and I do not want to 
create 'technical names' just to force the Pyro style access. (Another 
problem is that I do not want to rewrite my classes and inherit them 
from the Pyro base object class.)

Thanks for the comment. I'm going to check the Pyro documentation again. 
I might find something useful.

  Les

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


Re: Still Loving Python

2005-12-14 Thread Steve Holden
Alex Martelli wrote:
> Jérôme Laheurte <[EMAIL PROTECTED]> wrote:
>...
> 
>>Sorry for the harsh tone, I just think GUI builders are *evil*. Except
>>maybe for QT Designer, which has a nice model where you implement
>>callbacks by subclassing the generated classes. At least you don't have to
>>look at the generated code.
> 
> 
> Try Interface Builder on a Mac: it builds interfaces as _data_ files,
> not "generated code".  You can then use the same UI from Objective C,
> Java, Python (w/PyObjC), AppleScript... interface-painters which
> generate code are a really bad idea.  (I'm sure Apple's IB is not the
> only interface-painter which encodes the UI as a datafile, easily
> interpreted at startup by a suitable library for whatever language
> you're using to flesh it out -- it's such an obviously RIGHT idea!).
> 
You're right. For example wxDesigner will produce XML, as well as 
writing wxWidgets calls directly in Python, Perl or C++.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: OO in Python? ^^

2005-12-14 Thread bonono

Magnus Lycka wrote:
> I don't really know Haskell, so I can't really compare it
> to Python. A smarter compiler can certainly infer types from
> the code and assemble several implementations of an
> algorithm, but unless I'm confused, this makes it difficult
> to do the kind of dynamic linking / late binding that we do in
> Python. How do you compile a dynamic library without locking
> library users to specific types?
I don't know. I am learning Haskell(and Python too), long way to go
before I would get into the the usage you mentioned, if ever, be it
Haskell or Python.

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


Re: Developing a network protocol with Python

2005-12-14 Thread Paul Rubin
Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
> I already have my own classes. My objects are in object ownership
> trees, and they are referencing to each other (weakly and
> strongly). These classes have their own streaming methods, and they
> can be pickled safely.

Standard warning: if you're accepting requests from potentially
hostile sources, don't use pickle.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do (not) I distribute my Python progz?

2005-12-14 Thread Ben Sizer
Tolga wrote:
> Let's suppose that I have written a Python program and, of course, want
> to show it to the world ;-)
>
> So, do I have to distrubute my source code? Or is there a way to hide
> my code?

Suggested solutions to this in the past have including using Py2exe (or
something like it) to create single-file distributables (viewable with
a zip program, however), writing custom import hooks to decode
encrypted modules, and storing valuable data online. It might even be
possible to do some sort of RMI and store useful parts of your code
online, although this requires a network connection and a
latency-insensitive application, which are by no means universal.

You could also consider moving your sensitive code to a compiled C
module, perhaps using something like Pyrex to make it fairly easy.

Obviously you will want to decide whether it's worth the effort to do
all this, because most of the time it won't be.

-- 
Ben Sizer

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


Re: newbie-one more example of difficulty in van Rossum's tutorial

2005-12-14 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Thanks Brian, now I get it. BTW there is no fuzzuness in your
> explanaition it is crystal clear.
> 
You might also want to note that name-mangling and the reason for it are 
pretty advanced topics for an introductory tutorial. Having got thus 
far, further learning might better be gained by using Python on actual 
projects.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: IsString

2005-12-14 Thread Ben Sizer
Steven D'Aprano wrote:
> def modify_in_place(obj):
> """Modify an arbitrary object in place."""
> obj = None
>
> x = [1, 2, 3] # mutable object
> modify_in_place(x)
> assert x is None
>
>
> Doesn't work either.

To be fair, this isn't because the function is not pass by reference,
but because the assignment operator reassigns the reference rather than
altering the referent, and thus modify_in_place doesn't actually
contain any modifying operations. With a good understanding of what
Python's assignment operator actually does, (I believe) you can view
Python as pass-by-reference without any semantic problems.

-- 
Ben Sizer

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


Re: writing a Mail Server

2005-12-14 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hello,
> I have to implement a mail server type program for a project using
> python. I have already implemented smtp and pop3 protocol to send and
> retrieve mail at the client side. I used an existing mail server
> account to test the code. Now, I need to write the functionality of the
> mail server end. My goal is to receive emails from a few accounts, look
> at the to addresses and forward it to different mailboxes. And,
> different users should be able to pick up mail from their mailboxes.
> I am new to python and from what I have learned, I need to use
> SimpleSocketServer. I am not clear about how it will get an email type
> file and then put it in the right mailbox.
> I don't need to do too much fancy address checking, spam filtering etc.
> 
> Is there a simple way to approach this? Will really appreciate the
> input.
> Thanks
> 
Look at the SpamBayes project, which IIRC has proxies for both SMTP and 
POP3, which should be easy to adapt to your purposes - you don't really 
need a full server implementation.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Puzzling output when executing .pyc file directly

2005-12-14 Thread Steve Holden
Steven D'Aprano wrote:
> I created a simple test file called "tester.py":
> 
> 
> def dostuff(obj):
>  print "Doing stuff with %s now..." % obj
>  return len(str(obj))
> x = "things"
> if __name__ == "__main__":
>  print dostuff(x)
> 
> 
> imported it into Python, then exited the current Python 
> session. Then I compared the results of calling the .py 
> file with those from calling the .pyc file:
> 
> 
> bash-2.03$ python tester.py
> Doing stuff with things now...
> 6
> 
> bash-2.03$ python tester.pyc
> Doing stuff with things now...
> 6
> run_pyc_file: nested_scopes: 0
> 
> 
> Can anyone tell me what the run_pyc_file line is doing 
> in the output of the .pyc file? Is that normal 
> behaviour when calling a .pyc file?
> 
No and no :-)

> For my sins, I am using Python 2.1.1 on sunos5.
> 
Don't know whether that was a 2.1.1-specific problem, but that's 
certainly not how 2.4.1 behaves. But then, you knew that already, didn't 
you?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


const objects (was Re: Death to tuples!)

2005-12-14 Thread Gabriel Zachmann

I was wondering why python doesn't contain a way to make things "const"?

If it were possible to "declare" variables at the time they are bound to 
objects that they should not allow modification of the object, then we would 
have a concept _orthogonal_ to data types themselves and, as a by-product, a 
way to declare tuples as constant lists.

So this could look like this:

 const l = [1, 2, 3]

 def foo( const l ): ...

and also

 const d = { "1" : 1, "2" : 2, ... }

etc.

It seems to me that implementing that feature would be fairly easy.
All that would be needed is a flag with each variable.

Just my tupence,
Gabriel.


-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-14 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> Magnus Lycka wrote:
> 
>>I don't really know Haskell, so I can't really compare it
>>to Python. A smarter compiler can certainly infer types from
>>the code and assemble several implementations of an
>>algorithm, but unless I'm confused, this makes it difficult
>>to do the kind of dynamic linking / late binding that we do in
>>Python. How do you compile a dynamic library without locking
>>library users to specific types?
> 
> I don't know. I am learning Haskell(and Python too), long way to go
> before I would get into the the usage you mentioned, if ever, be it
> Haskell or Python.

Huh? I must have expressed my thoughts badly. This is trivial to
use in Python. You could for instance write a module like this:

### my_module.py ###
import copy

def sum(*args):
 result = copy.copy(args[0])
 for arg in args[1:]:
 result += arg
 return result

### end my_module.py ###

Then you can do:

 >>> from my_module import sum
 >>> sum(1,2,3)
6
 >>> sum('a','b','c')
'abc'
 >>> sum([1,2,3],[4,4,4])
[1, 2, 3, 4, 4, 4]
 >>>

Assume that you didn't use Python, but rather something with
static typing. How could you make a module such as my_module.py,
which is capable of working with any type that supports some
standard copy functionality and the +-operator?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can i change the default python?

2005-12-14 Thread [EMAIL PROTECTED]
Thanks for the hint Xavier.
I made the default interpreter ipython.

# rm /usr/bin/python
# ln -s /usr/bin/python2.4-ipython /usr/bin/python

ipython is better i think ..

and another question;
When i type "sudo aptitude install python-jabber" for example, it
brings the python2.3-jabber package. But i want it to bring me the 2.4
package. Of course i am able to use "sudo aptitude install
python2.4-jabber" but i want to know if this situation is normal? Can i
tell aptitude, bring me python2.4-xx when i type python-xx?

And running two version of python should be a problem?

koray

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


Re: List text files showing LFs and expanded tabs (was: Colorize expanded tabs)

2005-12-14 Thread qwweeeit
Hi Gene,
thank you for your reply, also if my post was meant to be only
an exercise to apply color to lfs and expanded tabs in listing
files and not to apply it to an editor.
However your comment has directed me to consider more
deeply other editors (I use kwrite).
I am inclined to change to vim but I haven't found the
vim module for python.
By the way I'm not sure that vim can display lfs and expanded
tabs in color!
Bye.

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


Re: OO in Python? ^^

2005-12-14 Thread bonono

Magnus Lycka wrote:
> [EMAIL PROTECTED] wrote:
> > Magnus Lycka wrote:
> >
> >>I don't really know Haskell, so I can't really compare it
> >>to Python. A smarter compiler can certainly infer types from
> >>the code and assemble several implementations of an
> >>algorithm, but unless I'm confused, this makes it difficult
> >>to do the kind of dynamic linking / late binding that we do in
> >>Python. How do you compile a dynamic library without locking
> >>library users to specific types?
> >
> > I don't know. I am learning Haskell(and Python too), long way to go
> > before I would get into the the usage you mentioned, if ever, be it
> > Haskell or Python.
>
> Huh? I must have expressed my thoughts badly. This is trivial to
> use in Python. You could for instance write a module like this:
>
> ### my_module.py ###
> import copy
>
> def sum(*args):
>  result = copy.copy(args[0])
>  for arg in args[1:]:
>  result += arg
>  return result
>
> ### end my_module.py ###
>
> Then you can do:
>
>  >>> from my_module import sum
>  >>> sum(1,2,3)
> 6
>  >>> sum('a','b','c')
> 'abc'
>  >>> sum([1,2,3],[4,4,4])
> [1, 2, 3, 4, 4, 4]
>  >>>
>
> Assume that you didn't use Python, but rather something with
> static typing. How could you make a module such as my_module.py,
> which is capable of working with any type that supports some
> standard copy functionality and the +-operator?
Ah, I thought you were talking about DLL or some external library
stuff. In Haskell, it use a concept of type class. Conceptually similar
to the "duck typing" thing in python/ruby. You just delcare the data
type then add an implementation as an instance of a type class that
knows about +/- or copy. The inference engine then would do its work.

I would assume that even in python, there are different implement of
+/- and copy for different object types.

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


definition of 'polymorphism' and python

2005-12-14 Thread Gabriel Zachmann
I understand the Wikipedia article on Polymorphism
( http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 )
that it doesn't make sense to talk about polymorphism in a fully dynamically 
typed language -- does the Python community agree?

cheers,
gabriel.

-- 
/---\
| Any intelligent fool can make things bigger, more complex,|
| or more violent. It takes a touch of genius - and a lot of courage -  |
| to move in the opposite direction. (Einstein) |
\---/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do (not) I distribute my Python progz?

2005-12-14 Thread Juergen Kareta
Hi Steven,

> For many purposes, you can just distribute the .pyc compiled byte-code. 
> That will discourage the casual user from reading the source code, but 
> of course a serious programmer will be able to disassemble the .pyc code 
> very easily.

very easily ?

I tried it with my own code a year or two ago, and had some problems 
(sorry don't remember all steps, but I think there was a tool called 
disassemble ?). As I don't use a repository at the moment, I would need
it sometimes to disassemble older versions of my exe'd code. Could you 
please give some hints, how I can get on ?

Thanks in advance
Jürgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-14 Thread bonono

Magnus Lycka wrote:
> Assume that you didn't use Python, but rather something with
> static typing. How could you make a module such as my_module.py,
> which is capable of working with any type that supports some
> standard copy functionality and the +-operator?

The following is a very short Haskell function I defined which I hope
can give you some idea.

What it does is just take a generic list of things(I want to use it on
string) and break it up into a tuple using any object in token as
seperator (sort of C's strtok).

breakKeyword token xs =
  case break (flip elem token) xs of
(_,[]) -> (xs,[])
(ys,z:zs) -> (ys, zs)

This is the function declaration derived by Haskell(I haven't specify
anything above about types)

*MyList> :type breakKeyword
breakKeyword :: (Eq a) => [a] -> [a] -> ([a], [a])

What it means is that breakKeyword can take any list of object type "a"
so long it belongs to the class Eq. It can be char, number or whatever
so long it is an instance of Eq.

All that is needed for my custom data type(whatever it is) is that it
must implment the compare function that "elem" would use to compare if
a given object is in the list of token.

*MyList> :type elem
elem :: (Eq a) => a -> [a] -> Bool

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


Re: definition of 'polymorphism' and python

2005-12-14 Thread Kay Schluehr
Gabriel Zachmann wrote:
> I understand the Wikipedia article on Polymorphism
> ( http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 )
> that it doesn't make sense to talk about polymorphism in a fully dynamically
> typed language -- does the Python community agree?

Maybe you should articulate your objection instead of letting others
guess what you might think?

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


Re: Still Loving Python

2005-12-14 Thread Bengt Richter
On Tue, 13 Dec 2005 20:33:36 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

>Peter Maas <[EMAIL PROTECTED]> writes:
>> Mike Meyer schrieb:
>>> I agree. I've tried a number of different gui builders. I find it much
>>> faster to type something like:
>>> ui.add_button("New", self.new)
>>> ui.add_button("Open", self.open)
>>> ui.add_button("Save", self.save)
>>> ui.add_button("Save As", self.save_as)
>>> Than have to drag four menu buttons from a pallette, then open the
>>> properties of each one to edit the text of the button and the callback
>>> entry (or whatever dance they need so you can enter the required
>>> text).
>> If you design a moderately complex UI a designer will be faster. It's
>> not the speed of typing vs. dragging that matters. You see the result
>> instantly and don't have to start your program, look, type code, start
>> again and so on.
>
>But you only need to do that if you're wanting near-absolute control
>over what's displayed. Once you provide reasonable accessability and
>configuration features - letting the user specifiy fonts, which
>buttons show up, which toolbars you're going to have, what's in the
>menus, etc. In this case, "look" is trivial, and it seldom requires a
>second pass.
>
>> A GUI builder is more pleasant to work with, at least
>> with a good one like Delphi or Qt designer.
>
>That is your opinion, and I'm sure it's true for you. It isn't true
>for me.
De gustibus non disputandum, or whatever ;-)

>
>> It's not a good idea to do everything in code. I find it tiresome to
>> create menus and toolbars by writing code.
>
>Maybe you're doing something wrong? Or maybe it is tiresome for you,
>and you should be using something else.
>
>> Creating visual resources visually is the direct way, creating them in
>> code is a detour. Code is too lengthy and too versatile for such a
>> job.
>
>Your application creates code in the end, so that's the direct
>route. A visual representation of a modern app is a relatively static
>version of the real interface, and thus at best an approximation.
>
>Worse yet, there's a good chance your visual tool stores the
>information needed to recreate either the visual version or the code
>in either a binary format, or a proprietary one, or both. In the
>former case, standard code analysis tools are nearly useless. In the
>latter case, they own your code. While that price might be worth it if
>you place enough value onj being able to manipulate images instead of
>code, either is enough to make me avoid a tool.
>
If that is your concept of Delphi, it is wrong. A text view of what you have
created visually is available. I put four buttons on a blank form with
captions per your example. The result is

object Form1: TForm1
  Left = 200
  Top = 108
  Width = 696
  Height = 480
  Caption = 'Form1'
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  PixelsPerInch = 96
  TextHeight = 13
  object Button1: TButton
Left = 64
Top = 48
Width = 75
Height = 25
Caption = 'New'
TabOrder = 0
  end
  object Button2: TButton
Left = 152
Top = 48
Width = 75
Height = 25
Caption = 'Open'
TabOrder = 1
  end
  object Button3: TButton
Left = 240
Top = 48
Width = 75
Height = 25
Caption = 'Save'
TabOrder = 2
  end
  object Button4: TButton
Left = 328
Top = 48
Width = 75
Height = 25
Caption = 'Save As'
TabOrder = 3
  end
end

You see the above sort of text if you are looking at a form you are working and 
you press Alt-F12.
If you do not violate the format, you can edit it as text right in the window 
you are looking at
and round-trip it back to a visual view with another Alt-F12, and you will see 
the adjusted visual view.
Other aspects of objects show up too if you set non-default conditions one way 
or the other. E.g.,
adding an individual mouse-over hint is a matter of typing the text in a slot 
in the object inspector
which is automatically showing the properties of the button etc that you have 
visually selected
on your form/dialog. E.g., above button with hint added.

  object Button4: TButton
Left = 328
Top = 48
Width = 75
Height = 25
Hint = 'Opens a file dialog for saving'
Caption = 'Save As'
ParentShowHint = False
ShowHint = True
TabOrder = 3
  end

A single click compiles, links and runs the resulting independent windows .exe 
in a fraction of a second
for the above, and I can see the hint, kill the .exe, and go on where I was.

Of course, as you see, I could select the text and put it in the clipboard, and 
post it here.

BTW, Delphi also compiles and links in a blink (literally for small programs), 
and generates
a small .exe. Delphi also lets you code without GUI and gives you a command 
line compiler for
its object pascal, and you can write very small executables that way if you 
like, even using x86 builtin assembler.
And it compiles and li

Re: Developing a network protocol with Python

2005-12-14 Thread Laszlo Zsolt Nagy
Paul Rubin wrote:

>Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
>  
>
>>I already have my own classes. My objects are in object ownership
>>trees, and they are referencing to each other (weakly and
>>strongly). These classes have their own streaming methods, and they
>>can be pickled safely.
>>
>>
>
>Standard warning: if you're accepting requests from potentially
>hostile sources, don't use pickle.
>  
>
Yes, I know.  Not talking about TLS/SSL - there can be hostile persons, 
knowing a valid password and using a modified client program.

But how can I transfer pure python objects otherwise? Pyro also uses 
Pickle and it also transfers bytecode.
Well, Pyro has an option to use XML messaging, but that is very 
restricted, you cannot publish arbitrary python objects with XML. :-(

I read somewhere that Pickle had a security problem before Python 2.2, 
but after 2.2 it has been solved.
BTW how CORBA or COM does this? They can do object marshaling safely. 
Can we do the same with Python?
Isn't it enough to implement find_global of a cPickler ?

   Les


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


Re: const objects (was Re: Death to tuples!)

2005-12-14 Thread Steven D'Aprano
On Wed, 14 Dec 2005 10:57:05 +0100, Gabriel Zachmann wrote:

> I was wondering why python doesn't contain a way to make things "const"?
> 
> If it were possible to "declare" variables at the time they are bound to 
> objects that they should not allow modification of the object, then we would 
> have a concept _orthogonal_ to data types themselves and, as a by-product, a 
> way to declare tuples as constant lists.

In an earlier thread, somebody took me to task for saying that Python
doesn't have variables, but names and objects instead.

This is another example of the mental confusion that occurs when you think
of Python having variables. Some languages have variables. Some do not. Do
not apply the rules of behaviour of C (which has variables) to Python
(which does not).

Python already has objects which do not allow modification of the object.
They are called tuples, strings, ints, floats, and other immutables.



> So this could look like this:
> 
>  const l = [1, 2, 3]

(As an aside, it is poor practice to use "l" for a name, because it is too
easy to mistake for 1 in many fonts. I always use capital L for quick
throw-away lists, like using x or n for numbers or s for a string.)

Let's do some tests with the constant list, which I will call L:


py> L.count(2)
1
py> L.append(4)
Traceback (most recent call last):
  File "", line 1, in ?
ConstantError: can't modify constant object

(Obviously I've faked that last error message.) So far so good: we can
call list methods on L, but we can't modify it.

But now look what happens when we rebind the name L:

py> L = 2
py> print L
2

Rebinding the name L doesn't do anything to the object that L pointed to.
That "constant list" will still be floating in memory somewhere. If L was
the only reference to it, then it will be garbage collected and the memory
it uses reclaimed.


Now, let's look at another problem with the idea of constants for Python:

py> L = [1, 2, 3]  # just an ordinary modifiable list
py> const D = {1: "hello world", 2: L}  # constant dict

Try to modify the dictionary:

py> D[0] = "parrot"
Traceback (most recent call last):
  File "", line 1, in ?
ConstantError: can't modify constant object

So far so good.

py> L.append(4)

What should happen now? Should Python allow the modification of ordinary
list L? If it does, then this lets you modify constants through the back
door: we've changed one of the items of a supposedly unchangeable dict.

But if we *don't* allow the change to take place, we've locked up an
ordinary, modifiable list simply by putting it inside a constant. This
will be a great way to cause horrible side-effects: you have some code
which accesses an ordinary list, and expects to be able to modify it. Some
other piece of code, could be in another module, puts that list inside a
constant, and *bam* your code will break when you try to modify your list.

Let me ask you this: what problem are you trying to solve by adding
constants to Python? 



> It seems to me that implementing that feature would be fairly easy.
> All that would be needed is a flag with each variable.

Surely not. Just adding a flag to objects would not actually implement the
change in behaviour you want. You need to code changes to the parser to
recognise the new keyword, and you also need code to actually make objects
unmodifiable.



-- 
Steven.

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


Re: ActivePython and Amara

2005-12-14 Thread James
If you are having problems installing Amara, ElementTree is another
option

http://effbot.org/downloads/elementtree-1.2.6-20050316.win32.exe

from elementtree import ElementTree as ET
from urllib import urlopen

rss = ET.parse(urlopen('index.xml'))
title = rss.find('//channel/title').text
articles = [item.find('title').text for item in
rss.findall('//channel/item')]

This is quick and dirty. Read this
(http://diveintopython.org/http_web_services/review.html) before you
make the real thing.

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


Re: ActivePython and Amara

2005-12-14 Thread James
OK! The story so far ...
You wanted to parse an RSS feed and wanted a simple library. You tried
Amara. The binary installer had a problem. Not sure what was the issue
with installing the source via distutils.

Since you have way too many options to do this, it is probably better
to switch to another module for now.

ElementTree is another good module
http://effbot.org/downloads/elementtree-1.2.6-20050316.win32.exe

Following is a snippet of code that probably does what you want.
You should be able to extend it from there.
You might want to read this before you finish your aggregator.
http://diveintopython.org/http_web_services/review.html
Basically some netiquette when you repeatedly poll someone's server.
---

from elementtree import ElementTree as ET
from urllib import urlopen

rss = ET.parse(urlopen('http://www.digg.com/rss/index.xml'))
title = rss.find('//channel/title').text
articles = [item.find('title').text for item in
rss.findall('//channel/item')]

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


Re: PyQt not working well on Mac OS X

2005-12-14 Thread Dan Sommers
On 13 Dec 2005 19:03:47 -0800,
"Michael McGarry" <[EMAIL PROTECTED]> wrote:

> Hi,
> I am running a Python/Qt app I developed that runs flawlessly in Linux
> on my Mac. It is unfortunate not running properly on the Mac OS X. The
> window will not come into focus and is grayed out.

> Does anyone have any ideas?

You may have to "bundle" your app -- i.e., create the whole
application.app structure -- rather that just run the python program
from within a shell.  Cocoa looks for a bunch of resources in standard
places before it will let your app interact with the user.

Regards,
Dan

-- 
Dan Sommers

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


Re: Amara (XML) problem on Solaris

2005-12-14 Thread Doru-Catalin Togea
On Wed, 14 Dec 2005, Alan Franzoni wrote:

> Also, are you sure the code is correct? I've taken a peek at the Amara's
> website, and the create_document() function seems to lie within the
> binderytools module. I think the line should look like:
>
> depending on the way you imported the module, but your previous code, if
> really working on Windows, makes me think you did something like:
>
> import amara.binderytools as amara
>
> or something like that?
> Please post some more code, if you can.

This is a simple test:

import amara

doc = amara.create_document()
doc.xml_append(doc.xml_create_element(u"units"))

print "OK"

On Windows XP Pro it runs like this:

C:\owera\test\xaps2-test>python amara-test1.py
OK

C:\owera\test\xaps2-test>

On Solaris it runs like this:

bash-2.03$ python amara-test1.py
Traceback (most recent call last):
   File "amara-test1.py", line 3, in ?
 doc = amara.create_document()
AttributeError: 'module' object has no attribute 'create_document'
bash-2.03$

Catalin

-- 

  == 
 << We are what we repeatedly do.  >>
 <<  Excellence, therefore, is not an act  >>
 << but a habit.   >>
  == 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do (not) I distribute my Python progz?

2005-12-14 Thread Steven D'Aprano
On Wed, 14 Dec 2005 11:41:25 +0100, Juergen Kareta wrote:

> Hi Steven,
> 
>> For many purposes, you can just distribute the .pyc compiled byte-code. 
>> That will discourage the casual user from reading the source code, but 
>> of course a serious programmer will be able to disassemble the .pyc code 
>> very easily.
> 
> very easily ?
> 
> I tried it with my own code a year or two ago, and had some problems 
> (sorry don't remember all steps, but I think there was a tool called 
> disassemble ?). As I don't use a repository at the moment, I would need
> it sometimes to disassemble older versions of my exe'd code. Could you 
> please give some hints, how I can get on ?

What makes you think I'm a serious programmer? *wink*

Try this:


py> import dis  # the Python disassembler
py> 
py> def f(x):
... print x
... return x+1
...
py> dis.dis(f)
  2   0 LOAD_FAST0 (x)
  3 PRINT_ITEM
  4 PRINT_NEWLINE
 
  3   5 LOAD_FAST0 (x)
  8 LOAD_CONST   1 (1)
 11 BINARY_ADD
 12 RETURN_VALUE
 13 LOAD_CONST   0 (None)
 16 RETURN_VALUE


Python's byte-code is not exactly as easy to understand as native Python,
but it is still understandable. And I wonder, is there a program which
will try to generate Python code from the output of the disassembler?


-- 
Steven

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


Re: Puzzling output when executing .pyc file directly

2005-12-14 Thread Peter Otten
Steven D'Aprano wrote:

> bash-2.03$ python tester.pyc
> Doing stuff with things now...
> 6
> run_pyc_file: nested_scopes: 0
> 
> 
> Can anyone tell me what the run_pyc_file line is doing
> in the output of the .pyc file? Is that normal
> behaviour when calling a .pyc file?
> 
> For my sins, I am using Python 2.1.1 on sunos5.
 
"that's just a random debugging printf left in by mistake"

http://mail.python.org/pipermail/python-list/2002-April/096463.html

Peter

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


Re: const objects (was Re: Death to tuples!)

2005-12-14 Thread Steve Holden
Gabriel Zachmann wrote:
[...]
> 
> It seems to me that implementing that feature would be fairly easy.
> All that would be needed is a flag with each variable.
> 
It seems to me like it should be quite easy to add a sixth forward gear 
to my car, but I'm quite sure an auto engineer would quickly be able to 
point out several reasons why it wasn't, as well as questioning my 
"need" for a sixth gear in the first place.

Perhaps you could explain why the absence of const objects is a problem?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


openings on java with japanese language

2005-12-14 Thread suresh . reddy
send your profile to [EMAIL PROTECTED]

Job Code: JJ1

Job Description:

 Skills: Experience in Java, J2EE, Struts and servlets.

 This is for onsite (Japan) and should be proficient at
Japanese Knowledge (Level 3/4).

Number of positions : 6


Experience:

3-5 years on Real time experience on Struts and servlets.

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


Re: definition of 'polymorphism' and python

2005-12-14 Thread Steven D'Aprano
On Wed, 14 Dec 2005 02:47:40 -0800, Kay Schluehr wrote:

> Gabriel Zachmann wrote:
>> I understand the Wikipedia article on Polymorphism
>> ( http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 )
>> that it doesn't make sense to talk about polymorphism in a fully dynamically
>> typed language -- does the Python community agree?
> 
> Maybe you should articulate your objection instead of letting others
> guess what you might think?

In fairness, it is possible that Gabriel doesn't have any objects, because
he doesn't have an opinion yet.

Speaking for myself, I found that the first half of the article so
jargon-ridden that my brain rebooted seven times trying to read it, but
the section "Example" was so clear and simple that I now feel myself to be
an expert on polymorphism and am confident enough to give my opinion with
no fear of contradiction by any right-thinking Python programmer.

[deadpan]


But seriously... Python objects are strongly typed. Python will allow all
six of the examples of addition from the Example section. Since this is
supposed to be an example of polymorphism, and Python will do that exact
thing, then absolutely I would describe Python as polymorphic.

Well, that is, I would describe Python as polymorphic if I thought there
was any value to the term *wink*



-- 
Steven.

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


Re: ElementTree - Why not part of the core?

2005-12-14 Thread Gregory Petrosyan
[EMAIL PROTECTED]:~$ python
Python 2.5a0 (#1, Dec 14 2005, 14:11:55)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import xml.etree.ElementTree as ET
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.5/xml.py", line 20, in 
import xmlcore
ImportError: No module named xmlcore
>>>

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


Re: ElementTree - Why not part of the core?

2005-12-14 Thread Gregory Petrosyan
This I've got after

make install

and

[EMAIL PROTECTED]:~$ python

When launching ./python from ./trunk, everything is OK. Is it a problem
with me or with installation?

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


Re: definition of 'polymorphism' and python

2005-12-14 Thread Ben Sizer
Gabriel Zachmann wrote:
> I understand the Wikipedia article on Polymorphism
> ( http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29 )
> that it doesn't make sense to talk about polymorphism in a fully dynamically
> typed language -- does the Python community agree?

"In computer science, polymorphism means allowing a single definition
to be used with different types of data (specifically, different
classes of objects)."

>>> len("abcd")
4
>>> len([1,2,3,4,5,6])
6

Looks pretty polymorphic to me. In fact, Python's polymorphism support
is so good that it makes inheritance much less important than it is in
other languages.

-- 
Ben Sizer

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


Re: OO in Python? ^^

2005-12-14 Thread Antoon Pardon
Op 2005-12-14, Magnus Lycka schreef <[EMAIL PROTECTED]>:
> [EMAIL PROTECTED] wrote:
>> Magnus Lycka wrote:
>> 
>>>I don't really know Haskell, so I can't really compare it
>>>to Python. A smarter compiler can certainly infer types from
>>>the code and assemble several implementations of an
>>>algorithm, but unless I'm confused, this makes it difficult
>>>to do the kind of dynamic linking / late binding that we do in
>>>Python. How do you compile a dynamic library without locking
>>>library users to specific types?
>> 
>> I don't know. I am learning Haskell(and Python too), long way to go
>> before I would get into the the usage you mentioned, if ever, be it
>> Haskell or Python.
>
> Huh? I must have expressed my thoughts badly. This is trivial to
> use in Python. You could for instance write a module like this:
>
> ### my_module.py ###
> import copy
>
> def sum(*args):
>  result = copy.copy(args[0])
>  for arg in args[1:]:
>  result += arg
>  return result
>
> ### end my_module.py ###
>
> Then you can do:
>
> >>> from my_module import sum
> >>> sum(1,2,3)
> 6
> >>> sum('a','b','c')
> 'abc'
> >>> sum([1,2,3],[4,4,4])
> [1, 2, 3, 4, 4, 4]
> >>>
>
> Assume that you didn't use Python, but rather something with
> static typing.

That depends on what you would call static typing.

Suppose we would add type declarations in python.
So we could do things like

  int: a
  object: b

Some people seem to think that this would introduce static
typing, but the only effect those staments need to have
is that each time a variable is rebound an assert statement
would implicitly be executed, checking whether the variable is
still an instance of the declared type.

(Assuming for simplicity that all classes are subclasses
of object so that all objects are instances of object.)

> How could you make a module such as my_module.py,

In the above scenario in just the same way as in python.

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


First practical Python code, comments appreciated

2005-12-14 Thread planetthoughtful
Hi All,

I've written my first piece of practical Python code (included below),
and would appreciate some comments. My situation was that I had a
directory with a number of subdirectories that contained one or more
zip files in each. Many of the zipfiles had the same filename (which is
why they had previously been stored in separate directories). I wanted
to bring all of the zip files (several hundrd in total) down to the
common parent directory and obviously rename them in the process by
appending a unique string to each filename.

The code below did the job admirably, but I don't imagine it is
anywhere near as efficiently written as it could and should be. Note:
I'm aware there was no need, for example, to wrap the "os.walk(path)"
statement in a def -- in a couple of places I added extra steps just to
help familiarize myself with Python syntax.

I'd very much like to see how experienced Python coders would have
achieved the same task, if any of you can spare a couple of minutes to
share some knowledge with me.

Many thanks and much warmth,

planetthoughtful

import os
fcount = 0
path = 'X:\zipfiles'
def listFiles(path):
mylist = os.walk(path)
return mylist

filelist = listFiles(path)
for s in filelist:
if len(s[2]) > 0:
for f in s[2]:
pad = str(fcount)
if len(pad) == 1:
pad = "00" + pad
elif len(pad) == 2:
pad = "0" + pad

(fname, fext) = os.path.splitext(f)
oldname = f
newname = fname + "_" + pad + fext
os.rename(s[0] + "\\" + oldname, path + "\\" + newname)
fcount = fcount + 1

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


Re: How do i read line from an input file, without the /n

2005-12-14 Thread doritrieur
thanks all for your replies! it did helped me!
by the way, i am really new to phyton and to programming, can anyone
refer me to an online source that supplies the relevant data for syntax
ect?

thanks, Dorit.

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


Re: How can I load python script into Html ??

2005-12-14 Thread PatPoul
Sorry I was not clear, my setup is functionnal with Pywin32.
Python 2.4 + pywin32

and actually, I can do this kind of script on client side :



alert('test')



but I want to include external python script with the HTML tag 

Re: First practical Python code, comments appreciated

2005-12-14 Thread Steve Holden
planetthoughtful wrote:
> Hi All,
> 
> I've written my first piece of practical Python code (included below),
> and would appreciate some comments. My situation was that I had a
> directory with a number of subdirectories that contained one or more
> zip files in each. Many of the zipfiles had the same filename (which is
> why they had previously been stored in separate directories). I wanted
> to bring all of the zip files (several hundrd in total) down to the
> common parent directory and obviously rename them in the process by
> appending a unique string to each filename.
> 
> The code below did the job admirably, but I don't imagine it is
> anywhere near as efficiently written as it could and should be. Note:
> I'm aware there was no need, for example, to wrap the "os.walk(path)"
> statement in a def -- in a couple of places I added extra steps just to
> help familiarize myself with Python syntax.
> 
> I'd very much like to see how experienced Python coders would have
> achieved the same task, if any of you can spare a couple of minutes to
> share some knowledge with me.
> 
> Many thanks and much warmth,
> 
> planetthoughtful

Brave of you. Please note I haven't actually tested the exact format of 
these suggestions, so I made have made stupid typos or syntax errors.
> 
> import os
> fcount = 0
> path = 'X:\zipfiles'
> def listFiles(path):
> mylist = os.walk(path)
> return mylist
> 
> filelist = listFiles(path)
> for s in filelist:
> if len(s[2]) > 0:

You don't really need this "if" - with an empty s the "for" loop on the 
next line will simply execute its body zero times, giving the effect you 
appear to want without the extra level of logic.

> for f in s[2]:
> pad = str(fcount)
> if len(pad) == 1:
> pad = "00" + pad
> elif len(pad) == 2:
> pad = "0" + pad
> 
Here you could take advantage of the string formatting "%" operator and 
instead of the "if" statement just say

   pad = "%03d" % fcount

  >>> ["%03d" % x for x in (1, 3, 10, 30, 100, 300)]
['001', '003', '010', '030', '100', '300']

> (fname, fext) = os.path.splitext(f)
> oldname = f

There isn't really any advantage to this assignment, though I admit it 
does show what you are doing a little better. So why not just use

for oldname in s[2]:

to control the loop, and then replace the two statements above with

   (fname, fext) = os.path.splitext(oldname)

Note that assignments of one plain name to another are always fast 
operations in Pythin, though, so this isn't criminal behaviour - it just 
clutters your logic a little having essentially two names for the same 
thing.

> newname = fname + "_" + pad + fext
> os.rename(s[0] + "\\" + oldname, path + "\\" + newname)

That form is non-portable. You might argue "I'm never going to run this 
program on anything other than Windows", and indeed for throwaway 
programs it's often easier to write something non-portable. It's 
surprising, though, how often you end up *not* throwing away such 
programs, so it can help to write portably from the start. I'd have used

   newname = os.path.join(path,
  "%s_%s.%s" % (fname, pad, fext))
   os.rename(os.path.join(s[0], oldname), newname)

> fcount = fcount + 1
> 

Just a few pointers to make the script simpler, but your program is a 
very creditable first effort. Let us know what mistakes I made!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: How do i read line from an input file, without the /n

2005-12-14 Thread Gerard Flanagan
doritrieur wrote:

>  can anyone
> refer me to an online source that supplies the relevant data for syntax


http://rgruet.free.fr/PQR2.3.html
http://www.google.com

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


Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
How can I get rid of recursive call __getattr__ inside this method, if
i need to use method or property of the class?

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


Re: Still Loving Python

2005-12-14 Thread Peter Decker
On 12/13/05, Mike Meyer <[EMAIL PROTECTED]> wrote:

> > Why this need to have everyone do things the way you do?
>
> Whatever makes you think I have this need? I said I hated them. I'm
> pretty sure I didn't say everyone should have to use them.

Sorry, but there is a world of difference between saying "I prefer X
over Y" and "Yes, Y is evil". And unless English is a second language
for you, it's insulting to imply a difference between calling
something evil and agreeing with someone who did, even if you added a
smiley.

This is a 'discussion' list. Nothing kills discussion faster than
zealots who call those who disagree with them evil or idiots or
clueless n00bs.

--

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


Re: Python C/API - *arg,**kwds variable argumnents

2005-12-14 Thread Raymond L. Buvel
[EMAIL PROTECTED] wrote:
> I am writing a C extension with python 2.3.5 and need constructs
> similar to python
>func(*args, **kwds)
> What's a neat way to do that?
> I found pyrex has a __Pyx_GetStarArgs -
> is there something I'm missing from the regular C/API maybe using one
> of the PyArg_Parse.. calls ?
> 
> Thanks,
> M.
> 

It looks like the PyArg_ParseTupleAndKeywords API call is what you are
looking for.  Documentation is

http://python.org/doc/2.4.2/ext/parseTupleAndKeywords.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get rid of recursive call __getattr__

2005-12-14 Thread bruno at modulix
Pelmen wrote:
> How can I get rid of recursive call __getattr__ inside this method, if
> i need to use method or property of the class?
> 
Sorry, but I don't understand your question. Which recursive calls to
__getattr__ ? __getattr__ is only called if a/ it's defined and b/ the
attribute has not been found (see below).

Have you overriden __setattr__ or __getattribute__ ? If yes, please read
the corresponding sections of the Fine Manual.


>>> class Toto(object):
... def __init__(self, name):
... self.name = name
... def __getattr__(self, attname):
... print "__getattr__ called for %s" % attname
... return "%s doesn't exists" % attname
...
>>> t = Toto('toto')
>>> t.name = name
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'name' is not defined
>>> t.name
'toto'
>>> t.age
__getattr__ called for age
"age doesn't exists"

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Developing a network protocol with Python

2005-12-14 Thread Paul Rubin
Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
> But how can I transfer pure python objects otherwise? Pyro also uses
> Pickle and it also transfers bytecode.

Pyro in the past used pickle in an insecure way.  I'd heard it had
been fixed and I didn't realize it still uses pickle.

> I read somewhere that Pickle had a security problem before Python 2.2,
> but after 2.2 it has been solved.

If you use pickle in the obvious way, it's definitely still insecure.
There is some info in the docs about how to use some special pickle
features to protect yourself from the insecurity, but you have to go
out of your way for that.  I'm skeptical that they really protect you
in all cases, so I'd avoid unpickling any untrusted data.  But I don't
know a specific exploit

> BTW how CORBA or COM does this? They can do object marshaling safely.

I think they don't let you marshal arbitrary class instances and have
the class constructors called as part of demarshalling (COM anyway, I
don't know about CORBA).

>  Can we do the same with Python?

Yes, of course, it's possible in principle, but pickle doesn't do it
that way.

See SF RFE #467384 and bug #471893 for some more discussion of this.
Basically I think these issues are better understood now than they
were a few years ago.

> Isn't it enough to implement find_global of a cPickler ?

I can't definitely say the answer is no but I feel quite paranoid
about it.  The cPickle code needs careful review which I don't think
it's gotten.  It was not written with security in mind, though some
security hacks were added as afterthoughts.  I continue to believe
that Python should have a deserializer designed to be absolutely
bulletproof no matter what anyone throws at it, and it doesn't
currently have one.  I've gotten by with limited, ad hoc wire formats
for the applications where I've needed them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Tim N. van der Leeuw

Pelmen wrote:
> How can I get rid of recursive call __getattr__ inside this method, if
> i need to use method or property of the class?

Hi Pelmen,

Having read the docs included with my Python distribution on
__getattr__, I don't see yet how you will get recursive calls to the
method... (It's called only when the attribute cannot be looked up via
normal means)

If you are seeing recursive calls to __getattr__, perhaps you can
highlight the problem with some sample-code?

regards,

--Tim

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
thanks, i should been read more closely

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
thanks, i understood my mistake
i try to get attribute, that wasn't defined

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
as __repr__ for example?

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
thanks, i found the problem

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


Re: Still Loving Python

2005-12-14 Thread Daniel Crespo
Lawrence Oluyede wrote:

> ps. the customer wants Windows as a platform, we develop on Linux using
> PyGTK, postgre and sql server for some old data. This is the true power of
> cross-platform :)

PyGTK is crossplatform, that's true, but it looks very ugly under
Windows and don't know under MacOS (if it's supported). I couldn't find
the way for get it running with an atractive look & feel under Windows
after compiling it. Also, it needs the GTK+ Runtime Environment. I use
wxPython and it is very very very very good. It's not perfect, but IMO,
it is much better than PyGTK. PyGTK is good if you intend to develop
for Linux.

Daniel

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


Re: Still Loving Python

2005-12-14 Thread TwistyCreek
Peter Decker wrote:

> On 12/13/05, Mike Meyer <[EMAIL PROTECTED]> wrote:
> 
>> > Why this need to have everyone do things the way you do?
>>
>> Whatever makes you think I have this need? I said I hated them. I'm
>> pretty sure I didn't say everyone should have to use them.
> 
> Sorry, but there is a world of difference between saying "I prefer X over
> Y" and "Yes, Y is evil". And unless English is a second language for you,
> it's insulting to imply a difference between calling something evil and
> agreeing with someone who did, even if you added a smiley.
> 
> This is a 'discussion' list. Nothing kills discussion faster than zealots
> who call those who disagree with them evil or idiots or clueless n00bs.

Except maybe anal retentive prats who argue semantics to cover up the fact
that they wouldn't know a for loop from a foreskin.

And by the by... visual tools ARE evil. 

It's like your dad getting his drunken bar buddies to plow your mother
because he's too  fat to do it himself. The unfortunate offspring of any
such union is equally the bastard be it human or machine. It will have
this queer tendency to have the same eyes as the guy over in the corner,
luxuriating in a puddle of his own urine.

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
>>> class Test:
  def __getattr__(self, attr):
print attr

  def foo(x):
print x

>>> t = Test()
>>> print t
__str__

Traceback (most recent call last):
  File "", line 1, in -toplevel-
print t
TypeError: 'NoneType' object is not callable

what i have to do? define __str__ explicitly?

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


Re: ElementTree - Why not part of the core?

2005-12-14 Thread Istvan Albert
> $ python
> Python 2.5a0 (#1, Dec 12 2005, 19:26:49)
>>> import xml.etree.ElementTree as ET

hip hip hurray!

> http://svn.python.org/view/python/trunk/Lib/xml/etree/

don't know how this works, the link now seems to be:

http://svn.python.org/view/python/trunk/Lib/xmlcore/etree/

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


Re: Still Loving Python

2005-12-14 Thread Peter Decker
On 14 Dec 2005 13:49:39 -, TwistyCreek <[EMAIL PROTECTED]> wrote:

> And by the by... visual tools ARE evil. 
>
> It's like your dad getting his drunken bar buddies to plow your mother
> because he's too  fat to do it himself. The unfortunate offspring of any
> such union is equally the bastard be it human or machine. It will have
> this queer tendency to have the same eyes as the guy over in the corner,
> luxuriating in a puddle of his own urine.

Wow, I can't think of a response that would make you look more
clueless than what you just wrote.

And thank you for making my point: zealots have no place in a
discussion list, since they are incapable of discussing.

--

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


Re: Still Loving Python

2005-12-14 Thread Lawrence Oluyede
Il 2005-12-14, Daniel Crespo <[EMAIL PROTECTED]> ha scritto:
> PyGTK is crossplatform, that's true, but it looks very ugly under
> Windows and don't know under MacOS (if it's supported). 

You can use themes. Under MacOSX you have to install X11, but a native
version in on the way.

> I couldn't find
> the way for get it running with an atractive look & feel under Windows
> after compiling it. Also, it needs the GTK+ Runtime Environment. I use
> wxPython and it is very very very very good. It's not perfect, but IMO,
> it is much better than PyGTK. PyGTK is good if you intend to develop
> for Linux.

So wxPython doesn't need a runtime? I don't think so.  wxPython for me
sucks under Linux (built on gtk2) and I don't like its API at all. It
seems a bit awkward to me. Anyway... what do you mean with "much better" ?

-- 
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Still Loving Python

2005-12-14 Thread Martin Christensen
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

> "Bengt" == Bengt Richter <[EMAIL PROTECTED]> writes:
Bengt> De gustibus non disputandum, or whatever ;-)

Yeah, and quidquid latine dictum sit, altum viditur. :-)

Martin
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using Mailcrypt+GnuPG 

iEYEARECAAYFAkOgIuoACgkQYu1fMmOQldULYwCgjZovLw/gTJ8I/z/Wem203aca
DUUAoJ7GNNn2QOrmFINrgw58OkRnBmJU
=mUHX
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Steve Holden
Pelmen wrote:
> How can I get rid of recursive call __getattr__ inside this method, if
> i need to use method or property of the class?
> 
The usual mistake here is to write a __getattr__() implementation that 
references an undefined self-relative name, which leads to a recursive 
call of __getattr__(), which ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: First practical Python code, comments appreciated

2005-12-14 Thread Paul McGuire
"Steve Holden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> That form is non-portable. You might argue "I'm never going to run this
> program on anything other than Windows", and indeed for throwaway
> programs it's often easier to write something non-portable. It's
> surprising, though, how often you end up *not* throwing away such
> programs, so it can help to write portably from the start. I'd have used
>
>newname = os.path.join(path,
>   "%s_%s.%s" % (fname, pad, fext))
>os.rename(os.path.join(s[0], oldname), newname)
>
> > fcount = fcount + 1
> >
>
> Just a few pointers to make the script simpler, but your program is a
> very creditable first effort. Let us know what mistakes I made!
>

Just to chime in, and say that Steve's comments on portable programming have
to do with more than just your code running on other machines.  Developing
habits such as portable programming helps you to do these kinds of things
naturally, rather than to have to make a special effort if/when the issue
does come up.  Meanwhile, your portfolio of developed code reflects a
broader thinking span on your part, beyond just "let me whip together
something quick for the problem at hand."  When presenting your work, at a
conference or a job interview, it always helps to convey that you can see
the bigger picture.

Also, developing portable coding habits makes it easier for *you* to
assimilate code that others may have written for other platforms -
portability is an n-way street.  If you download some code fragment from
SourceForge, or from a tutorial, or a PyCon presentation, you will be less
likely to scratch your head over the purpose of os.join if you are in the
habit of using it already.

Otherwise, your code (with Steve's comments) is good, and it looks like it
does the job.  But I would also look over some tutorials, or examples of
existing code - Python comes with a huge set of sample code in the provided
libraries, and if you simply "self-teach" yourself, you can develop some bad
habits, and remain ignorant of some nice features and best practices.

Look at the use of native data structures (tuples, lists, and dicts), the
use of classes and class hierarchies, the uses of the module library, and
some of the relatively recent idioms of generators, list
comprehensions/generator expressions.  Look at the layout of the code to see
how the author broke the problem into manageable pieces.  Look for some of
the modules that crop up over and over again - not just sys, os, and math,
which are analogous to the C RTL, but also itertools, which I think is more
in the category of useful magic, like the C++ STL's  module.

Look for object design concepts, such as containment and delegation, and ask
yourself how well they fit the problem for the given script.  If you are new
to object-oriented coding as well, read some of the free online Python
introductory texts, such as "Dive into Python" and "Think like a Computer
Scientist in Python," to learn how some of the object design idioms
translate to Python's type and language model.

Python expertise comes in a series of plateaus, over time and with practice.
It's a stimulating and rewarding journey, no matter which plateau you
reach - welcome to Python!

-- Paul


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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Peter Otten
Pelmen wrote:

> >>> class Test:
>   def __getattr__(self, attr):
> print attr
> 
>   def foo(x):
> print x
> 
> >>> t = Test()
> >>> print t
> __str__
> 
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> print t
> TypeError: 'NoneType' object is not callable
> 
> what i have to do? define __str__ explicitly?

By seemingly not returning anything your __getattr__() method actually
returns None. Instead you should raise an AttributeError when your
__getattr__() encounters the name of an attribute it doesn't handle.
Let's assume Test.__getattr__() should implement an attribute 'alpha' and
nothing else:

>>> class Test:
... def __getattr__(self, name):
... print "looking up", name
... if name == "alpha":
... return 42
... print "lookup failed for", name
... raise AttributeError
...
>>> print Test()
looking up __str__
lookup failed for __str__
looking up __repr__
lookup failed for __repr__
<__main__.Test instance at 0x4029248c>

When the lookup fails in the instance it is deferred to the class.
By the way, new-style classes handle __special__ methods a bit differently
-- try deriving Test from object 

class Test(object):
   # same as above

to see the difference.

Peter

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


Re: Which Python web framework is most like Ruby on Rails?

2005-12-14 Thread DH
Alex Martelli wrote:
> Alternatively, counting Google hits:
> 
> rails python django 112,000
> rails python subway  81,600
> rails python turbogears  32,000
> 
> This isn't exactly "buzz", of course, but it's SOME measure of "critical
> mass" -- and with django about equal to subway+turbogears, it does not
> appear to show any emerging dominance.  A significant measure of "buzz"
> might be obtained by redoing the same search in, say, two weeks, and
> noticing the deltas...

Actually the turbogears mailing list has ~850 subscribers while
the django one has ~650.  I don't think that should be interpreted
as anything, but it does show the opposite of what you found with
the google search.  They both have "buzz".
Also others are working on another rails-like framework
called pylons: http://pylons.groovie.org/project
Because of course if other languages have 1 or two frameworks, python
needs a dozen.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Python web framework is most like Ruby on Rails?

2005-12-14 Thread Luis M. Gonzalez
As fas as I know, TurboGears is not very different.
But it is a project that unifies many different third party components
into one integrated package.
Its main component is CherryPy, which is a known python web framework.

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Pelmen
thanks, now all clear

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


Re: First practical Python code, comments appreciated

2005-12-14 Thread planetthoughtful
Thanks to both Steve and Paul!

I actually come from a PHP background, and I'm learning Python, oddly
enough, as a result of recently purchasing a USB Flash Drive, and
through wanting to be able to carry a portable programming language on
the drive so that I have the capability of developing / using useful
code wherever I happen to be (I'm actually using Movable Python
http://www.voidspace.org.uk/python/movpy/ - I hope it's not lacking in
any fundamental way).

To be honest, I could have achieved the same result more gracefully in
PHP (and I know that will cause some eyebrows to arch over the
suggestion that anything can be done gracefully in PHP), but that's
simply because I'm very comfortable with its syntax and with writing
economical code in it, not because it's actually well-suited to that
type of task.

I'm already working through Dive Into Python, which seems to be a good
starting place. Thankfully, I'm comfortable with OO concepts, at least
in how they are expressed in PHP5, so I'm not entirely lost in
unfamiliar territory with those aspects of Python.

My big learning curve will come, I suspect, when I move into creating
GUI apps with Python and wxPython, since that's my end goal - to be
able to carry several self-developed applications on my Flash Drive
that aren't dependent on any resources not found on the Flash Drive.

But, you have to learn to crawl before you can learn to code, so
approaching basic tasks like the one in my first attempt at a practical
application of Python are a good way to begin.

Thanks to both for your comments and advice!

Much warmth,

planetthoughtful

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


Re: Visual Python, really "Visual"?

2005-12-14 Thread Maurice LING
Tolga wrote:
> After a very rapid entrance into the Python, I have immediately looked
> for a good IDE. Komodo and Wing IDE look very good and I think they are
> enough. But now, I am searching for a Pyhton environment which should
> look like Delphi / Kylix, Borland's C++ builder or Allegro Common Lisp.
> I have found a plug-in named "Visual Python" and this name naturally
> maked me happy. But is it really "Visual" and does it provide a WYSIWYG
> rapid development environment? Has it drag'n drop buttons, checkboxes,
> radio buttons, forms et cetera?
> 

Please correct me if I am wrong. It seems that most of the python GUI 
builders require or is based on wxPython or others and not tkinter. I am 
using Mac OSX with Fink, so it is a real hassle for me to build wxPython 
and install it (haven't had much luck over the last 4-6 tries).

So, is there any python GUI builders based on tkinter? Personally, I 
prefer to drag and design a screen rather than programming it abstractly.

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


Re: ElementTree - Why not part of the core?

2005-12-14 Thread Steve Holden
Istvan Albert wrote:
>>$ python
>>Python 2.5a0 (#1, Dec 12 2005, 19:26:49)
>>
import xml.etree.ElementTree as ET
> 
> 
> hip hip hurray!
> 
> 
>>http://svn.python.org/view/python/trunk/Lib/xml/etree/
> 
> 
> don't know how this works, the link now seems to be:
> 
> http://svn.python.org/view/python/trunk/Lib/xmlcore/etree/
> 
For 2.5 the current xml namespaces will, I believe, move to xmlcore.

Compatibility code will replace the current xml package, to ensure that 
core modules not replaced by other components will still be available 
under their old names. This will allow better handling of fallbacks 
when, say, an optional C extension module is absent and it can be 
replaced by an xmlcore pure Python module.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Windows Services

2005-12-14 Thread Peter Hansen
Mondal wrote:
> Can anybody tell me how to develop Windows Services (which are actually
> daemons) using Python. 

Yes, anyone can tell you.  Anyone who can use Google that is.  Can you?

http://www.google.com/search?q=python+windows+service

(There are directly relevant answers on the first page of results.)

> Also what protocol is most suitable for
> developing a server-client application with the server running as a
> Windows Service.

I'd suggest whatever protocol is most suitable for developing 
client-server applications with the server *not* running as a Windows 
Service.  In other words, I don't think the manner in which the service 
is invoked has much impact on the protocol you would use.

Generally the best protocol is determined more by what your server will 
actually do, and performance requirements, than anything else.

-Peter

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


Re: First practical Python code, comments appreciated

2005-12-14 Thread Steve Holden
Paul McGuire wrote:
[...]
> portability is an n-way street. 
+1 QOTW

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: disassemble, was(How do (not) I distribute my Python progz?)

2005-12-14 Thread Juergen Kareta

Hi Steven,


>What makes you think I'm a serious programmer? *wink*

Ok, it's not a 'serious' investigation, but maybe it could be, that you
(sometimes) quote something usefull  ;-)


> Python's byte-code is not exactly as easy to understand as native Python,
> but it is still understandable. And I wonder, is there a program which
> will try to generate Python code from the output of the disassembler?

look at:
http://www.crazy-compilers.com/decompyle/

it's only a online service. But if it works, it would be nice to have 
such a tool as standalone programm.

Thanks a lot.

regards,
Jürgen
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: First practical Python code, comments appreciated

2005-12-14 Thread Steve Holden
Paul McGuire wrote:
[...]
> portability is an n-way street. 
+1 QOTW

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: "0 in [True,False]" returns True

2005-12-14 Thread Grant Edwards
On 2005-12-14, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

>> Well, as you might argue, I'm not tryng to effect a change in your
>> behaviour, I'm simply trying to point out how it could be made more
>> rational.
>
> What would be the difference in his usage and allowing Null in a RDBMS
> column?

Don't know -- homey don't play 'dat.

> Or return NaN instead of raising exception for numeric
> functions ?

Because usually (in my applications anyway) NaN is a perfectly
valid value and not an "exception" case that needs to be handled.

-- 
Grant Edwards   grante Yow!  Am I in GRADUATE
  at   SCHOOL yet?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Optimize function similiar to dict.update() but adds common values

2005-12-14 Thread Gregory Piñero
Hey guys,

I thought I'd throw this out there since everyone loves optimization
questions (it's true, check out the number of replies to those type of
questions!)

Right now I have a function shown below.  I want to combine two
dictionaries and add the values together where-ever there is overlap. 
I figured this function would be reasonably fast, but I have around 1
million keys in each dictionary (~80% overlap) and it just runs all
night.

So maybe my function is not O(n)?  I really figured it was but maybe
dictionary lookups are O(nlogn)?

Anyway here is the function.  Any ideas on doing this task a lot
faster would be appriciated.

Thanks!



def add_freqs(freq1,freq2):
"""Add two word freq dicts"""
newfreq={}
for key,value in freq1.items():
newfreq[key]=value+freq2.get(key,0)
for key,value in freq2.items():
newfreq[key]=value+freq1.get(key,0)
return newfreq

freq1={
'dog':1,
'cat':2,
'human':3
}
freq2={
'perro':1,
'gato':1,
'human':2
}
print add_freqs(freq1,freq2)

answer_I_want={
'dog':1,
'cat':2,
'perro':1,
'gato':1,
'human':5
}



--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Steve Holden
Peter Otten wrote:
> Pelmen wrote:
> 
> 
>class Test:
>>
>>  def __getattr__(self, attr):
>>print attr
>>
>>  def foo(x):
>>print x
>>
>>
>t = Test()
>print t
>>
>>__str__
>>
>>Traceback (most recent call last):
>>  File "", line 1, in -toplevel-
>>print t
>>TypeError: 'NoneType' object is not callable
>>
>>what i have to do? define __str__ explicitly?
> 
> 
> By seemingly not returning anything your __getattr__() method actually
> returns None. Instead you should raise an AttributeError when your
> __getattr__() encounters the name of an attribute it doesn't handle.
> Let's assume Test.__getattr__() should implement an attribute 'alpha' and
> nothing else:
> 
> 
class Test:
> 
> ... def __getattr__(self, name):
> ... print "looking up", name
> ... if name == "alpha":
> ... return 42
> ... print "lookup failed for", name
> ... raise AttributeError

or, rather better IMHO,

   raise AttributeError("lookup failed for %s" % name)
> ...
> 
regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Get rid of recursive call __getattr__

2005-12-14 Thread Peter Hansen
Pelmen wrote:
class Test:
> 
> def __getattr__(self, attr):
>   print attr
> 
> def foo(x):
>   print x
> 
> 
t = Test()
print t
> 
> __str__
> 
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> print t
> TypeError: 'NoneType' object is not callable
> 
> what i have to do? define __str__ explicitly?

Yes.  Or subclass "object" as it has a default __str__ already.

(By the way, you do realize that the NoneType message comes because your 
__getattr__ is returning None, don't you?  So technically you could also 
return a real value (in this case a callable) and it would also work, 
though it's very likely not what you wanted.

class Test:
 def __getattr__(self, name):
 def callable_attribute():
 return 'i am attr %s' % name
 return callable_attribute

 >>> t = Test()
 >>> print t
i am attr __str__

-Peter

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


Re: Still Loving Python

2005-12-14 Thread Mike Meyer
[EMAIL PROTECTED] (Bengt Richter) writes:
> A single click compiles, links and runs the resulting independent windows 
> .exe in a fraction of a second
> for the above, and I can see the hint, kill the .exe, and go on where I was.

Click? Yuck. If I wanted it, I've had environments where a single
keystroke (much better) compiled, linked and ran the resulting
app. Not in a fraction of a second, but that's sort of irrelevant to
the GUI/non-GUI question.

  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: "0 in [True,False]" returns True

2005-12-14 Thread Antoon Pardon
Op 2005-12-14, Grant Edwards schreef <[EMAIL PROTECTED]>:
> On 2005-12-14, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
>>> Well, as you might argue, I'm not tryng to effect a change in your
>>> behaviour, I'm simply trying to point out how it could be made more
>>> rational.
>>
>> What would be the difference in his usage and allowing Null in a RDBMS
>> column?
>
> Don't know -- homey don't play 'dat.
>
>> Or return NaN instead of raising exception for numeric
>> functions ?
>
> Because usually (in my applications anyway) NaN is a perfectly
> valid value and not an "exception" case that needs to be handled.

I don't see the difference. In my application False and True
(or Registered and UnRegistered if you prefer) are perfectly valid
values too.  They are not "exception" cases that need to be
handled.

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


Re: Still Loving Python

2005-12-14 Thread Mike Meyer
Peter Decker <[EMAIL PROTECTED]> writes:
> On 12/13/05, Mike Meyer <[EMAIL PROTECTED]> wrote:
>> > Why this need to have everyone do things the way you do?
>> Whatever makes you think I have this need? I said I hated them. I'm
>> pretty sure I didn't say everyone should have to use them.
> Sorry, but there is a world of difference between saying "I prefer X
> over Y" and "Yes, Y is evil". And unless English is a second language
> for you, it's insulting to imply a difference between calling
> something evil and agreeing with someone who did, even if you added a
> smiley.

I don't agree. I do apologize, though - no insult as intended.

> This is a 'discussion' list. Nothing kills discussion faster than
> zealots who call those who disagree with them evil or idiots or
> clueless n00bs.

There's also a world of difference between saying "X is evil" and
saying "users of X are evil."  Unless English is a second language for
you, going from a statement about X to a statement about is users of X
is insulting.

   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: Still Loving Python

2005-12-14 Thread Steve Holden
TwistyCreek wrote:
> Peter Decker wrote:
> 
> 
>>On 12/13/05, Mike Meyer <[EMAIL PROTECTED]> wrote:
>>
>>
Why this need to have everyone do things the way you do?
>>>
>>>Whatever makes you think I have this need? I said I hated them. I'm
>>>pretty sure I didn't say everyone should have to use them.
>>
>>Sorry, but there is a world of difference between saying "I prefer X over
>>Y" and "Yes, Y is evil". And unless English is a second language for you,
>>it's insulting to imply a difference between calling something evil and
>>agreeing with someone who did, even if you added a smiley.
>>
>>This is a 'discussion' list. Nothing kills discussion faster than zealots
>>who call those who disagree with them evil or idiots or clueless n00bs.
> 
> 
> Except maybe anal retentive prats who argue semantics to cover up the fact
> that they wouldn't know a for loop from a foreskin.
> 
> And by the by... visual tools ARE evil. 
> 
> It's like your dad getting his drunken bar buddies to plow your mother
> [...]  in a puddle of his own urine.
> 
And that's quite enough of that, thanks.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Newbie needs help with regex strings

2005-12-14 Thread Catalina Scott A Contr AFCA/EVEO
I have a file with lines in the following format.

pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'

I would like to pull out some of the values and write them to a csv
file.

For line in filea
pie = regex
quantity = regex
cooked = regex
ingredients = regex
fileb.write (quantity,pie,cooked,ingredients)

How can I retreive the values and assign them to a name?

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


Re: definition of 'polymorphism' and python

2005-12-14 Thread Grant Edwards
On 2005-12-14, Gabriel Zachmann <[EMAIL PROTECTED]> wrote:

> I understand the Wikipedia article on Polymorphism (
> http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29
> ) that it doesn't make sense to talk about polymorphism in a
> fully dynamically typed language -- does the Python community
> agree?

No.

-- 
Grant Edwards   grante Yow!  Youth of today! Join
  at   me in a mass rally
   visi.comfor traditional mental
   attitudes!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Python web framework is most like Ruby on Rails?

2005-12-14 Thread gene tani

DH wrote:
> Alex Martelli wrote:

> Because of course if other languages have 1 or two frameworks, python
> needs a dozen.

["there are still fewer %s than py keywords"%x for x in ["IDEs","web
app frameworks","GUI frameworks"]]

and 37000 google hits for "Snakes and Rubies"?!

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


Re: writing IM bots

2005-12-14 Thread Amit Khemka
thank you all for ur suggestions .. I got msnp and curfoo(for yahoo)
customized and working  :-) .. though they are pretty slow in
responding to messages  ... will try jabber based
protocols,

cheers,
amit.

On 12/14/05, Linsong <[EMAIL PROTECTED]> wrote:
>Why not twisted.words, for me, twisted can solved almost all(if not
> all, you can implement it under twisted framework easily) internet
> protocol related tasks and it is really *cool*!
>Twisted Words includes:
>
> * Low-level protocol implementations of OSCAR (AIM and ICQ), IRC,
>   MSN, TOC (AIM).
> * Jabber libraries.
> * Prototypes of chat server and client frameworks built on top of
>   the protocols.
>
>I have used twisted.words for IRC and MSN, it works very well. Never
> forget to investigate the other projects of twisted, it will give you a
> lot back.
> http://twistedmatrix.com/projects/words/
>
> Good Luck!
> Linsong
>
>
> Amit Khemka wrote:
>
> >Hello,
> >I am trying to write an IM Bot, which automatically replies to a
> >message, in Python.
> >I was wondering If there are python modules for connecting to Yahoo!,
> >msn networks ...
> >ideally I would like to have a multithreaded module.
> >
> >This is one I found for msn, if anyone has used it please comment,
> >- http://users.auriga.wearlab.de/~alb/msnlib/
> >
> >cheers,
> >amit.
> >
> >
> >--
> >
> >Endless the world's turn, endless the sun's spinning
> >Endless the quest;
> >I turn again, back to my own beginning,
> >And here, find rest.
> >
> >
>
>


--

Endless the world's turn, endless the sun's spinning
Endless the quest;
I turn again, back to my own beginning,
And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "0 in [True,False]" returns True

2005-12-14 Thread Grant Edwards
On 2005-12-14, Antoon Pardon <[EMAIL PROTECTED]> wrote:

 Well, as you might argue, I'm not tryng to effect a change in
 your behaviour, I'm simply trying to point out how it could be
 made more rational.
[...]
>>> Or return NaN instead of raising exception for numeric
>>> functions ?
>>
>> Because usually (in my applications anyway) NaN is a perfectly
>> valid value and not an "exception" case that needs to be
>> handled.
>
> I don't see the difference. In my application False and True
> (or Registered and UnRegistered if you prefer) are perfectly
> valid values too.  They are not "exception" cases that need to
> be handled.

Well, in my case, a given name (or return value) is always
bound to a floating point object. I don't test the type of the
object and treat it in two different ways depending on what
type it is.  It's just a float.

-- 
Grant Edwards   grante Yow!  .. Do you like
  at   "TENDER VITTLES?"?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: definition of 'polymorphism' and python

2005-12-14 Thread gene tani

Grant Edwards wrote:
> On 2005-12-14, Gabriel Zachmann <[EMAIL PROTECTED]> wrote:
>
> > I understand the Wikipedia article on Polymorphism (
> > http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29
> > ) that it doesn't make sense to talk about polymorphism in a
> > fully dynamically typed language -- does the Python community
> > agree?
>
> No.


Excellent.  Maybe we can have a gentleman's agreement to confine all
unfocused arguments about following terms to Artima.com and C2 wiki

Strong, weak, static, dynamic, latent, duck typing
polymorphism, encapsulation, delegation, 

;-}

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


Re: const objects (was Re: Death to tuples!)

2005-12-14 Thread Christopher Subich
Gabriel Zachmann wrote:
> 
> I was wondering why python doesn't contain a way to make things "const"?
> 
> If it were possible to "declare" variables at the time they are bound to 
> objects that they should not allow modification of the object, then we 
> would have a concept _orthogonal_ to data types themselves and, as a 
> by-product, a way to declare tuples as constant lists.
.
.
.
> It seems to me that implementing that feature would be fairly easy.
> All that would be needed is a flag with each variable.

Nope, that's not all you need; in fact, your definition of 'const' 
conflates two sorts of constants.

Consider:

 >>>const l = 1
 >>>l = 2 # error?

And
 >>>const l = []
 >>>l.append(foo) # error?

with its more general:
 >>>const foo = MyClass()
 >>>foo.myMethod() # error?  myMethod might mutate.

And none of this can prevent:
 >>>d = {}
 >>>const foo=[d]
 >>>d['bar']='baz'

The first "constant" is the only well-defined one in Python: a constant 
name.  A "constant" name would prohibit rebinding of the name for the 
scope of the name.  Of course, it can't prevent whatsoever mutation of 
the object which is referenced by the name.

Conceptually, a constant name would be possible in a python-like 
language, but it would require significant change to the language to 
implement; possibly something along the lines of name/attribute 
unification (because with properties it's possible to have 
nearly-constant[1] attributes on class instances).

The other form of constant, that of a frozen object, is difficult 
(probably impossible) to do for a general object: without knowing ahead 
of time the effects of any method invocation, it is very difficult to 
know whether the object will be mutated.  Combine this with exec/eval 
(as the most absurd level of generality), and I'd argue that it is 
probably theoretically impossible.

For more limited cases, and for more limited definitions of immutable, 
and ignoring completely the effects of extremely strange code, you might 
be able to hack something together with a metaclass (or do something 
along the lines of a frozenset).  I wouldn't recommend it just for 
general use.

Really, the single best purpose of constant names/objects is for 
compiler optimization, which CPython doesn't do as-of-yet.  When it 
does, possibly through the PyPy project, constants will more likely be 
discovered automatically from analysis of running code.

[1] -- barring straight modification of __dict__
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OO in Python? ^^

2005-12-14 Thread Christopher Subich
Antoon Pardon wrote:
> Suppose we would add type declarations in python.
> So we could do things like
> 
>   int: a
>   object: b
> 
> Some people seem to think that this would introduce static
> typing, but the only effect those staments need to have
> is that each time a variable is rebound an assert statement
> would implicitly be executed, checking whether the variable is
> still an instance of the declared type.

Doesn't work; duck typing is emphatically not subclass-typing.  For this 
system to still work and be as general as Python is now (without having 
to make all variables 'object's), we'd need true interface checking. 
That is, we'd have to be able to say:

implements + like int: a

or somesuch.  This is a Hard problem, and not worth solving for the 
simple benefit of checking type errors in code.

It might be worth solving for dynamic code optimization, but that's 
still a ways off.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to get the local mac address?

2005-12-14 Thread Daniel Crespo
Hi, I tried:

import ctypes
import socket
import struct

def get_macaddress(host):
""" Returns the MAC address of a network host, requires >= WIN2K.
"""

# Check for api availability
try:
SendARP = ctypes.windll.Iphlpapi.SendARP
except:
raise NotImplementedError('Usage only on Windows 2000 and
above')

# Doesn't work with loopbacks, but let's try and help.
if host == '127.0.0.1' or host.lower() == 'localhost':
host = socket.gethostname()

# gethostbyname blocks, so use it wisely.
try:
inetaddr = ctypes.windll.wsock32.inet_addr(host)
if inetaddr in (0, -1):
raise Exception
except:
hostip = socket.gethostbyname(host)
inetaddr = ctypes.windll.wsock32.inet_addr(hostip)

buffer = ctypes.c_buffer(6)
addlen = ctypes.c_ulong(ctypes.sizeof(buffer))
if SendARP(inetaddr, 0, ctypes.byref(buffer), ctypes.byref(addlen))
!= 0:
raise WindowsError('Retreival of mac address(%s) - failed' %
host)

# Convert binary data into a string.
macaddr = ''
for intval in struct.unpack('BB', buffer):
if intval > 15:
replacestr = '0x'
else:
replacestr = 'x'
macaddr = ''.join([macaddr, hex(intval).replace(replacestr,
'')])

return macaddr.upper()

if __name__ == '__main__':
print 'Your mac address is %s' % get_macaddress('localhost')

It works perfect under W2K and above. But I would like to run it on
Win98 too. Any help?

Thanks

Daniel

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


Re: const objects (was Re: Death to tuples!)

2005-12-14 Thread Magnus Lycka
Gabriel Zachmann wrote:
> 
> I was wondering why python doesn't contain a way to make things "const"?
> 
> If it were possible to "declare" variables at the time they are bound to 
> objects that they should not allow modification of the object, then we 
> would have a concept _orthogonal_ to data types themselves and, as a 
> by-product, a way to declare tuples as constant lists.
> 
> So this could look like this:
> 
> const l = [1, 2, 3]

That was a bit confusing. Is it the name 'l' or the list
object [1, 2, 3] that you want to make const? If you want
to make the list object immutable, it would make more sense
to write "l = const [1, 2, 3]". I don't quite see the point
though.

If you could write "const l = [1, 2, 3]", that should logically
mean that the name l is fixed to the (mutable) list object
that initially contains [1, 2, 3], i.e. l.append(6) is OK,
but l = 'something completely different" in the same scope
as "const l = [1, 2, 3]" would be forbidden.

Besides, what's the use case for mutable numbers for instance,
when you always use freely rebindable references in your source
code to refer to these numbers. Do you want to be able to play
nasty tricks like this?

 >>> f = 5
 >>> v = f
 >>> v++
 >>> print f
6

It seems to me that you don't quite understand what the
assignment operator does in Python. Please read
http://effbot.org/zone/python-objects.htm

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


Re: Difference between ActivePython and Python.org

2005-12-14 Thread Daniel Crespo
Good question, I have the same anxiety.

Thanks

Daniel

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


Re: First practical Python code, comments appreciated

2005-12-14 Thread Kent Johnson
planetthoughtful wrote:
> Hi All,
> 
> I've written my first piece of practical Python code (included below),
> and would appreciate some comments. My situation was that I had a
> directory with a number of subdirectories that contained one or more
> zip files in each. Many of the zipfiles had the same filename (which is
> why they had previously been stored in separate directories). I wanted
> to bring all of the zip files (several hundrd in total) down to the
> common parent directory and obviously rename them in the process by
> appending a unique string to each filename.
> 
> The code below did the job admirably, but I don't imagine it is
> anywhere near as efficiently written as it could and should be. Note:
> I'm aware there was no need, for example, to wrap the "os.walk(path)"
> statement in a def -- in a couple of places I added extra steps just to
> help familiarize myself with Python syntax.
> 
> I'd very much like to see how experienced Python coders would have
> achieved the same task, if any of you can spare a couple of minutes to
> share some knowledge with me.
> 
> Many thanks and much warmth,
> 
> planetthoughtful
> 
> import os
> fcount = 0
> path = 'X:\zipfiles'
> def listFiles(path):
> mylist = os.walk(path)
> return mylist

Note that os.walk() doesn't return a list, it returns an iterable object (a 
generator). 
Your usage will work for either, but your names are misnomers.
> 
> filelist = listFiles(path)
> for s in filelist:

I would write
for dirpath, dirnames, filenames in filelist:

which gives names to what you call s[0] and s[2]

or just
for dirpath, dirnames, filenames in os.walk(path):

Kent

> if len(s[2]) > 0:
> for f in s[2]:
> pad = str(fcount)
> if len(pad) == 1:
> pad = "00" + pad
> elif len(pad) == 2:
> pad = "0" + pad
> 
> (fname, fext) = os.path.splitext(f)
> oldname = f
> newname = fname + "_" + pad + fext
> os.rename(s[0] + "\\" + oldname, path + "\\" + newname)
> fcount = fcount + 1
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   >