Re: python needs leaning stuff from other language

2009-04-04 Thread Robert Kern

On 2009-04-03 23:48, Tim Wintle wrote:

On Fri, 2009-04-03 at 18:27 -0500, Robert Kern wrote:

agreed. If .clear was to be added then really assignments to slices
should be entirely removed.

Please tell me you are joking.


Well I'm not joking as such.

I've noticed that python-ideas seems to be positive on the idea, and has
a patch ready for Guido, obviously I'm not that anti it that I'd always
be complaining if it is implemented, I just see it as unnecessary:
http://mail.python.org/pipermail/python-ideas/2009-April/003933.html


Let's be clear: python-ideas seems positive on the idea of adding a .clear() 
method. *Completely removing* slice assignment has not been broached there.



(I didn't expect such strong responses btw!)


You are proposing the removal of a general, orthogonal feature (and breaking 
code in consequence!) just because of a new syntax for a single special case of 
that feature. That is quite simply ridiculous.


.clear() would be non-orthogonal syntactic sugar. That's okay! Python has 
syntactic sugar in a number of other places, too! Appropriate doses of syntactic 
sugar and non-orthogonality are precisely what lets you implement "There should 
be one-- and preferably only one --obvious way to do it." The really key word in 
that sentence is "obvious", not "one".


FWIW, removing slice assignment would be a gross form of non-orthogonality, too. 
__getitem__, __setitem__ and __delitem__ should all be able to accept the same 
indices (or else raise exceptions in the case of immutability).


--
Robert Kern

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

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


Re: Problem understanding some unit tests in Python distribution

2009-04-04 Thread Peter Otten
André wrote:

> Hi everyone,
> 
> In the hope of perhaps contributing some additional unit tests for
> Python (thus contributing back to the community), I dove in the code
> and found something that should be simple but that I can not wrap my
> head around.
> 
> In list_tests.py, one finds
> ===
> from test import test_support, seq_tests
> 
> class CommonTest(seq_tests.CommonTest):
> 
> def test_init(self):
> # Iterable arg is optional
> self.assertEqual(self.type2test([]), self.type2test())
> # etc.
> ===
> 
> Wanting to figure out what the type2test() method does, I looked in
> seq_tests.py and found the following:
> 
> ===
> class CommonTest(unittest.TestCase):
> # The type to be tested
> type2test = None
> 
> def test_constructors(self):
> l0 = []
> l1 = [0]
> l2 = [0, 1]
> 
> u = self.type2test()
> u0 = self.type2test(l0)
> u1 = self.type2test(l1)
> u2 = self.type2test(l2)
> 
> # etc.
> ===
> No where do I find a definition for the type2test() method - other
> than seeing it as a class variable defined to be None by default.  I
> looked in unittest.TestCase and did not see it anywhere.
> 
> Am I missing something obvious?  I would appreciate if someone could
> point me in the right direction.

Use grep ;)

CommonTest is not run standalone, it is used as a(n abstract) base class for
several other tests that override type2test. 

E. g. in Lib/test/list_tests.py:

from test import test_support, seq_tests

class CommonTest(seq_tests.CommonTest):
...

And then in Lib/test/test_list.py:

from test import test_support, list_tests

class ListTest(list_tests.CommonTest):
type2test = list
...

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


Re: Module caching

2009-04-04 Thread Graham Dumpleton
On Apr 4, 10:41 am, Jon Clements  wrote:
> On 3 Apr, 23:58, Aaron Scott  wrote:
>
> > > are you an experienced python programmer?
>
> > Yeah, I'd link to think I'm fairly experienced and not making any
> > stupid mistakes. That said, I'm fairly new to working with mod_python.
>
> > All I really want is to have mod_python stop caching variables. This
> > seems like it should be easy enough to do, but I can't for the life of
> > me find information on how to do it.
>
> > Aaron
>
> Umm... Well, mod_python works for long running processes that don't
> really store data, but return it on demand... so keeping module level
> variables around is going to be a gotcha.
>
> It's a kludge, but setting MaxRequestsPerChild to 1 in the Apache
> config basically forces a reload of everything for every request...
> that might be worth a go -- but it's nasty...

They may as well use CGI then. Personally I would never recommend
MaxRequestsPerChild be set to 1.

Anyway, this person also posted on mod_python list. One of the things
I highlighted there was that mod_python for some configurations is
multithreaded and as such they may not be properly protecting
variables if they are storing them at global scope. They haven't
responded to any comments about it on mod_python list. They were also
told to read:

  http://www.dscpl.com.au/wiki/ModPython/Articles/TheProcessInterpreterModel

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


TODAY April 4 -Guido & Python 3000 @ Global FSW Voice Meeting BerkeleyTIP -Linus,Guido,Shuttleworth...

2009-04-04 Thread john_re
Guido - Python 3000 video.
5PM Python hour

Anyone:  Please email me or the BTIP list if you know of any recent
(past 12 months) Python videos. Thanks. :)

Join with the friendly, productive, Global FSW community,
in the _TWICE_ monthly, Voice over internet meeting,
  BerkeleyTIP-Global.   GNU(Linux) & BSD, Free SW, HW & FreeCulture,
  Talks Installfest Project/ProgrammingParty
http://sites.google.com/site/berkeleytip/

NEW- _TWO_ monthly day long meetings- 10AM-6PM Pacific (GMT -8H) time,
  = 1P - 9P Eastern  =  6PM - 2AM (Sat to Sunday) GMT
  Join in as short or long as you like.
 1st Saturday - April  4*  TODAY  *
 3rd Sunday   - April 20


=  LOCATION - ONLINE, IN YOUR AREA, OR AT U. California Berkeley
http://sites.google.com/site/berkeleytip/remote-attendance
http://sites.google.com/site/berkeleytip/directions


= NEW VIDEOS:
Linux Torvalds- GIT
Mark Shuttleworth - Debian & Ubuntu - Debian & Derived Distros
Krafft Shuttleworth Levsen - Debian Derivers Roundtable
Fabricio Cannini  - Debian High Performance clusters and supercomputers
Guido Van Rossum  - Python 3000
BestTech LAMPR- Get Started with Ruby on Rails in < 5 minutes
Culture - Professor Wikipedia - The funniest video of the year.
  [Citation needed.]

[Thanks to all the speakers, videographers, & organizations.  :)
Please excuse if I mistyped names.  <8-0
I hereby invite the speakers to attend BTIP for Q&A & discussion.
Please notify the speakers if you know how to contact them, thanks. :) ]

Download the videos & watch them before or during the meeting.
Join online during the relevant topic hour to discuss each video.
[See below for longer talk descriptions.]
http://sites.google.com/site/berkeleytip/talk-videos


=  YOU GIVE A 5 MINUTE LIGHTNING TALK
4 PM.  Let us know in advance what you'd like to talk about. :)


= NEW MEETING COMPONENTS
FREE CULTURE - Wikipedia, Creative Commons, etc

COLLEGE MAJORS
  Business, Medicine, Law, Engineering,
  Art/Lit/Science/Social/Psych/Humanities/LiberalArts, etc

SOFTWARE: Games


= SCHEDULE / AGENDA 10AM - 6PM Pacific time (= GMT - 8 Hours)
TIMETOPIC / ACTIVITY
10 ASet up.  Get on IRC & VOIP
11 AInstallfest; Ekiga3
12 NAsterisk, OLPC, Games;
PROGRAMMING PARTY: VOIP Conference client & server
1 P Xen, Virtualbox; LAMPR - Database; Law; GNU
2 P KDE & GNOME; Macintosh; FreeCulture: Wikipedia,CreativeCommons
3 P Debian; BSD; College & University groups; Business
4 P LIGHTNING TALKS; Ubuntu
Hardware- Ex: OpenMoko Phone; Medicine
5 P Art/Literature/Music; Python; INetWebDev; 
Local simultaneous meetings arrangements for next meeting


= Voice/VOIP CONFERENCE MEETING TECHNOLOGY
Join in on IRC, & we'll help you get on VOIP.  :)

IRC: #BerkeleyTIP, irc.freenode.net
Hardware: VOIP Headset- (USB recommended for echo cancellation?)
Software: Ekiga(GnomeMeeting) recommended. SIP
VOIP server: Ekiga.net
http://sites.google.com/site/berkeleytip/remote-attendance


= LOCATION GROWTH:   GREAT PROGRESS
In March we QUADRUPLED our international attendance. :) Welcome :)
  GLOBAL: Germany, England, Iran, India
  US: So far: Hawaii, California, Washington, Michigan, Virgina,
  NCarolina
When will your state or country 1st join in???


=  PROJECT / PROGRAMMING PARTY
Work on your own project, or the group project.

Share details of your project on IRC, VOIP & the mailing list.  Invite
others to join in your project.

Or, work on the group project - Learning about & Improving Ekiga,
Asterisk, & our VOIP conference system/technology.


=  Join the Global BerkeleyTIP mailing list
http://groups.google.com/group/BerkTIPGlobal


=  THANKS, HOPE YOU JOIN;  FOR FORWARDING
I hope you join in the meeting.  :)

Join by yourself, or invite  your friends over & have a party.  Have a
party at your home, or at a local to you location - a WiFi cafe, or at a
college or university is a great place for a meeting.  :)

You are invited to forward this message wherever appropriate - Ex:
perhaps your local meeting group (LUG, etc), or whatever, if you see
this on a global mailing list.



===
= VIDEOS - MORE DETAILED DESCRIPTIONS:
3 from DebConf08:
1) Fabricio Cannini - Debian High Performance clusters and
supercomputers, 1hr

2) Mark Shuttleworth on Debian and Ubuntu - Keynote current state of
collaboration between Debian and Ubuntu, progress made, and new
opportunities for collaboration and development.

3) Debian Derivers Roundtable discussion - prominent developers of
Debian-derived works, including Martin (Debian Edu). 1hr

Linus Torvalds on Git - Git is a rewrite from scratch concurrent
versioning system that Linus wrote to replace cvs, subversion (svn) and
other versioning systems used in large collaborative software
development. Benefits, drawbacks and insufficiencies of other versioning
systems in common use.  Google Tech Talks

Guido Van Rossum, Python

Re: how to optimize zipimport

2009-04-04 Thread Coonay.appspot
On Apr 2, 6:26 pm, John Machin  wrote:
> On Mar 30, 11:39 pm, Coonay  wrote:
>
>
>
> > On Mar 26, 1:38 pm, John Machin  wrote:
>
> > > On Mar 26, 2:06 pm, Coonay  wrote:
>
> > > > On Mar 26, 10:41 am, Coonay  wrote:
>
> > > > > in my mudule ,i import another mudule from a zip ,
>
> > > > > when i call  my mudle method,the module in the zip will be import from
> > > > > the zip every time,that slow down the operation,
>
> > > > > i try to search the some workarodnd or solution but i don't get one,
>
> > i don't use zipimport directly,just like u said i put the zip in the
> > sys.path
>
> > i found the the module in the zip reloaded  everytime the code is
> > called,i mean, say ,first time it take me 1 second to call a method in
> > the zip,but it take another 1 second to call the mothod for another
> > time ,and so on
>
> How do you know that it is being reloaded each time a methos is
> called?
>
> > > Note: it may help when you reply to show a stripped-down version of
> > > your calling module, sufficient to back up your description of what is
> > > happening.
>
> We can only guess if you don't show us what is actually happening.
> Vague descriptions are not very useful. Show us how exactly you are
> importing the modules, how you are calling methods, with timing
> calls ...

yes , i put the pyc file with py source file in the zip
>
> By the way, have you read this part of the documentation:
> "Note that if an archive only contains .py files, Python will not
> attempt to modify the archive by adding the corresponding .pyc or .pyo
> file, meaning that if a ZIP archive doesn't contain .pyc files,
> importing may be rather slow."
> ?
>
> Do you have .pyc files in your ZIP file? If not that would make the
> first import slower than it should be.
>
> However second, third, ... imports (if you do any) should be
> instantaneous -- unless you are messing about deleting modules from
> sys.modules.
>
> And *method* calls should be instantaneous.



it run much faster when i unzip the lib and put then in a directory

>
> Does your app run at the same speed when you have all the modules in a
> directory instead of inside a zip file?
>
> Apart from code executed once at app start to inject the path to the
> zip file into sys.path, have you made any other changes to accommodate
> using import from zip? If so, what changes?
>
> Have you tried running your app from the shell (Windows translation:
> in a Command Prompt window) like this:
>
> python -v app_start.py
>
> This will show you all the imports as they happen.
>
> HTH ... but a clear description from you (plus code samples) of
> exactly what you are doing woul dhelp a whole lot more.
>
> John

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


Re: Hash of None varies per-machine

2009-04-04 Thread Thomas Bellman
Steven D'Aprano  wrote:

> You can hash numbers no matter how big they are.

> >>> hash(float('inf'))
> 314159

Cute.  And hash(float('-inf')) is -271828...


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"God is real, but Jesus is an integer."  !  bellman @ lysator.liu.se
 !  Make Love -- Nicht Wahr!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problem understanding some unit tests in Python distribution

2009-04-04 Thread André
On Apr 4, 4:38 am, Peter Otten <[email protected]> wrote:
> André wrote:
> > Hi everyone,
>
> > In the hope of perhaps contributing some additional unit tests for
> > Python (thus contributing back to the community), I dove in the code
> > and found something that should be simple but that I can not wrap my
> > head around.
>
> > In list_tests.py, one finds
> > ===
> > from test import test_support, seq_tests
>
> > class CommonTest(seq_tests.CommonTest):
>
> >     def test_init(self):
> >         # Iterable arg is optional
> >         self.assertEqual(self.type2test([]), self.type2test())
> > # etc.
> > ===
>
> > Wanting to figure out what the type2test() method does, I looked in
> > seq_tests.py and found the following:
>
> > ===
> > class CommonTest(unittest.TestCase):
> >     # The type to be tested
> >     type2test = None
>
> >     def test_constructors(self):
> >         l0 = []
> >         l1 = [0]
> >         l2 = [0, 1]
>
> >         u = self.type2test()
> >         u0 = self.type2test(l0)
> >         u1 = self.type2test(l1)
> >         u2 = self.type2test(l2)
>
> > # etc.
> > ===
> > No where do I find a definition for the type2test() method - other
> > than seeing it as a class variable defined to be None by default.  I
> > looked in unittest.TestCase and did not see it anywhere.
>
> > Am I missing something obvious?  I would appreciate if someone could
> > point me in the right direction.
>
> Use grep ;)
>

I sort of did (use a "find all" from within my editor...)

> CommonTest is not run standalone, it is used as a(n abstract) base class for
> several other tests that override type2test.
>
> E. g. in Lib/test/list_tests.py:
>
> from test import test_support, seq_tests
>
> class CommonTest(seq_tests.CommonTest):
> ...
>
> And then in Lib/test/test_list.py:
>
> from test import test_support, list_tests
>
> class ListTest(list_tests.CommonTest):
>     type2test = list

I can't believe I missed that one.

Thank you very much!

André

> ...
>
> Peter

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


Re: is there a way to collect twitts with python?

2009-04-04 Thread '2+
anyway i found:

http://code.google.com/p/python-twitter/
and
http://mike.verdone.ca/twitter/

and both were easy to install on intrepid .. but didn't work
python-twitter did work by manually downloading:
http://python-twitter.googlecode.com/svn/trunk/twitter.py
well but it seems like i have to follow the guy to get his twit

-- 
SaRiGaMa's Oil Vending Orchestra
is podcasting:
http://sarigama.namaste.jp/podcast/rss.xml
and supplying oil.py for free:
http://oilpy.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


How to free /destroy object created by PyTuple_New

2009-04-04 Thread grbgooglefan

I am using PyTuple_New to pass function arguments to
PyObject_CallObject for execution of a Python function.

How can I free up the memory and object allocated by the PyTuple_New
function?

I am using Python interpreter in my multi-threaded C application & at
load condition my application crashes in Python's evaluation function.
I am not explicitely releasing the PyTuple_New object.

Please guide how can I destory object created by PyTuple_New?

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


Re: "Pythoner",Wish me luck!

2009-04-04 Thread Hendrik van Rooyen
 "barisa"  wrote:

>Hi,
>I'm also begginer in python;
>i did few basic programs about graph etc..
>
>my question is : what benefit is using interactive intrepreter ?
>
>i come from java backround, so I use eclipse for python as well.
>I start my program, it does it's job, and that's it.  (after some
>debugging ofc)
>
The Interactive Interpreter is not intended to be a development
environment, (although you can use it like that for small things)
but it is very handy to do simple tests in when you are not sure
that you understand what some new (to you) language feature
does exactly.  
In this way you can "test bench" small snippets of code, which
makes subsequent debugging of your program less onerous,
and makes it more likely that the "job" your program does is
in fact the "job" that you imagined it should do when you started
to write it.
So, for instance, lets say that it is the first time that you use
the append method of the built in list class, and you are not sure
what it returns.
you have two basic options - you can either go look for the
documentation and RTFM, or you can go into your active 
interpreter and just try it.
The second alternative is often the quickest, and it is definitely
the safest, because what happens is the definitive behaviour
of your installation.
Reading the manual carries the following risks:
- It could be the wrong manual
- The manual and the code may not be congruent

Another reason for using the II is to help you discover stuff.
Calling dir(something) can teach you quite a lot that is of
practical import.

And then there is the help system too.

hth - Hendrik

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


PyFunction_New examples

2009-04-04 Thread Trigve
Hi,
I'm trying to use PyFunction_New() function but I've problem finding out how it
works. What I'm trying to do is to create python function on the fly and then
trying to create function object from if via PyFunction_New.

My problems are similar to this:

http://article.gmane.org/gmane.comp.python.general/548300/match=pyfunction_new

Please CC me.

thanks

Trigve

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


statvfs clearance

2009-04-04 Thread Sreejith K
Python's statvfs module contains the following indexes to use with
os.statvfs() that contains the specified information

statvfs.F_BSIZE
Preferred file system block size.

statvfs.F_FRSIZE
Fundamental file system block size.

statvfs.F_BLOCKS
Total number of blocks in the filesystem.

statvfs.F_BFREE
Total number of free blocks.

statvfs.F_BAVAIL
Free blocks available to non-super user.

statvfs.F_FILES
Total number of file nodes.

statvfs.F_FFREE
Total number of free file nodes.

statvfs.F_FAVAIL
Free nodes available to non-super user.

statvfs.F_FLAG
Flags. System dependent: see statvfs man page.

statvfs.F_NAMEMAX
Maximum file name length.

Can anyone tell me (or give me some links to know) what are these
values ? The first three I know, I need to know about the rest
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hash of None varies per-machine

2009-04-04 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:

On Fri, 03 Apr 2009 10:50:08 -0700, ben.taylor wrote:

>> 2. Should the hash of None vary per-machine? I can't think why you'd
>> write code that would rely on the value of the hash of None, but you
>> might I guess.
>
>The value of hash(None) appears to be the value of id(None), which means 
>it is the memory address that None happens to get, which means it will 
>depend on the precise order that Python allocates things when it starts 
>up, which will vary from platform to platform and version to version.
>
>> 3. Given that presumably not all things can be hashed (since the
>> documentation description of hash() says it gives you the hash of the
>> object "if it can be hashed"), should None be hashable?
>
>Any object can be hashed if it has a working __hash__ method. There's no 
>reason not to have None hashable -- it costs nothing and allows you to 
>use None as a dict key.

So what happens if I try to pickle the dict and keep it for next time?
Will I be able to access whatever I have associated with None?
(directly -  mydict[None], not in a for loop.)
And if I send the pickle to another machine and unpickle it,
what then? - is unpickling smart enough to construct the dict
with the local hash of None?

- Seems to me that if it isn't, and you want to do this, there would 
   have to be a fixed, well known value for the hash of None.

- Hendrik

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


Re: statvfs clearance

2009-04-04 Thread Albert Hopkins
On Sat, 2009-04-04 at 03:56 -0700, Sreejith K wrote:
> Python's statvfs module contains the following indexes to use with
> os.statvfs() that contains the specified information
> 
> statvfs.F_BSIZE
> Preferred file system block size.
> 
> statvfs.F_FRSIZE
> Fundamental file system block size.
> 
> statvfs.F_BLOCKS
> Total number of blocks in the filesystem.
> 
> statvfs.F_BFREE
> Total number of free blocks.
> 
> statvfs.F_BAVAIL
> Free blocks available to non-super user.
> 
> statvfs.F_FILES
> Total number of file nodes.
> 
> statvfs.F_FFREE
> Total number of free file nodes.
> 
> statvfs.F_FAVAIL
> Free nodes available to non-super user.
> 
> statvfs.F_FLAG
> Flags. System dependent: see statvfs man page.
> 
> statvfs.F_NAMEMAX
> Maximum file name length.
> 
> Can anyone tell me (or give me some links to know) what are these
> values ? The first three I know, I need to know about the rest

The values would obviously depend on your particular system, which we
don't have.  So how could we, for example, know how many free blocks you
have on your filesystem?


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


Re: is there a way to collect twitts with python?

2009-04-04 Thread Hendrik van Rooyen
"Dennis Lee Bieber"  wrote:

> Given the subject line -- my first thought was "Depends on the
> density of the twitt population, and how hungry the python is" 

I see that everybody is politically correctly maintaining the 
three "t" twitt spelling, instead of yielding to the obvious
temptation to drop the last one.

Dennis, your reference to "density" comes perilously close...

- Hendrik


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


Re: Undefined symbol PyUnicodeUCS2_DecodeUTF8

2009-04-04 Thread Diez B. Roggisch

Manish Jain schrieb:


Hi all,

I am using Gnome on FreeBSD 7.1. A few days back, my gnome crashed and I 
have had to spend over 4 days recovering my gnome environment. Pretty 
much everything is okay now except for a few python-dependent 
applications (alacarte, for instance), which exit immediately with the 
following error message :



 Traceback (most recent call last):
  File "/usr/local/bin/alacarte", line 22, in 
from Alacarte.MainWindow import MainWindow
  File 
"/usr/local/lib/python2.5/site-packages/Alacarte/MainWindow.py", line 
19, in 

import gtk, gtk.glade, gmenu, gobject, gio
  File 
"/usr/local/lib/python2.5/site-packages/gtk-2.0/gtk/__init__.py", line 
38, in 

import gobject as _gobject
  File 
"/usr/local/lib/python2.5/site-packages/gtk-2.0/gobject/__init__.py", 
line 33, in 
from glib import spawn_async, idle_add, timeout_add, 
timeout_add_seconds, \
  File 
"/usr/local/lib/python2.5/site-packages/gtk-2.0/glib/__init__.py", 
line 30, in 

from glib._glib import *
ImportError: 
/usr/local/lib/python2.5/site-packages/gtk-2.0/glib/_glib.so: 
Undefined symbol "PyUnicodeUCS2_DecodeUTF8"


[1]+  Exit 1  alacarte



I have searched google/yahoo for any help without luck. I have rebuilt 
all python and gtk2 ports from scratch but the error continues.


Can anybody please point out the source and/or remedy for the problem ? 
I am using the python25 port.


Your problem is that your Python interpreter is not compiled with the 
same settings as the binary extensions you use. Python can use UTF16 or 
UTF32 as internal representation for unicode. AFAIK nowadays, 
distributions agreed to use the latter.


The gtk-binding of yours seems to be compiled against an interpreter 
that uses the former.


So you have to either recompile python to match the extensions 
expectations - or the other way round. I'd suggest the latter, as you 
might have a mixture of extensions which some of then won't work with 
the new interpreter.


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


Re: User or UserManager ? Problems of Observer Pattern

2009-04-04 Thread 一首诗
Thanks for your advice.

I studied python from the tutorial and the library manual, and I think
I am familiar enough with Python's grammar and API.  That's why I
never thought I need to read a book of Python.

But if "Programming Python" also explains OO, I would be happy to read
it.
In fact, I am also planning to read again "Head First Object-Oriented
Design and Analysis".
I thought it's time for me to try again to find what is the *point* of
Obejct.

Anyway, this time I will be patient enough.  I won't touch my code
until I am sure find some way to improve it.

On Apr 4, 1:14 pm, Michele Simionato 
wrote:
> On Apr 3, 7:34 pm, 一首诗  wrote:
>
>
>
> > #
> > # Choice 2
> > #
>
> > class UserManager:
>
> > users = []
>
> > @classmethod
> > def delUser(cls, user):
> > cls.users.remove(user)
>
> > RoleManager.onUserDel(user)
>
> > class RoleManager:
>
> > roles = []
>
> > @classmethod
> > def onUserDel(cls, user):
> > for r in cls.roles.items():
> > r.users.remove(user)
>
> Choice #2 is better, but it should not be implemented
> this way. Using a class as a pure container of methods,
> a big singleton, makes little sense, since you would
> be better off with a module and old fashioned procedural
> programming. You recognize this and are worried about this.
> You do not need to be worried to much,
> since there is nothing wrong with procedural design
> (but you should use modules not classes). If you want
> to be more object oriented, the first thing is to understand
> is that you define objects in order to pass them to
> other objects. For instance, you are using a global
> list of users as a class attribute, but I would
> just pass the list in the __init__ method, and
> make it an instance attribute. I also would make
> a RoleManager instance and pass it to the UserManager,
> so that it can be used directly. Or perhaps I would
> define a single UserRoleManager doing all the job.
> It depends.
> But all the point of OOP is to pass objects to other objects.
> It is not bad to think of a data object as of a record
> on steroids. Objects which are purely data and not
> behavior are the simplest and the best objects, start
> from them.
> There are also objects which are mostly behavior
> and nearly no data (the Manager objects here, which
> just act over collections of other objects). Those
> are more difficult to write. OTOH, nobody forces you
> to write the managers as objects. You may find easier
> to write a set of manager functions. This set of
> functions can later become methods of a Manager object,
> if it seems fit, but that must be done a posteriori,
> not a priori.
> Perhaps you should read some book like "Programming Python"
> by Ludz which has many examples of how to write OO applications
> in Python (I mean no offense, but indeed from you examples
> is seems to me that you are missing the point of OOP,
> as you are the first to recognize).
> HTH,
>
>Michele Simionato

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


Re: django model problem

2009-04-04 Thread Dave Angel

Mark wrote:
I think the first thing you need to do is decide if there is going to be 
more than one Musician object. and more than one Album object.  
Presently you are giving all musicians the same first_name and 
last_name.  I suggest you look up the documentation for the special 
method __init__()


Then you need to realize that assigning new attributes to an instance 
object needs to be done inside an instance method, either __init__() or 
some other method with a self parameter.




What you say would normally make sense, but it's Django and it works that
way here. See:
http://docs.djangoproject.com/en/dev/topics/db/models/#fields


Regards
MS

  
Sorry, somehow I missed the subject line.  I have no experience with 
Django, but once I got your message, I read a little of the 
introduction.  Apparently the static fields in a class in models.py are 
treated specially, and describe rows of the database, and the 
relationships between those rows.  Then I guess Django generates the 
necessary instance attributes and methods to make it live.


If I had to guess, I'd say your redundant fields were caused by you 
defining a one-to-one relationship between objects that already had a 
many-to-one relationship.  Presumably there's already a method (or 
attribute) to get a list of albums from musician object.  You might 
better just add a date field to the Album class, and make a method or 
function to sort that list.


Anyway, since I don't have time to actually install and configure Django 
to experiment, I'd suggest you post a query on the django-users mailing 
list, at http://groups.google.com/group/django-users


Sorry I couldn't be more help.
DaveA

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


Re: A design problem I met again and again.

2009-04-04 Thread 一首诗
That's clever.  I never thought of that.  Not only something concrete,
like people, could be class, but a procedure, like a Session, could
also be a Class.

Thanks for you all who replied.  I learned a lot from this thread and
I even made some notes of all your advices because I think I might
review them many times in my future work.

On Apr 4, 12:10 pm, Carl Banks  wrote:
> On Apr 2, 11:25 pm, 一首诗  wrote:
>
>
>
> > Consolidate existing functions?
>
> > I've thought about it.
>
> > For example, I have two functions:
>
> > #=
>
> > def startXXX(id):
> > pass
>
> > def startYYY(id):
> > pass
> > #=
>
> > I could turn it into one:
>
> > #=
> > def start(type, id):
> > if(type == "XXX"):
> > pass
> > else if(type == "YYY"):
> > pass
> > #=
>
> > But isn't the first style more clear for my code's user?
>
> Not necessarily, especially if the user wants to dynamically choose
> which start*** function to call.
>
> I have one more suggestion.  Consider whether there are groups of
> methods that are used together but aren't used with other groups of
> functions.  For instance, maybe there is a group of methods that can
> only be called after a call to startXXX.  If that's the case, you
> might want to separate those groups into different classes.  The
> branched-off class would then act as a sort of session handler.
>
> A piece of user code that looked like this (where sc is an instance of
> your enormous class):
>
> sc.startX()
> sc.send_data_via_X()
> sc.receive_data_via_X()
> sc.stopX()
>
> might look like this after you factor it out:
>
> session = sc.startX()  # creates and returns a new XSession object
> session.send_data()# these are methods of the XSession
> session.receive_data()
> session.stop()
>
> Any methods that are callable any time, you can retain in the big
> class, or put in a base class of all the sessions.
>
> Carl Banks

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


[ANN] Pyro 3.9 released

2009-04-04 Thread Irmen de Jong

Hi,

Pyro 3.9 has been released!

Pyro is a an advanced and powerful Distributed Object Technology system written entirely 
in Python, that is designed to be very easy to use.

Have a look at http://pyro.sourceforge.net for more information.


Highlights of this release are:
- improved compatibility with Jython,
- fixed a deadlock bug in the name server proxy,
- fixed mobile code problem with dependent modules,
- manual improvements
- script tool improvements

As always the detailed changes are in the changes chapter in the manual.
You can download Pyro 3.9 from sourceforge: http://sourceforge.net/projects/pyro

Enjoy,

Irmen de Jong
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread Dikkie Dik
> Anybody have a solution for Windows (XP) Explorer search not finding 
> ordinary text in *.py files? 

This is a known issue. You won't be able to search PHP or even VBScript
files either, as they are not "known" text formats and are therefore
considered "binary, nothing to see here, move along please".

I lost the link I used, but this site seems to have the info also:
http://www.petri.co.il/windows_xp_search_bug.htm

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


Re: Hash of None varies per-machine

2009-04-04 Thread Steven D'Aprano
On Sat, 04 Apr 2009 13:09:06 +0200, Hendrik van Rooyen wrote:

>>Any object can be hashed if it has a working __hash__ method. There's no
>>reason not to have None hashable -- it costs nothing and allows you to
>>use None as a dict key.
> 
> So what happens if I try to pickle the dict and keep it for next time?

You pickle the dict and keep it for next time.

> Will I be able to access whatever I have associated with None?

Yes.

> (directly
> -  mydict[None], not in a for loop.) And if I send the pickle to another
> machine and unpickle it, what then? 

It just works.

> - is unpickling smart enough to
> construct the dict with the local hash of None?

Yes.

> - Seems to me that if it isn't, and you want to do this, there would
>have to be a fixed, well known value for the hash of None.

Seems to me you have misunderstood the way pickling works.

On one machine:

>>> import pickle
>>> pickle.dump({None: "hello world"}, open("pickled", 'w'))

And then on another:

>>> import pickle
>>> pickle.load(open('pickled'))
{None: 'hello world'}

It just works.


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


Re: PEP 382: Namespace Packages

2009-04-04 Thread Martin v. Löwis
> -0
> 
> My main concern is that we'll start seeing all kinds of packages with
> names like:
> 
> com.dusinc.sarray.ptookkit.v_1_34_beta.btree.BTree
> 
> The current lack of global package namespace effectively prevents
> bureaucratic package naming, which in my mind makes it worth the
> cost.  However, I'd be willing to believe this can be kept under
> control some other way.

In principle, people can do this today already. That they are not
doing it is a good sign.

I think this bureaucratic naming in Java originates more from an
explicitly stated policy that people should use such naming than
from the ability to actually do so easily.

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


Re: A design problem I met again and again.

2009-04-04 Thread andrew cooke
Note sure who wrote:
>> > Consolidate existing functions?
>>
>> > I've thought about it.
>>
>> > For example, I have two functions:
>>
>> > #=
>>
>> > def startXXX(id):
>> > pass
>>
>> > def startYYY(id):
>> > pass
>> > #=
>>
>> > I could turn it into one:
>>
>> > #=
>> > def start(type, id):
>> > if(type == "XXX"):
>> > pass
>> > else if(type == "YYY"):
>> > pass
>> > #=

in general, if you are testing type that is an indication you should
refactor to use a base class with subclassing.

for example:

def my_print(x):
  print 'i have a ',
  if type(x) is Foo:
print 'furry foo'
  elif type(x) is Bar:
print 'bubbly Bar;
  else:
print 'strange beast'

might be refactored as

class MyPrintable(object):
  def my_print(self):
print 'i have a ', self.describe()

class Foo(MyPrintable):
  def describe(self):
return 'furry Foo'

etc etc.

it's not always possible, but any type() or isinstance() in an OO program
is a big red flag that the design is wrong.

andrew



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


Re: PEP 382: Namespace Packages

2009-04-04 Thread Martin v. Löwis
Neal Becker wrote:
> While solving this problem, is it possible also to address an issue that 
> shows up in certain distributions?  I'm specifically talking about the fact 
> that on Redhat/Fedora, we have on x86_64 both /usr/lib/pythonxx/ and 
> /usr/lib64/pythonxx.  The former is supposed to be for non-arch specific 
> packages (pure python) and the latter for arch-specific.

I can't see how this is related to this PEP. It's not at all about how
sys.path should be constructed.

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


Re: A design problem I met again and again.

2009-04-04 Thread andrew cooke
andrew cooke wrote:
[...]
>>> > #=
>>> > def start(type, id):
>>> > if(type == "XXX"):
>>> > pass
>>> > else if(type == "YYY"):
>>> > pass
>>> > #=

i just realised i am assuming type is a type of an object, but you might
be using it to mean something else here, in which case case my advice
might be irrelevant (but not necessarily - the value of type might still
depend on an object type in some way, and often does in oo programming).

andrew

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


Re: how to optimize zipimport

2009-04-04 Thread John Machin
On Apr 4, 7:06 pm, "Coonay.appspot"  wrote:
> On Apr 2, 6:26 pm, John Machin  wrote:
[snip]
> > > i found the the module in the zip reloaded  everytime the code is
> > > called,i mean, say ,first time it take me 1 second to call a method in
> > > the zip,but it take another 1 second to call the mothod for another
> > > time ,and so on
>
> > How do you know that it is being reloaded each time a methos is
> > called?

You haven't answered the above question.




> > > > Note: it may help when you reply to show a stripped-down version of
> > > > your calling module, sufficient to back up your description of what is
> > > > happening.
>
> > We can only guess if you don't show us what is actually happening.
> > Vague descriptions are not very useful. Show us how exactly you are
> > importing the modules, how you are calling methods, with timing
> > calls ...

No answer.

[snip]

> > Apart from code executed once at app start to inject the path to the
> > zip file into sys.path, have you made any other changes to accommodate
> > using import from zip? If so, what changes?

No answer.

> > Have you tried running your app from the shell (Windows translation:
> > in a Command Prompt window) like this:
>
> > python -v app_start.py
>
> > This will show you all the imports as they happen.

No answer.

> > HTH ... but a clear description from you (plus code samples) of
> > exactly what you are doing woul dhelp a whole lot more.

No answer.

Conclusion: you don't actually want any help.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-04 Thread Giampaolo Rodola'
On 4 Apr, 04:19, Steven D'Aprano  wrote:
> On Fri, 03 Apr 2009 18:52:52 -0700, Giampaolo Rodola' wrote:
> > If "there should be one-- and preferably only one --obvious way to do
> > it" then my_list.clear() is more obvious than del my_list[:]. Honestly
> > I'm a little surprised that such a topic hasn't been raised before.
>
> I'm a little surprised that you didn't bother googling before making that
> statement. Of course it has been raised before. See (for example) these
> threads:
>
> http://mail.python.org/pipermail/python-dev/2005-July/054564.html
>
> http://mail.python.org/pipermail/python-list/2006-April/549278.html
>
> http://mail.python.org/pipermail/python-list/2006-May/556977.html
>
> http://mail.python.org/pipermail/python-ideas/2007-May/000692.html
>
> The good news is that Python-Ideas seems to be receptive to the idea,
> including some heavy-weights like Raymond Hettinger, which leads me to be
> hopeful that Python-Dev and Guido himself will agree:
>
> http://mail.python.org/pipermail/python-ideas/2009-April/003897.html
>
> Keep your fingers crossed that this is the last time we need to have this
> discussion!
>
> --
> Steven

Sorry, it was 3:52 AM, that's why I didn't bother. =)


--- Giampaolo
http://code.google.com/p/pyftpdlib
--
http://mail.python.org/mailman/listinfo/python-list


Testing dynamic languages

2009-04-04 Thread grkuntzmd
I am a Java developer. There, I said it :-).

When I am writing code, I can  rely on the compiler to confirm that
any methods I write will be called with parameters of the "right"
type. I do not need to test that parameter #1 really is a String
before I call some method on it that only works on Strings.

If I am writing in Python, since it is dynamically, but strongly
typed, I really should check that each parameter is of the expected
type, or at least can respond to the method I plan on calling ("duck"
typing). Every call should be wrapped in a try/except statement to
prevent the method (and program) from crashing when my method is
called with an integer instead of the expected string.

Is this the experience that Python programmer (of large projects) see?
Do you also write unit tests to confirm that the methods actually
check for and catch "bad" parameter types? If I am writing small one-
off scripts, I wouldn't worry about it, but if I am writing a large
system that must have 99+% uptime without constant monitoring, this
really should be verified.

Up for discussion...
--
http://mail.python.org/mailman/listinfo/python-list


Trouble with subprocess.Popen()

2009-04-04 Thread Fernando
Hi,

I'm having a very strange issue with subprocess.Popen.  I'm using it
to call several times an external exe and keep the output in a list.

Every time you call this external exe, it will return a different
string. However, if I call it several times using Popen, it will
always return the SAME string. =:-O  It looks like Popen is returning
always the same value from stdout, without recalling the exe.

This is my code:

def get_key():

from subprocess import Popen, PIPE

args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ]
process = Popen(args, stdout=PIPE)
output = process.communicate()[0].strip()
return output


print get_key() # Returns a certain string
print get_key() # Should return another string, but returns the
same!
-

What on Earth am I doing wrong?!
--
http://mail.python.org/mailman/listinfo/python-list


Re: is there a way to collect twitts with python?

2009-04-04 Thread Dotan Cohen
Python can in fact collect twits:
http://www.johnwoodwardphotography.com/images/snake_girl_promo_13_x_19.jpg
http://www.bennadel.com/resources/uploads/been_busy_at_kinky_solutions.jpg

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread Martin P. Hellwig

[email protected] wrote:


If I am writing in Python, since it is dynamically, but strongly
typed, I really should check that each parameter is of the expected
type, or at least can respond to the method I plan on calling ("duck"
typing). Every call should be wrapped in a try/except statement to
prevent the method (and program) from crashing when my method is
called with an integer instead of the expected string.


Logically speaking, you only need one try/except at the very top of the 
program if you only want to catch these things, but that would be a 
really, really, really bad advice.


I wonder if it wouldn't be better to design the program in such a way 
that the original input is handled in a way that it doesn't conflict 
with what you want to do with.


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


Re: statvfs clearance

2009-04-04 Thread Hrvoje Niksic
Sreejith K  writes:

> Python's statvfs module contains the following indexes to use with
> os.statvfs() that contains the specified information
>
> statvfs.F_BSIZE
> Preferred file system block size.
[...]
> statvfs.F_NAMEMAX
> Maximum file name length.
>
> Can anyone tell me (or give me some links to know) what are these
> values ? The first three I know, I need to know about the rest

You can simply print them, they are integers:

>>> import statvfs
>>> statvfs.F_FLAG
8
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread andrew cooke
[email protected] wrote:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.
>
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.

if you are going to do that, stay with java.  seriously - i too, am a java
developer about half the time, and you can make java pretty dynamic if you
try hard enough.  look at exploiting aspects and functional programming
libraries, for example.

the standard solution to what you describe (which is itself a standard
problem with dynamic languages) is unit testing.  proponents of dynamic
languages argue that you need to do testing anyway for its other
advantages.  proponents of statically typed languages argue that you need
to write more.  the best solution is probably to use a better language
(like ocaml or even haskell) (and i am only half joking).

asserting types isn't really going to work once you start exploiting just
what python can do (although look at abstract base classes - abcs - which
make things easier).

personally, i find that i write slightly more tests in python than java
and that my python code is, to be honest, slightly less reliable.  i also
add type assertions at critical points when refactoring (but otherwise
not).

so in summary:
- yes it's an issue
- solve it with more unit testing, not type assertions
- use the right tool for the job (which might be java)

all the above just my experience.  i tend to use java for the server side
and python for getting data into the database, so each plays to its
strengths.

andrew


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


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread John Machin
On Apr 4, 3:21 pm, John Doe  wrote:
> Anybody have a solution for Windows (XP) Explorer search not finding
> ordinary text in *.py files?
>

Get a grep on yourself!

http://gnuwin32.sourceforge.net/packages/grep.htm

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


Re: Testing dynamic languages

2009-04-04 Thread Emmanuel Surleau
On Saturday 04 April 2009 15:37:44 [email protected] wrote:
> I am a Java developer. There, I said it :-).
>
> When I am writing code, I can  rely on the compiler to confirm that
> any methods I write will be called with parameters of the "right"
> type. I do not need to test that parameter #1 really is a String
> before I call some method on it that only works on Strings.
>
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

Well, it depends on what you're trying to do, really. You do *not* want to 
check parameters in every function. If you are designing a library, it is 
strongly advised to document what kind of parameters your functions 
expect. Otherwise, if your program will handle arbitrary input, you should 
check its format and reject it if it's invalid.

Cheers,

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


Re: Best way to extract from regex in if statement

2009-04-04 Thread Paul McGuire
On Apr 3, 9:26 pm, Paul Rubin  wrote:
> bwgoudey  writes:
> > elif re.match("^DATASET:\s*(.+) ", line):
> >         m=re.match("^DATASET:\s*(.+) ", line)
> >         print m.group(1))
>
> Sometimes I like to make a special class that saves the result:
>
>   class Reg(object):   # illustrative code, not tested
>      def match(self, pattern, line):
>         self.result = re.match(pattern, line)
>         return self.result
>
I took this a little further, *and* lightly tested it too.

Since this idiom makes repeated references to the input line, I added
that to the constructor of the matching class.

By using __call__, I made the created object callable, taking the RE
expression as its lone argument and returning a boolean indicating
match success or failure.  The result of the re.match call is saved in
self.matchresult.

By using __getattr__, the created object proxies for the results of
the re.match call.

I think the resulting code looks pretty close to the original C or
Perl idiom of cascading "elif (c=re_expr_match("..."))" blocks.

(I thought about cacheing previously seen REs, or adding support for
compiled REs instead of just strings - after all, this idiom usually
occurs in a loop while iterating of some large body of text.  It turns
out that the re module already caches previously compiled REs, so I
left my cacheing out in favor of that already being done in the std
lib.)

-- Paul

import re

class REmatcher(object):
def __init__(self,sourceline):
self.line = sourceline
def __call__(self, regexp):
self.matchresult = re.match(regexp, self.line)
self.success = self.matchresult is not None
return self.success
def __getattr__(self, attr):
return getattr(self.matchresult, attr)


This test:

test = """\
ABC
123
xyzzy
Holy Hand Grenade
Take the pebble from my hand, Grasshopper
"""

outfmt = "'%s' is %s [%s]"
for line in test.splitlines():
matchexpr = REmatcher(line)
if matchexpr(r"\d+$"):
print outfmt % (line, "numeric", matchexpr.group())
elif matchexpr(r"[a-z]+$"):
print outfmt % (line, "lowercase", matchexpr.group())
elif matchexpr(r"[A-Z]+$"):
print outfmt % (line, "uppercase", matchexpr.group())
elif matchexpr(r"([A-Z][a-z]*)(\s[A-Z][a-z]*)*$"):
print outfmt % (line, "a proper word or phrase",
matchexpr.group())
else:
print outfmt % (line, "something completely different", "...")

Produces:
'ABC' is uppercase [ABC]
'123' is numeric [123]
'xyzzy' is lowercase [xyzzy]
'Holy Hand Grenade' is a proper word or phrase [Holy Hand Grenade]
'Take the pebble from my hand, Grasshopper' is something completely
different [...]
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to free /destroy object created by PyTuple_New

2009-04-04 Thread Andrew Svetlov
To destroy every python object you need to call Py_DECREF.
To call python code fron you C thread you need to use pair
PyGILState_Ensure/PyGILState_Release.
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 4, 12:58 am, Lawrence D'Oliveiro  wrote:
> In message <8bc55c05-19da-41c4-
>
> [email protected]>, gert wrote:
> >     with open('com1', 'r') as f:
> >         for line in f:
> >              print('line')
>
> Why bother, why not just
>
>     for line in open('com1', 'r') :
>         print line

Interesting :)
So its does the same thing as with right ?
Automatic closing and finalizing stuff.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread andrew cooke
andrew cooke wrote:
> if you are going to do that, stay with java.  seriously - i too, am a java
> developer about half the time, and you can make java pretty dynamic if you
> try hard enough.  look at exploiting aspects and functional programming
> libraries, for example.

also, of course, scala.  andrew

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


Re: Testing dynamic languages

2009-04-04 Thread Luis Gonzalez
On Apr 4, 11:17 am, Emmanuel Surleau 
wrote:
> On Saturday 04 April 2009 15:37:44 [email protected] wrote:
>
> > I am a Java developer. There, I said it :-).

Don't worry. I also do terrible things to support my family...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread [email protected]
On Apr 4, 12:21 am, John Doe  wrote:
> Anybody have a solution for Windows (XP) Explorer search not finding
> ordinary text in *.py files?
>
> Thanks.

Googling turns up this.
http://www.pcmag.com/article2/0,4149,1206399,00.asp

I haven't tried it myself.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-04 Thread Paul McGuire
On Apr 3, 11:48 pm, Tim Wintle  wrote:
> del mylist[:]
> * or *
> mylist[:] = []
> * or *
> mylist = []
>
> which, although semantically similar are different as far as the
> interpreter are concerned (since two of them create a new list):
>

Only the last item creates a new list of any consequence.  The first
two retain the original list and delete or discard the items in it.  A
temporary list gets created in the 2nd option, and is then used to
assign new contents to mylist's [:] slice - so yes, technically, a new
list *is* created in the case of this option. But mylist does not get
bound to it as in the 3rd case.  In case 2, mylist's binding is
unchanged, and the temporary list gets GC'ed almost immediately.

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 3, 10:10 pm, Christian Heimes  wrote:
> gert wrote:
> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.
>
> So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.

With all respect but why do people in general avoid the question when
they do not know something?
I appreciate the answer and its a valid solution, never the less
useless in the answer I seek.

I hope I did not offend anybody. When you want to do something about
the future, you have to take the hard way, so others can take the easy
way. If somebody is stuck going the hard way, to clear it for others,
you can not expect them to be satisfied with a easy answer.

Sorry.

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


Re: statvfs clearance

2009-04-04 Thread Albert Hopkins
On Sat, 2009-04-04 at 15:48 +0200, Hrvoje Niksic wrote:
> Sreejith K  writes:
> 
> > Python's statvfs module contains the following indexes to use with
> > os.statvfs() that contains the specified information
> >
> > statvfs.F_BSIZE
> > Preferred file system block size.
> [...]
> > statvfs.F_NAMEMAX
> > Maximum file name length.
> >
> > Can anyone tell me (or give me some links to know) what are these
> > values ? The first three I know, I need to know about the rest
> 
> You can simply print them, they are integers:
> 
> >>> import statvfs
> >>> statvfs.F_FLAG
> 8
> --

Oh, did the OP mean the values of the indices?  Yeah, of course you can
just print them.  Or even look at statvfs.py.  It's a whopping 15 lines:

"""Constants for interpreting the results of os.statvfs() and
os.fstatvfs().""" 

# Indices for statvfs struct members in the tuple returned by
# os.statvfs() and os.fstatvfs().

F_BSIZE   = 0   # Preferred file system block size
F_FRSIZE  = 1   # Fundamental file system block size
F_BLOCKS  = 2   # Total number of file system blocks (FRSIZE)
F_BFREE   = 3   # Total number of free blocks
F_BAVAIL  = 4   # Free blocks available to non-superuser
F_FILES   = 5   # Total number of file nodes
F_FFREE   = 6   # Total number of free file nodes
F_FAVAIL  = 7   # Free nodes available to non-superuser
F_FLAG= 8   # Flags (see your local statvfs man page)
F_NAMEMAX = 9   # Maximum file name length


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


Re: python needs leaning stuff from other language

2009-04-04 Thread Zamnedix
On Apr 3, 8:48 am, Steven D'Aprano  wrote:
> On Fri, 03 Apr 2009 08:23:22 -0700, Zamnedix wrote:
> > On Apr 2, 3:25 pm, [email protected] wrote:
> >> python's list needs a thing  list.clear()  like c# arraylist and
> >> python needs a writeline() method
>
> > Please don't post things like list before you do any research. You don't
> > know what you are talking about.
>
> The original poster may or may not know what he is talking about, but
> adding a clear() method to lists seems to be very much in demand. I'd
> vote Yes for one.
>
> Besides, this news group is for people to ask questions about Python,
> even stupid questions. It's not just for experts only.
>
> --
> Steven

Sorry. It was inappropriate. I just get a little mad at people who
don't even ATTEMPT to speak proper English. And then they go on
bashing our language without any sort of context.
--
http://mail.python.org/mailman/listinfo/python-list


Re: statvfs clearance

2009-04-04 Thread Dave Angel



Hrvoje Niksic wrote:

Sreejith K  writes:

  

Python's statvfs module contains the following indexes to use with
os.statvfs() that contains the specified information

statvfs.F_BSIZE
Preferred file system block size.


[...]
  

statvfs.F_NAMEMAX
Maximum file name length.

Can anyone tell me (or give me some links to know) what are these
values ? The first three I know, I need to know about the rest



  

The following web page describes them:
   http://docs.python.org/library/statvfs.html
but you already knew that much.  So what are you really asking for?

You can simply print them, they are integers:

  

import statvfs
statvfs.F_FLAG


8

  
But those values may be specific to a particular python implementation.  
No reason to assume they'd be the same across OS platforms, or between 
versions 2.5 and 2.6.  The whole thing is deprecated, and is eliminated 
in 3.0


The term we used to use for these is "magic numbers."   Using 
magic-numbers directly in your code is a good way to ensure future time 
debugging.


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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Kushal Kumaran
On Fri, 03 Apr 2009 22:10:36 +0200
Christian Heimes  wrote:

> gert wrote:
> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.
> 
> So don't use Python 3.0. Most people are still using Python 2.5 or
> 2.6.
> 

Alternatively, you could look into the pySerial source and find out
what it does.

-- 
kushal

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


Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread grocery_stocker
Given the following

[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def counter():
...   mylist = range(3)
...   for i in mylist:
...  yield i*i
...
>>> counter

>>> gen = counter()
>>> gen

>>> while True:
...i = gen.next()
...print i
...
0
1
4
Traceback (most recent call last):
  File "", line 2, in ?
StopIteration


I thought the 'for' in counter() was supposed to catch StopIteration.
Ie, I thought that something like

...   for i in mylist:
...  yield i*i

Got translated to something like
>>> try:
...while True:
...   do some stuff
... except StopIteration:
...pass
...

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


lxml and xslt extensions

2009-04-04 Thread dasacc22
Hi,

Im not sure where else to ask this. But basically Im having trouble
figuring out how to successfully apply multiple extensions in a single
transformation. So for example if i have







in my xsl and my xslt extension looks like

class TagExtension(etree.XSLTExtension):
  def execute( ..., output_parent):
print 'executing tag_extension'
tag = etree.Element('p')
tag.text = 'Hello'
output_parent.append(tag)

well then the transformation works for the first tag and appends it to
the root of the created doc but all subsequent calls dont append
(maybe b/c output_parent is now somewhere else for return?). And to
clarify, I know that its the first call that completes and all
subsequent calls fail b/c i have a subsequent call that performs a
different transformation.

Thanks for any help or hints,
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread Dave Angel

grocery_stocker wrote:

Given the following

[cdal...@localhost ~]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
  

def counter():


...   mylist = range(3)
...   for i in mylist:
...  yield i*i
...
  

counter



  

gen = counter()
gen



  

while True:


...i = gen.next()
...print i
...
0
1
4
Traceback (most recent call last):
  File "", line 2, in ?
StopIteration


I thought the 'for' in counter() was supposed to catch StopIteration.
Ie, I thought that something like

...   for i in mylist:
...  yield i*i

Got translated to something like
  

try:


...while True:
...   do some stuff
... except StopIteration:
...pass
...


  
There are two separate StopIteration's here.  The for statement you 
describe will indeed catch the StopIteration from the list's iterator.


But that for statement is inside a generator function, and the generator 
function throws a StopIteration when it returns (as opposed to when it 
yields).  If you had used that generator inside another for statement, 
it would have worked as you expect.  But when you call nest() 
explicitly, you have to be prepared for the exception.  Clearly, the 
while True loop cannot go forever, when your generator is finite.



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


Re: Why doesn't StopIteration get caught in the following code?

2009-04-04 Thread andrew cooke
grocery_stocker wrote:
 while True:
> ...i = gen.next()
> ...print i
> ...
> 0
> 1
> 4

python's magic isn't as magic as you hope.

roughly speaking, it only does the necessary rewriting (writing the
equivalent code with next etc etc) when you define a function or a method
that contains "yield".  the above doesn't, so it's not rewritten and
there's no magic.

more exactly:
http://docs.python.org/reference/datamodel.html#index-1747

andrew


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


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread Dave Angel

John Doe wrote:

Tim Golden  wrote:
 
Now I think about it, try searching for "xplorer2" since I think I 
mentioned that I have used that instead of explorer for some while. 


Yeah... at least by the time I move from Windows XP to Windows 7, very 
likely I will be using a different file manager. If I cannot

search Python files, now might be a good time to switch. Thanks for
the search criteria, I will look for that thread.
  
The original thread is at
http://mail.python.org/pipermail/tutor/2009-January/066765.html


and the product xplorer2 is athttp://zabkat.com/
Std version is $30, but there's a free version also.

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


Re: lxml and xslt extensions

2009-04-04 Thread dasacc22
On Apr 4, 11:31 am, dasacc22  wrote:
> Hi,
>
> Im not sure where else to ask this. But basically Im having trouble
> figuring out how to successfully apply multiple extensions in a single
> transformation. So for example if i have
> 
> 
> 
> 
> 
> 
>
> in my xsl and my xslt extension looks like
>
> class TagExtension(etree.XSLTExtension):
>   def execute( ..., output_parent):
>     print 'executing tag_extension'
>     tag = etree.Element('p')
>     tag.text = 'Hello'
>     output_parent.append(tag)
>
> well then the transformation works for the first tag and appends it to
> the root of the created doc but all subsequent calls dont append
> (maybe b/c output_parent is now somewhere else for return?). And to
> clarify, I know that its the first call that completes and all
> subsequent calls fail b/c i have a subsequent call that performs a
> different transformation.
>
> Thanks for any help or hints,
> Daniel

Oh well I found the culprit, etree.tostring seems to cut it off after
the first transformation, simply doing a

$> print result

displays the entire document. To make use of the keyword options
xml_declaration, pretty_print, encoding, I tried using the .write
method of result to a StringIO but it produces the same clipped
result. Guess Ill have to edit the .docinfo attributes on the result
and return the string
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hash of None varies per-machine

2009-04-04 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:


>Seems to me you have misunderstood the way pickling works.

Yeah right - have you ever looked at the pickle code?

Good to hear it "just works"

:-)

- Hendrik

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


Re: is there a way to collect twitts with python?

2009-04-04 Thread Bradley Wright
Just to pimp my own wares:

http://github.com/bradleywright/yatcip/tree/master

A Python Twitter client.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread Francesco Bochicchio
On Sat, 04 Apr 2009 07:37:44 -0700, grkuntzmd wrote:

> I am a Java developer. There, I said it :-).
> 
> When I am writing code, I can  rely on the compiler to confirm that
> any methods I write will be called with parameters of the "right"
> type. I do not need to test that parameter #1 really is a String
> before I call some method on it that only works on Strings.
> 
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.
> 
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.
> 
> Up for discussion...

Uhm. 
I write large bodies of code for living ... not in Python, unfortunately.
I usually divide my code in two classes wrt sanity checks : inner code and
boundary code. Boundary code gets paranoic checks on everything:
arguments, consistency etc ... also with static typing : an 'int'
parameter declaration in C/C++ make sure that your function gets an
integer, but ensure nothing in the way of minimum and maximum value, so
before using it - say - as an array index, it is better to check
that. Inner code gets less checks, based on the assumptions that inputs
have been properly checked by the boundary functions.

This method is not without risks - an architectural change can move a 
function from an inner zone to a boundary zone, and I may forget to
'fortify' the function. However, this is a guideline that served me well.

Beside that there is another guideline I apply to languages like java and
python - programs in these languages do not 'crash' ... they throw
exceptions. Now, supposing to add an input check  : what are you
going to do if you find bad data? In the answer is - as often the case -
throw an exception, then maybe the check is not worth much ...

There are exceptions to this guideline, as always, like if you want to
generate a more meaningful exception, but this is another guideline I
tend to follow. And this means that my level of checking in python is 
much lower than in - say - C++. And I don't worry too much about argument
types, more about external inputs with the right 'semantic'.

The one coding behaviour that dynamic types forced me to change, is that
now I tend to build programs more incrementally, because catching typos
error and logic errors at the same time on a large body of code can be
frustrating and not very productive ... but I find myself to use now the
same approach also when I code in statically typed languages : a bit
slower at beginning, but tend to procuce more reliable results .

Ciao

FB


 
 
 

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


Re: Testing dynamic languages

2009-04-04 Thread Tim Wintle
On Sat, 2009-04-04 at 06:37 -0700, [email protected] wrote:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

At some point you should wrap it in a try/except block - but only at the
point where you want the exception to be handled. That will normally be
quite far up, and you'll just let the exception travel back up to that
point.


for example, in a web server type of thing you might have something
vaguely like


def main:
  for request in request_itter:
try:
  headers = request.get_headers()
  dispatch = get_dispatch_fn(headers)
  response = dispatch(response)
except:
  send_500()

You probably then don't need to catch any exceptions in the get_headers,
or actual processing methods (unless you are writing to sql or
something, when you might want to wrap all statements in a try block,
and then put a "ROLLBACK;" query in the except block (and then raise the
caught exception so it goes back the the block above)

> 
> Is this the experience that Python programmer (of large projects) see?
> Do you also write unit tests to confirm that the methods actually
> check for and catch "bad" parameter types? If I am writing small one-
> off scripts, I wouldn't worry about it, but if I am writing a large
> system that must have 99+% uptime without constant monitoring, this
> really should be verified.

I write large applications with a target of 99.9% uptime, and I don't
find it a problem. occasionally I have to check parameters, but that's
not very often

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

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


Re: python needs leaning stuff from other language

2009-04-04 Thread Tim Wintle
On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:
> 
> Let's be clear: python-ideas seems positive on the idea of adding a .clear() 
> method. *Completely removing* slice assignment has not been broached there.

Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments

> 
> > (I didn't expect such strong responses btw!)
> 
> You are proposing the removal of a general, orthogonal feature (and breaking 
> code in consequence!) just because of a new syntax for a single special case 
> of 
> that feature. That is quite simply ridiculous.

Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.

> 
> .clear() would be non-orthogonal syntactic sugar. That's okay! Python has 
> syntactic sugar in a number of other places, too! Appropriate doses of 
> syntactic 
> sugar and non-orthogonality are precisely what lets you implement "There 
> should 
> be one-- and preferably only one --obvious way to do it." The really key word 
> in 
> that sentence is "obvious", not "one".
> 
> FWIW, removing slice assignment would be a gross form of non-orthogonality, 
> too. 
> __getitem__, __setitem__ and __delitem__ should all be able to accept the 
> same 
> indices (or else raise exceptions in the case of immutability).

hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread gert
On Apr 4, 5:20 pm, Kushal Kumaran  wrote:
> On Fri, 03 Apr 2009 22:10:36 +0200
>
> Christian Heimes  wrote:
> > gert wrote:
> > > I do understand, and I went looking into pySerial, but it is a long
> > > way from getting compatible with python3.x and involves other libs
> > > that are big and non pyhton3.x compatible.
>
> > So don't use Python 3.0. Most people are still using Python 2.5 or
> > 2.6.
>
> Alternatively, you could look into the pySerial source and find out
> what it does.

I think pywin32 is the way they do the things I want. Witch is not
python3 ready and way to much work around to do it clean. Using ctypes
is a option but you have to really know what you are doing and what
you are looking for.

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


Re: Testing dynamic languages

2009-04-04 Thread grkuntzmd
This may be obvious but, clearly there are (at least) two general
types of errors: those caused by data external to the program and
those caused by bugs in the program. For all inputs coming into the
program from outside, such as user inputs and data coming over a
network, the inputs must be completely checked -- always assume that
they will be incorrect and are intended to crash your code -- be
pleasantly surprised when they are not :-). Check for all bad inputs.

If the data are from inside the program, the assumption may be that
they are good and if not, it was a bug. I suppose you can write unit
tests on each routine to see that the methods that routine calls are
with valid arguments (using mocks). I actually tried this in a Java
program using JMockit; it was tedious, but it did catch a few
"potential" bugs. I would love to say that I ALWAYS remember the input
and output condition of every subroutine I write, but I just finished
a new feature for a company project that involved 100+ routines and
classes and I admit that I don't always remember which ones can return
null and which always return empty arrays, for example, even though I
try to write JavaDocs at the top of each routine. By mocking these
routines, I can check that the caller always handles each case
gracefully.
--
http://mail.python.org/mailman/listinfo/python-list


Re: django model problem

2009-04-04 Thread Mark
> 
> Anyway, since I don't have time to actually install and configure Django 
> to experiment, I'd suggest you post a query on the django-users mailing 
> list, at http://groups.google.com/group/django-users
 
Yes, that's what I did - it seems my problem is either a tough one, or it's
just impossible to do what I want. 
Anyway great thanks for your interest and help!

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


Re: Hash of None varies per-machine

2009-04-04 Thread Peter Pearson
On 03 Apr 2009 10:57:05 -0700, Paul Rubin  wrote:
> [email protected] writes:
>> 1. Is it correct that if you hash two things that are not equal they
>> might give you the same hash value?
>
> Yes, hashes are 32 bit numbers and there are far more than 2**32
> possible Python values (think of long ints), so obviously there must
> be multiple values that hash to the same slot.

For example, on this machine:

Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) 
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

 hash( "latox" ) == hash( "uzyky" )
True

YMMV.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread Gabriel Genellina

En Sat, 04 Apr 2009 11:29:22 -0300, gert  escribió:


On Apr 4, 12:58 am, Lawrence D'Oliveiro  wrote:

In message <8bc55c05-19da-41c4-

[email protected]>, gert wrote:
>     with open('com1', 'r') as f:
>         for line in f:
>              print('line')

Why bother, why not just

    for line in open('com1', 'r') :
        print line


Interesting :)
So its does the same thing as with right ?
Automatic closing and finalizing stuff.


No, it does not. Either use `with` o a `try...finally` block.

--
Gabriel Genellina

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


Best Compatible JS Lib for Django

2009-04-04 Thread ntwrkd
Does anyone have experience with using JS Libraries with Django?
Do some work better than others and are easier to code with?

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


Re: dict view to list

2009-04-04 Thread Aahz
In article <6b4065b0-6af7-4aff-8023-40e5d521f...@v19g2000yqn.googlegroups.com>,
Luis Gonzalez   wrote:
>
>Yes, I know the python approach is to use built-ins.
>But wouldn't it be cool if we could do mydict.values().tolist()
>instead?
>It would be more regular and intuitive and readable from an OO point
>of view.
>In my oppinion, this would be cleaner.
>Built-ins used like this look like an early decission made when
>designing an imperative language.

What kind of language do you think Python is?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."  --Brian W. Kernighan
--
http://mail.python.org/mailman/listinfo/python-list


Generators/iterators, Pythonicity, and primes

2009-04-04 Thread John Posner
Inspired by recent threads (and recalling my first message to Python
edu-sig), I did some Internet searching on producing prime numbers using
Python generators. Most algorithms I found don't go for the infinite,
contenting themselves with "list all the primes below a given number".

Here's a very Pythonic (IMHO) implementation that keeps going and going and
going ...:

from itertools import count
from math import sqrt

def prime_gen():
"""
Generate all prime numbers
"""
primes = []
for n in count(2):
if all(n%p for p in primes if p < sqrt(n)):
primes.append(n)
yield n

The use of all() is particularly nifty (see
http://code.activestate.com/recipes/576640/). And so is the way in which the
list comprehension easily incorporates the sqrt(n) optimization.

Question: Is there a way to implement this algorithm using generator
expressions only -- no "yield" statements allowed?

BTW -- thank you, John Machin, for the spanking ('I'd worry about "correct"
before "Pythonic"') in a previous message. I *did* manage to post a
correction to the needless conversion of a string to a list:

   b in list("\r\n\t")

... a few hours before your message arrived (Wed Apr 1 19:44:01 CEST 2009)!





E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: lxml and xslt extensions

2009-04-04 Thread Stefan Behnel
Hi,

dasacc22 wrote:
> On Apr 4, 11:31 am, dasacc22 wrote:
>> Im not sure where else to ask this.

The best place to ask is the lxml mailing list:

http://codespeak.net/mailman/listinfo/lxml-dev


>> But basically Im having trouble
>> figuring out how to successfully apply multiple extensions in a single
>> transformation. So for example if i have
>> 
>> 
>> 
>> 
>> 
>> 
>>
>> in my xsl and my xslt extension looks like
>>
>> class TagExtension(etree.XSLTExtension):
>>   def execute( ..., output_parent):
>> print 'executing tag_extension'
>> tag = etree.Element('p')
>> tag.text = 'Hello'
>> output_parent.append(tag)
>>
>> well then the transformation works for the first tag and appends it to
>> the root of the created doc but all subsequent calls dont append
>> (maybe b/c output_parent is now somewhere else for return?). And to
>> clarify, I know that its the first call that completes and all
>> subsequent calls fail b/c i have a subsequent call that performs a
>> different transformation.
> 
> Oh well I found the culprit, etree.tostring seems to cut it off after
> the first transformation,

Not sure what you mean here. Could you post your question on the lxml
mailing list and add a runnable example that shows the behaviour?


> simply doing a
> 
> $> print result
> 
> displays the entire document. To make use of the keyword options
> xml_declaration, pretty_print, encoding, I tried using the .write
> method of result to a StringIO but it produces the same clipped
> result. Guess Ill have to edit the .docinfo attributes on the result
> and return the string

.docinfo is basically read-only. The result of the XSLT is serialised as
requested by the xsl:output element in the stylesheet.

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


Can't one collect twitts and twits in any language?

2009-04-04 Thread Casey Hawthorne
:)
--
Regards,
Casey
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cannot find text in *.py files with Windows Explorer?

2009-04-04 Thread John Doe
Dave Angel  wrote:
> John Doe wrote:

>> ...at least by the time I move from Windows XP to Windows 7,
>> very likely I will be using a different file manager. If I cannot
>> search Python files, now might be a good time to switch.

> and the product xplorer2 is athttp://zabkat.com/
> Std version is $30, but there's a free version also.

The free version uses Windows Explorer search, therefore it will not
find text in *.py files. Same with Ultra Explorer.

Another file manager, FreeCommander, does find text in Python files.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread Mark Tolonen


"John Posner"  wrote in message 
news:af9fbcc3a7624599a6f51bad2397e...@amdup...

Inspired by recent threads (and recalling my first message to Python
edu-sig), I did some Internet searching on producing prime numbers using
Python generators. Most algorithms I found don't go for the infinite,
contenting themselves with "list all the primes below a given number".

Here's a very Pythonic (IMHO) implementation that keeps going and going 
and

going ...:

from itertools import count
from math import sqrt

def prime_gen():
   """
   Generate all prime numbers
   """
   primes = []
   for n in count(2):
   if all(n%p for p in primes if p < sqrt(n)):
   primes.append(n)
   yield n


p <= sqrt(n) works a little better :^)

-Mark


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


Re: python needs leaning stuff from other language

2009-04-04 Thread Diez B. Roggisch

Tim Wintle schrieb:

On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:
Let's be clear: python-ideas seems positive on the idea of adding a .clear() 
method. *Completely removing* slice assignment has not been broached there.


Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments


(I didn't expect such strong responses btw!)
You are proposing the removal of a general, orthogonal feature (and breaking 
code in consequence!) just because of a new syntax for a single special case of 
that feature. That is quite simply ridiculous.


Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.

.clear() would be non-orthogonal syntactic sugar. That's okay! Python has 
syntactic sugar in a number of other places, too! Appropriate doses of syntactic 
sugar and non-orthogonality are precisely what lets you implement "There should 
be one-- and preferably only one --obvious way to do it." The really key word in 
that sentence is "obvious", not "one".


FWIW, removing slice assignment would be a gross form of non-orthogonality, too. 
__getitem__, __setitem__ and __delitem__ should all be able to accept the same 
indices (or else raise exceptions in the case of immutability).


hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal


>>> l = range(10)
>>> l[3:7] = range(4)
>>> l
[0, 1, 2, 0, 1, 2, 3, 7, 8, 9]

How do you want to do that with clear?

That l[:] = [] clears a list is more of an "accident" than the intent of 
slice-assignment. Removing it in favor of clear() would remove an 
orthogonal feature of updating parts of a list with another iterable.


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


Re: Best Compatible JS Lib for Django

2009-04-04 Thread Daniel Fetchinson
> Does anyone have experience with using JS Libraries with Django?
> Do some work better than others and are easier to code with?

You might want to ask this on the django list.

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


RE: Generators/iterators, Pythonicity, and primes

2009-04-04 Thread John Posner
Mark Tolonen said:

 >> p <= sqrt(n) works a little better :^)
 >> 
 >> -Mark
 >> 

Right you are -- I found that bug in my last-minute check, and then I forgot
to trannscribe the fix into the email message. Duh -- thanks!

-John 






E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing dynamic languages

2009-04-04 Thread bearophileHUGS
grkunt...:
> If I am writing in Python, since it is dynamically, but strongly
> typed, I really should check that each parameter is of the expected
> type, or at least can respond to the method I plan on calling ("duck"
> typing). Every call should be wrapped in a try/except statement to
> prevent the method (and program) from crashing when my method is
> called with an integer instead of the expected string.

Others have already given you most of the answers (summary: don't do
that. Don't fight the language. Use doctests). My other suggestion is
to read code coming from 5+ Python programs written by other
(different) people. You will see how to use Python.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread Diez B. Roggisch

gert schrieb:

On Apr 3, 10:10 pm, Christian Heimes  wrote:

gert wrote:

I do understand, and I went looking into pySerial, but it is a long
way from getting compatible with python3.x and involves other libs
that are big and non pyhton3.x compatible.

So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.


With all respect but why do people in general avoid the question when
they do not know something?
I appreciate the answer and its a valid solution, never the less
useless in the answer I seek.

I hope I did not offend anybody. When you want to do something about
the future, you have to take the hard way, so others can take the easy
way. If somebody is stuck going the hard way, to clear it for others,
you can not expect them to be satisfied with a easy answer.


But your path is clearly *not* the future. It would be fixing win32 and 
pyserial, if anything.


And the suggestion to change the set of tools if there is no reason to 
stick to the ones you use now certainly is a valid answer. Especially if 
they do know that these solutions work.


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


Re: python needs leaning stuff from other language

2009-04-04 Thread Robert Kern

On 2009-04-04 12:07, Tim Wintle wrote:

On Sat, 2009-04-04 at 02:03 -0500, Robert Kern wrote:

Let's be clear: python-ideas seems positive on the idea of adding a .clear()
method. *Completely removing* slice assignment has not been broached there.


Yup, sorry - I did mean to refer to the initial suggestion, rather than
my comments


(I didn't expect such strong responses btw!)

You are proposing the removal of a general, orthogonal feature (and breaking
code in consequence!) just because of a new syntax for a single special case of
that feature. That is quite simply ridiculous.


Ok, I may have come across a little strongly (was very tired) - I'm not
_actually_ saying we should remove it, I'm just pointing out why
adding .clear() to lists seems to be unnecessary and slightly messy. The
suggested removal of assignments to slices is a theoretical statement.


But can you see why your wording might lead the rest of us to believe otherwise? 
 :-)



.clear() would be non-orthogonal syntactic sugar. That's okay! Python has
syntactic sugar in a number of other places, too! Appropriate doses of syntactic
sugar and non-orthogonality are precisely what lets you implement "There should
be one-- and preferably only one --obvious way to do it." The really key word in
that sentence is "obvious", not "one".

FWIW, removing slice assignment would be a gross form of non-orthogonality, too.
__getitem__, __setitem__ and __delitem__ should all be able to accept the same
indices (or else raise exceptions in the case of immutability).


hummm - I'm sure it would be confusing behaviour if it was not
available, but I'm not sure how it would be non-orthogonal


I might be abusing the term, but to me, orthogonality doesn't just mean avoiding 
overlapping functionality. It also means not putting in special-case limitations 
for otherwise general features. It would be odd if you could use integer indices 
for __getitem__, __setitem__ and __delitem__, but slice indices would work for 
__getitem__ and not the others.


--
Robert Kern

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

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


Re: with open('com1', 'r') as f:

2009-04-04 Thread Christian Heimes
gert wrote:
> On Apr 3, 10:10 pm, Christian Heimes  wrote:
>> gert wrote:
>>> I do understand, and I went looking into pySerial, but it is a long
>>> way from getting compatible with python3.x and involves other libs
>>> that are big and non pyhton3.x compatible.
>> So don't use Python 3.0. Most people are still using Python 2.5 or 2.6.
> 
> With all respect but why do people in general avoid the question when
> they do not know something?
> I appreciate the answer and its a valid solution, never the less
> useless in the answer I seek.

You are missing some background information. :)
I've spent a considerable amount of time with the design and development
of Python 3.0. I don't mention the fact in order to show off. I just
wanna explain to you that my suggestion has a solid background.

You are going throw a lot of unnecessary pain and suffering. Python 3.0
is for people, who like to play with cutting edge software and for
library developers, that port their code to 3.0. I appreciate your hard
work but it's really the wrong way. If you like to offer your help then
help the developers of pyserial. Please don't try to come by with a
hacky approach as using the old MS DOS magic files.

Christian

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


Re: is there a way to collect twitts with python?

2009-04-04 Thread '2+
nice info, thanx
that
# stalk my stalkers
example look smart
i won't use that one if it was for this ml ;D

On Sun, Apr 5, 2009 at 1:22 AM, Bradley Wright  wrote:
> Just to pimp my own wares:
>
> http://github.com/bradleywright/yatcip/tree/master
>
> A Python Twitter client.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

-- 
SaRiGaMa's Oil Vending Orchestra
is podcasting:
http://sarigama.namaste.jp/podcast/rss.xml
and supplying oil.py for free:
http://oilpy.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: with open('com1', 'r') as f:

2009-04-04 Thread Gabriel Genellina

En Sat, 04 Apr 2009 14:11:12 -0300, gert  escribió:


On Apr 4, 5:20 pm, Kushal Kumaran  wrote:

On Fri, 03 Apr 2009 22:10:36 +0200
Christian Heimes  wrote:
> gert wrote:



> > I do understand, and I went looking into pySerial, but it is a long
> > way from getting compatible with python3.x and involves other libs
> > that are big and non pyhton3.x compatible.

> So don't use Python 3.0. Most people are still using Python 2.5 or
> 2.6.

Alternatively, you could look into the pySerial source and find out
what it does.


I think pywin32 is the way they do the things I want. Witch is not
python3 ready and way to much work around to do it clean. Using ctypes
is a option but you have to really know what you are doing and what
you are looking for.


The last pywin32 release (213) does work with Python 3.
If you can wait a few days, I'm working on a proper port of pyserial.  
Preliminary testing shows it's working fine on Windows. Basically, I've  
modified the read/write methods to use bytes instead of str, and 2to3 did  
the rest:


Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit  
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
p3> import serial
p3> ser = serial.Serial(2)
p3> ser.write(b"ATI7\r\n")
p3> for line in ser: print(line.rstrip().decode("ascii","replace"))
...
ATI7

Configuration Profile...

Product type   US/Canada Internal
OptionsV32bis,V.FC,V.34+
Fax OptionsClass 1/Class 2.0
Clock Freq 92.0Mhz
Line Options   Caller ID,Distinctive Ring
Voice Options  Speakerphone,TAD
Eprom  256k
Ram64k

EPROM date 5/13/96
DSP date   5/13/96

EPROM rev  2.0
DSP rev2.0

OK
^C

--
Gabriel Genellina

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


Creating a session in windows to auth to remote machines

2009-04-04 Thread ericwoodworth
Hi,
 I'm trying to auth to remote machines so I can plunder WMI to get
logs and settings and the like.  My script works for most of my
machines because they're all in the same domain and I run the script
as somebody who has enough access to get at this stuff but for
machines off the domain I'm stuck.

 Now I'm primarily a sys/network admin and not a programmer.  As a
sys admin if I had this problem while trying to pull eventlogs
manually with eventvwr I would simply map a drive to the remote
machine.  That would allow me to enter a username/password and then
once I was authed I'd have a session and I'd be able to piggyback on
that session to pull logs.

 I'm looking to do exactly that from inside my script.  I could
probably import os and call the net use command to map a drive and get
a session that way but that feels really sloppy to me.  I want to be
able to explicitly close this session when I'm done with it too.

 So I figure there's a com object I could call to open this
session for me but I can't figure out what it is.  Any help would be
appreciated!

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


cProfile.py not found.

2009-04-04 Thread Rahul
I need to profile a slow-running code. The problem is I cannot seem to find  
cProfile.py. 

Where can I get it? Is it not included in the normal distro? I tried 
googling it up and theres tons of info on how to use it but no links for 
where to download it from.

I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10). 

I am aware this is kind of dated but some of our legacy codes insist on 
using that exact version. 


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


Re: Creating a session in windows to auth to remote machines

2009-04-04 Thread ericwoodworth
On Apr 4, 6:39 pm, [email protected] wrote:
> Hi,
>      I'm trying to auth to remote machines so I can plunder WMI to get
> logs and settings and the like.  My script works for most of my
> machines because they're all in the same domain and I run the script
> as somebody who has enough access to get at this stuff but for
> machines off the domain I'm stuck.
>
>      Now I'm primarily a sys/network admin and not a programmer.  As a
> sys admin if I had this problem while trying to pull eventlogs
> manually with eventvwr I would simply map a drive to the remote
> machine.  That would allow me to enter a username/password and then
> once I was authed I'd have a session and I'd be able to piggyback on
> that session to pull logs.
>
>      I'm looking to do exactly that from inside my script.  I could
> probably import os and call the net use command to map a drive and get
> a session that way but that feels really sloppy to me.  I want to be
> able to explicitly close this session when I'm done with it too.
>
>      So I figure there's a com object I could call to open this
> session for me but I can't figure out what it is.  Any help would be
> appreciated!
>
> Thanks

Also I am writing this in Python.  So I can use win32com if that's the
way to go or I can use anything python 2.6 has built in.  I mentioned
com objects because I'm using a lot of those currently but if there's
a more pythonic way to do what I"m after then I'm all ears.

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


Re: cProfile.py not found.

2009-04-04 Thread Robert Kern

On 2009-04-04 17:46, Rahul wrote:

I need to profile a slow-running code. The problem is I cannot seem to find
cProfile.py.

Where can I get it? Is it not included in the normal distro? I tried
googling it up and theres tons of info on how to use it but no links for
where to download it from.

I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10).

I am aware this is kind of dated but some of our legacy codes insist on
using that exact version.


What system are you on? Some Linux distributions put it into a separate package, 
like python-profile. The python.org Windows and Mac binaries should have it, though.


--
Robert Kern

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

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


Re: cProfile.py not found.

2009-04-04 Thread John Yeung
I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
the profile module.  That is what the docs recommend.

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


Re: cProfile.py not found.

2009-04-04 Thread Rahul
Robert Kern  wrote in
news:[email protected]: 

> What system are you on? Some Linux distributions put it into a
> separate package, like python-profile. The python.org Windows and Mac
> binaries should have it, though. 
> 
> 

THanks Robert. I'm on RHEL. 

Tried yum search python-profile. No hits. Also tried a locate on 
cProfile. No hits again.

Did a yum search python. Huge list but nothing promising. Yet, I 
reproduce it below just in case its hidden somewhere in the list. What 
options do I have now? 

python-sqlite2.i386 : DB-API 2.0 interface for SQLite 3.x
tix.i386 : A set of extension widgets for Tk
tix-devel.i386 : Tk Interface eXtension development files
tix-doc.i386 : Tk Interface eXtension documentation
vim-enhanced.i386 : A version of the VIM editor which includes recent
  : enhancements.
Django.noarch : A high-level Python Web framework
Django-doc.noarch : Documentation for Django
MySQL-python.i386 : An interface to MySQL
OpenIPMI-python.i386 : OpenIPMI Python language bindings
PyQt.i386 : Python bindings for Qt
PyQt-examples.i386 : Examples for PyQt
PyXML.i386 : XML libraries for python.
PyYAML.noarch : YAML parser and emitter for Python
Pyrex.noarch : A compiler/language for writing Python extension modules.
PythonCard.noarch : PythonCard GUI construction toolkit
R2spec.noarch : Python script to generate R spec file
SOAPpy.noarch : Full-featured SOAP library for Python
TurboGears.noarch : Back-to-front web development in Python
ant-scripts.i386 : Additional scripts for ant
archivemail.noarch : A tool for archiving and compressing old email in 
mailboxes
audit-libs-python.i386 : Python bindings for libaudit
babel.noarch : Tools for internationalizing Python applications
beecrypt-python.i386 : Files needed for python applications using 
beecrypt.
booty.noarch : simple python bootloader config lib
bsf.i386 : Bean Scripting Framework
cobbler.noarch : Boot server configurator
ctopy.noarch : C to Python translator
cvs2svn.noarch : CVS to Subversion Repository Converter
db4.i386 : The Berkeley DB database library (version 4) for C.
dbus-python.i386 : D-Bus Python Bindings
ddd.i386 : GUI for several command-line debuggers
deluge.i386 : Graphical BitTorrent client with support for DHT, UPnP, and 
PEX
denyhosts.noarch : A script to help thwart ssh server attacks
epydoc.noarch : Edward Loper's Python API documentation generation tool
exaile.i386 : A music player
flumotion.i386 : Flumotion - the Fluendo Streaming Server
fuzzyclock.noarch : Generates fuzzy clock output
gamin-python.i386 : Python bindings for the gamin library
gdal.i386 : Geospatial Data Abstraction Library
gdal-python.i386 : Python modules for the GDAL file format library
getmail.noarch : POP3 mail retriever with reliable Maildir delivery
glade2.i386 : A GTK+ GUI builder.
gnome-menus.i386 : A menu system for the GNOME project
gnome-python2.i386 : The sources for the PyGNOME Python extension module
gnome-python2-applet.i386 : Python bindings for GNOME Panel applets.
gnome-python2-bonobo.i386 : Python bindings for interacting with bonobo.
gnome-python2-canvas.i386 : Python bindings for the GNOME Canvas.
gnome-python2-desktop.i386 : The sources for additional PyGNOME Python 
extension
   : modules for the GNOME desktop
gnome-python2-extras.i386 : The sources for additional. PyGNOME Python 
extension
  : modules.
gnome-python2-gconf.i386 : Python bindings for interacting with GConf
gnome-python2-gnomedesktop.i386 : Python bindings for interacting with 
gnome-
: desktop
gnome-python2-gnomekeyring.i386 : Python bindings for interacting with 
gnome-
: keyring
gnome-python2-gnomeprint.i386 : Python bindings for interacting with
  : libgnomeprint
gnome-python2-gnomevfs.i386 : Python bindings for interacting with gnome-
vfs
gnome-python2-gtkhtml2.i386 : Python bindings for interacting with 
gtkhtml2

python-twisted-names.i386 : A Twisted DNS implementation
python-twisted-web.i386 : Twisted web server, programmable in Python
python-twisted-web2.i386 : Twisted web server, programmable in Python
python-twisted-words.i386 : Twisted Words contains Instant Messaging 
implementations
python-twitter.noarch : A python wrapper around the Twitter API
python-tz.noarch : World Timezone Definitions for Python
python-urlgrabber.noarch : High-level cross-protocol url-grabber
python-urljr.noarch : Common interface to urllib2 and curl for making 
HTTP requests
python-urwid.noarch : Console UI Library for Python
python-urwid.i386 : Console UI Library for Python
python-utmp.i386 : Python module for working with utmp
python-vcpx.noarch : Version Control Patch eXchanger
python-virtinst.noarch : Python modules for starting Xen guest 
installations
python-vorbis.i386 : Python bindings for libvorbis
python-webob.noarch : WSGI request and response object
python-which.noarch : Small w

[RELEASED] Python 3.1 alpha 2

2009-04-04 Thread Benjamin Peterson
On behalf of the Python development team, I'm thrilled to announce the second
alpha release of Python 3.1.

Python 3.1 focuses on the stabilization and optimization of features and changes
Python 3.0 introduced.  For example, the new I/O system has been rewritten in C
for speed.  Other features include an ordered dictionary implementation and
support for ttk Tile in Tkinter.  For a more extensive list of changes in 3.1,
see http://doc.python.org/dev/py3k/whatsnew/3.1.html or Misc/NEWS in the Python
distribution.

Please note that this is an alpha releases, and as such is not suitable for
production environments.  We continue to strive for a high degree of quality,
but there are still some known problems and the feature sets have not been
finalized.  This alpha is being released to solicit feedback and hopefully
discover bugs, as well as allowing you to determine how changes in 3.1 might
impact you.  If you find things broken or incorrect, please submit a bug report
at

 http://bugs.python.org

For more information and downloadable distributions, see the Python 3.1 website:

 http://www.python.org/download/releases/3.1/

See PEP 375 for release schedule details:

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


Regards,
-- Benjamin

Benjamin Peterson
benjamin at python.org
Release Manager
(on behalf of the entire python-dev team and 3.1's contributors)
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Robert Kern

On 2009-04-04 18:08, John Yeung wrote:

I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
the profile module.  That is what the docs recommend.


Oops, I missed that piece of information. Alternately, the OP can install 
lsprof, which was cProfile's third-party incarnation before it got integrated 
into the stdlib:


  http://codespeak.net/svn/user/arigo/hack/misc/lsprof/

--
Robert Kern

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

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


Re: cProfile.py not found.

2009-04-04 Thread John Machin
On Apr 5, 8:46 am, Rahul  wrote:
> I need to profile a slow-running code. The problem is I cannot seem to find  
> cProfile.py.
>
> Where can I get it? Is it not included in the normal distro? I tried
> googling it up and theres tons of info on how to use it but no links for
> where to download it from.
>
> I am using Python 2.4.4 (#3, Feb 17 2008, 15:06:10).

Read the fantastic manual:

http://docs.python.org/library/profile.html

Note: this is the *first* hit when you google either "cprofile" or
"cProfile.py".

"""
The Python standard library provides three different profilers:

   1.

  cProfile is recommended for most users; it’s a C extension with
reasonable overhead that makes it suitable for profiling long-running
programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.

  New in version 2.5.
"""
--
http://mail.python.org/mailman/listinfo/python-list


possible pairings in a set

2009-04-04 Thread Ross
I'm new to python and I'm trying to come up with a function that takes
a given number of players in a game and returns all possible unique
pairings. Here's the code I've come up with so far, but I'm not
getting the output I'd like to:

def all_pairings(players):
cleanlist = []
for i in range(players):
cleanlist.append(i)
return cleanlist
start = 0
follow = start +1
finallist = []
while follow <= len(cleanlist)-1:
for player in cleanlist:
mini = cleanlist[start],cleanlist[follow]
finallist.append(mini)
follow +=1
start+=1
return finallist

If I were to execute the function with all_pairings(4), I want to get
the output [[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]. Instead, I get
[0,1,2,3] with the code I currently have. Can you guys help me out?
Also, if my code is considered ugly or redundant by this community,
can you make suggestions to clean it up?
--
http://mail.python.org/mailman/listinfo/python-list


Re: what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread John Machin
On Apr 5, 9:56 am, Rahul  wrote:
> "profile" tells me that most of my runtime was spent in just one part (1.28
> sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this
> as a function call with my python code. Also what's the 0 in the snippet:  
> ":0(execfile)"? Isn't there supposed to be a line-number?
>
> Looking up "execfile" in the python manual leads me to "exec": "This
> statement supports dynamic execution of Python code."
>
> But that seems pretty generic; how can I now try figuring out which part of
> my python file is the bottleneck?
>
> Sorry, I'm a newbiee to profiling.
>
> ##
>        51651 function calls (37762 primitive calls) in 1.290 CPU seconds
>  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
> [snip]
>     1    0.010    0.010    1.280    1.280 :0(execfile)
> [snip]
> ##

That means no more than "the profiler executed all of your code
once, it took 0.01 seconds inside the execfile itself, 0.01 seconds
per execution, total time spent by the execfile *and* what it called
was 1.28 seconds ("cum" == "cumulative"), again 1.28 secs per
execution"

So ignore that and look at the figures for the app functions/methods.
--
http://mail.python.org/mailman/listinfo/python-list


Re: possible pairings in a set

2009-04-04 Thread Benjamin Peterson
Ross  gmail.com> writes:
> Can you guys help me out?

Do you have Python 2.6? If so, it's a solved problem. :)

import itertools
possible_pairings = list(itertools.combinations(players, 2))




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


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Machin  wrote in news:0a8400dc-b14b-4bb9-a608-
[email protected]:

> Read the fantastic manual:
> 
> http://docs.python.org/library/profile.html
 [snip]
>   cProfile is recommended for most users; it's a C extension with
> reasonable overhead that makes it suitable for profiling long-running
> programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.
> 
>   New in version 2.5.
> 

Thanks John; I did read the manual which is why I decided to use cProfile 
as it was "recommended for most users".  I missed the last bit about "New 
in version 2.5." 

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


Re: cProfile.py not found.

2009-04-04 Thread John Machin
On Apr 5, 9:41 am, Rahul  wrote:
> John Machin  wrote in news:0a8400dc-b14b-4bb9-a608-
> [email protected]:
>
>
>
> > Read the fantastic manual:
>
> >http://docs.python.org/library/profile.html
>  [snip]
> >       cProfile is recommended for most users; it's a C extension with
> > reasonable overhead that makes it suitable for profiling long-running
> > programs. Based on lsprof, contributed by Brett Rosen and Ted Czotter.
>
> >       New in version 2.5.
>
> Thanks John; I did read the manual which is why I decided to use cProfile
> as it was "recommended for most users".  I missed the last bit about "New
> in version 2.5."

Looks like our definitions of "read" differ :-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Yeung  wrote in news:c0752f32-b0cf-4fde-
[email protected]:

> I believe cProfile was added in 2.5.  Your best bet on 2.4 is probably
> the profile module.  That is what the docs recommend.
> 

Thanks John. That works. I'll use "profile" instead.

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


what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread Rahul
"profile" tells me that most of my runtime was spent in just one part (1.28 
sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this 
as a function call with my python code. Also what's the 0 in the snippet:  
":0(execfile)"? Isn't there supposed to be a line-number? 

Looking up "execfile" in the python manual leads me to "exec": "This 
statement supports dynamic execution of Python code."

But that seems pretty generic; how can I now try figuring out which part of 
my python file is the bottleneck? 

Sorry, I'm a newbiee to profiling.


##
   51651 function calls (37762 primitive calls) in 1.290 CPU seconds
 ncalls  tottime  percall  cumtime  percall filename:lineno(function)
[snip]
10.0100.0101.2801.280 :0(execfile)
[snip]
##




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


Re: cProfile.py not found.

2009-04-04 Thread Rahul
John Machin  wrote in news:4c8ee09e-71e2-464a-a3c0-
[email protected]:

> Looks like our definitions of "read" differ :-)
> 

Sorry. I ought to have said "skimmed" :) 

I guess I am one of those guilty lazy-bums that the manual refers to under 
<<>>

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


Re: what does "execfile" mean within profiler output and why does it not have a attached line number

2009-04-04 Thread Robert Kern

On 2009-04-04 18:56, Rahul wrote:

"profile" tells me that most of my runtime was spent in just one part (1.28
sec cumulatively out of 1.29 secs. But what is "execfile"? I don't see this
as a function call with my python code. Also what's the 0 in the snippet:
":0(execfile)"? Isn't there supposed to be a line-number?


It's a builtin function, so it has no filename or line number.

execfile is a function that reads a Python file and executes its code. This is 
almost certainly the execfile call from profile.py itself that is running your 
code. Ignore it.



Looking up "execfile" in the python manual leads me to "exec": "This
statement supports dynamic execution of Python code."

But that seems pretty generic; how can I now try figuring out which part of
my python file is the bottleneck?


To quickly find your hotspots, start by sorting by 'time' (that would be 
displayed as the 'tottime' column in the human-readable output). That tells you 
how much time is spent in each function itself, excluding the time it spends 
calling out to other functions. For example, per the docs under "Instant User’s 
Manual" (which you might want to spend a little more time with):


  p.sort_stats('time').print_stats(10)

--
Robert Kern

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

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


RE: possible pairings in a set

2009-04-04 Thread John Posner
 >> Also, if my code is considered ugly or redundant by this community,
 >> can you make suggestions to clean it up?

Python is pretty mature: if you have a simple, generic problem, the chances
are that someone else has already solved it, packaging the solution in a
library (or "module"). For your job, the "itertools" module includes the
function "combinations":

import itertools
for comb in itertools.combinations([0,1,2,3], 2):
print comb

output:
(0, 1)
(0, 2)
(0, 3)
(1, 2)
(1, 3)
(2, 3)

Note that the output of itertools.combinations() is not a list but an
iterator. If you need the entire list, use the list() function to have the
iterator deliver all the goods at once:

mylist = list(itertools.combinations([0,1,2,3], 2))





E-mail message checked by Spyware Doctor (6.0.0.386)
Database version: 5.12110
http://www.pctools.com/en/spyware-doctor-antivirus/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Goes Mercurial

2009-04-04 Thread Martin v. Löwis
>> I don't like git because it is too difficult for me. In many cases,
>> git would refuse to do operations like updating or local committing,
>> producing error messages I was not able to understand ...
> 
> Post an example of what you were trying to do, with the exact messages, and 
> we can walk you through it.

Unfortunately, these are many months ago, and I don't recall the exact
error messages. I wasn't really asking for help, merely pointing out
that I dislike git because it makes me ask for help (something I did
not have to do for CVS or subversion, except for very special cases).

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


  1   2   >