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

2009-04-03 Thread John Doe
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. 
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-03 Thread Tim Golden

John Doe wrote:
Anybody have a solution for Windows (XP) Explorer search not finding 
ordinary text in *.py files? 


It came up a couple of months ago either on this
list or on python-win32. Don't have web access
at the moment, but try searching the archives for
references to search, registry settings and probably
an msdn link. 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. That
should get you the thread at any rate.


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


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

2009-04-03 Thread Michael Torrie
Tim Wintle wrote:
> On Fri, 2009-04-03 at 14:58 -0600, Michael Torrie wrote:
>> Oh wow.  If this is what Twitter does to one's ability to articulate
>> clearly, I hope Twitter dies a horrible death and any APIs and Python
>> bindings with it!
> 
> Thank you, thank you, thank you 
> 
> everyone around me seems to love that thing (twitter), and I still can't
> work out why (apart from hacks such as using it as a hosted queue for
> cross-server comms, or receiving cheap sms to your app)

Yeah.  Of course I always thought that IRC was a good fit for this
purpose.  Virus writers seem to think so.  I wonder how Twitter would
deal with viruses and worms using Twitter and a command and control
communications mechanism.

People who love Twitter are also people who SMS a lot it seems.  Twitter
probably is a natural evolution of SMS, melding the IRC idea with
ridiculously short, hard-to-read, cryptic, lol-speak, messages.  I think
the Japanese just might be on to something as no one over there uses
SMS.  It's all e-mail to them.  Granted the scourge of abbreviated words
and lol-speak is just as bad there.   Sigh.


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


Books about refactoring in Python (Was: A design problem I met again and again.)

2009-04-03 Thread Michele Simionato
On Apr 4, 6:10 am, Carl Banks  wrote:
> 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.

That's good advice. A typical refactoring technique when
working with blob classes is to extract groups of methods
with commmon functionality, put them in a helper
class, make a helper object and pass it to the
original blob. In other words, tp split the blob
object as a composition of small logically independent
objects. BTW, is there anybody in this lists that
can suggest good books about refactoring in Python?
There are plenty of books about refactoring for Java
and C++ but on top of my mind I cannot think of a Python
book right now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: User or UserManager ? Problems of Observer Pattern

2009-04-03 Thread Michele Simionato
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: is there a way to collect twitts with python?

2009-04-03 Thread Nick Stinemates
> Thank you, thank you, thank you 

> everyone around me seems to love that thing (twitter), and I still can't
> work out why (apart from hacks such as using it as a hosted queue for
> cross-server comms, or receiving cheap sms to your app)

> Tim Wintle

You mean you don't want to read every detail of someone's life? Damn..

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


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

2009-04-03 Thread Tim Wintle
On Fri, 2009-04-03 at 14:58 -0600, Michael Torrie wrote:
> Oh wow.  If this is what Twitter does to one's ability to articulate
> clearly, I hope Twitter dies a horrible death and any APIs and Python
> bindings with it!

Thank you, thank you, thank you 

everyone around me seems to love that thing (twitter), and I still can't
work out why (apart from hacks such as using it as a hosted queue for
cross-server comms, or receiving cheap sms to your app)

Tim Wintle

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


Re: python needs leaning stuff from other language

2009-04-03 Thread Tim Wintle
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

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


you can already do:
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):

(Python 2.5.2 - don't have a newer version on this machine to check)
{{{
import dis
>>> def f(a):
...   del a[:]
...
>>> def g(a):
...   a[:] = []
...
>>> def h(a):
...   a = []
...
>>> dis.dis(f)
  2   0 LOAD_FAST0 (a)
  3 DELETE_SLICE+0  
  4 LOAD_CONST   0 (None)
  7 RETURN_VALUE
>>> dis.dis(g)
  2   0 BUILD_LIST   0
  3 LOAD_FAST0 (a)
  6 STORE_SLICE+0   
  7 LOAD_CONST   0 (None)
 10 RETURN_VALUE
>>> dis.dis(h)
  2   0 BUILD_LIST   0
  3 STORE_FAST   0 (a)
  6 LOAD_CONST   0 (None)
  9 RETURN_VALUE
}}}

so it seems silly to introduce a *third* formal description of what is
(almost) semantically the same!

My knowledge of the interpreter begins to get fuzzy here, but would this
add extra overhead by the look-ups to the .clear method (really don't
have the time to compile a patched version of trunk to test!) - it might
be a constant change, but it's still a difference to what I believe is
likely to be required to be fairly high-performance when it is used.

e.g. 
{{{
>>> def f(a):
...   a.clear()
... 
>>> dis.dis(f)
  2   0 LOAD_FAST0 (a)
  3 LOAD_ATTR0 (clear)
  6 CALL_FUNCTION0
  9 POP_TOP 
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE
}}}

The current versions at least do two different things quite efficiently
- if you are clearing the list and expect the list to be small / zero
length next time, then (I believe) it's more memory efficient to try 
mylist = []

,where
del mylist[:] 

will (I'm assuming - correct me if I'm wrong) reduce the size of the
list, but using the clever list memory usage it will scale to a large
size again fairly well.

As for:
"Should we also remove .update from dict?"

Am I missing something? What is the single statement that is equivalent
to .update (although personally I don't think I have *ever* used .update
- I'm normally using a set for situations where I would require .update)


Oh, and can I have the reference for Raymond Hettinger's blessing
(mentioned in a different branch of this thread)? As far as I can see he
has only (in archives at least) replied to a question about whether it's
worth formalising the request as a PEP, and hasn't entered a vote either
way:

"""
Just ask Guido for his blessing.  The implementation is trivial.
"""
http://mail.python.org/pipermail/python-ideas/2009-April/003938.html

Ironically much of my - very limited - knowledge of the interpreter
stems from many of his talks, which were the encouragement to start
actually reading the source for the interpreter!

I'm more than willing to drop my issue if it's voted against, but it
does feel dirty to me to add extra syntax that have completely parallel
semantics. 

In general language design (not just programming languages) I personally
take any (provable) requirement for this as a _possible_ problem with
the chosen basis / semantic value function (in 1st order language
terms), although I understand that it is sometimes unavoidable in real
life.

For example, this makes me question the orthogonality of "ordered" and
"collection" with semantics dictated by their methods/features. 

Proposing that the object:
mylist[a:b:c] 

return an iterator that is non-assignable appears to fix this
non-orthogonality as far as I can immediately see (although I am *very*
tired, and haven't thought it through far enough!)


Tim Wintle



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


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

2009-04-03 Thread John Doe

Anybody have a solution for Windows (XP) Explorer search not finding 
ordinary text in *.py files? 

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


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

2009-04-03 Thread alex23
On Apr 4, 6:58 am, Michael Torrie  wrote:
> Oh wow.  If this is what Twitter does to one's ability to articulate
> clearly, I hope Twitter dies a horrible death and any APIs and Python
> bindings with it!

At least he was able to use more than 140 chars :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: A design problem I met again and again.

2009-04-03 Thread Carl Banks
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


Re: Best way to pickle functions

2009-04-03 Thread Aaron Brady
On Apr 3, 3:48 pm, Aaron Scott  wrote:
> > Why not use import ?  Simply recreate the source file, if necessary, and
> > import it again.
>
> Ah, you'd think it would be that easy :P
>
> The problem with just importing a module is that the module is then
> cached in memory. Multiple copies of the program are running on a
> server, and each of them have something akin to a "randomfunctions"
> module. When the first program is accessed, it loads
> "randomfunctions". When the second program is accessed, it uses the
> "randomfunctions" module already in memory, even though it doesn't
> contain the right functions. So, I have to pull in these functions
> dynamically.

Here I found this cookie you can have it. 

imp.load_source(name, pathname[, file])
Load and initialize a module implemented as a Python source file and
return its module object. If the module was already initialized, it
will be initialized again.

'again' was actually in italics in the docs.  

I presume you're aware of eval and exec.
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Pythoner",Wish me luck!

2009-04-03 Thread George Sakkis
On Apr 3, 3:47 pm, barisa  wrote:
> On Apr 3, 8:58 pm, nrball...@gmail.com wrote:
>
>
>
> > On Apr 3, 12:33 pm, barisa  wrote:
>
> > > On Apr 3, 11:39 am, "Hendrik van Rooyen"  wrote:
>
> > > > "Matteo"  wrote:
>
> > > > On Apr 3, 9:05 am, Linuxwell  wrote:
>
> > > > >> Starting today I would like to study Python,Wish me luck!
>
> > > > >Good luck!
>
> > > > >Don't forget to...
>
> > > >  print 'Hello World!'
>
> > > > This is better advice than what you may think,
> > > > because the interactive interpreter is your very
> > > > best friend when studying the language.
>
> > > > You get there by typing "python" at the command
> > > > line, and pressing enter.
>
> > > > Using it, you will save yourself many hours of
> > > > misunderstanding.
>
> > > > - Hendrik
>
> > > 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)
>
> > I'm also a beginner in Python, but from my own experience the
> > interactive interpreter is great for experimenting with new modules
> > and output formatting because it allows you to see the immediate
> > output of a function before you write it into your program.  The
> > immediate result is that you'll see any errors and be able to fix them
> > before they end up in your script.
>
> > Nick Ballardhttp://90daysofpython.blogspot.com
>
> thanks, i'll give it a try

Or even better, install IPython [1], a python interpreter on steroids.
It's the first 3rd party python package I install on every new system
I work on; it's so powerful and versatile, it has almost displaced the
regular linux shell for me. I highly recommend it.

George

[1] http://ipython.scipy.org/
--
http://mail.python.org/mailman/listinfo/python-list


Problem understanding some unit tests in Python distribution

2009-04-03 Thread André
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.

Cheers,

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


Re: Let-expressions

2009-04-03 Thread sloisel
Thanks for the quick replies.

I didn't want statements in my expressions, just let-expressions.
That's okay, it was just a question.

Sébastien Loisel

On Apr 3, 7:20 pm, Chris Rebert  wrote:
> On Fri, Apr 3, 2009 at 4:18 PM, Terry Reedy  wrote:
> > sloisel wrote:
>
> >> Dear All,
>
> >> I searched this group and found that there have been discussions about
> >> introducing a let expression to the language so that you can define
> >> local variables in a lambda. I.e., something like f=lambda x: let
> >> y=x^2 in sin(y). (My syntax is unpythonic, but I hope you get it).
>
> >> Can someone tell me what eventually happened?
>
> > The discussions ended.
> > Proposals for assignment expressions have been rejected.
>
> To elaborate slightly, if you need anything more complicated than a
> single expression, then *don't use a lambda*. Just use a named
> function. It's much clearer and easier.
> Proposals to extend lambda usually spiral/evolve into wanting to make
> lambda multi-line, which has repeatedly been found to be incompatible
> with Python's indentation-based syntax; and, again, you can just use a
> named function.
>
> Cheers,
> Chris
>
> --
> I have a blog:http://blog.rebertia.com

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


Re: Best way to extract from regex in if statement

2009-04-03 Thread Tim Chase

Or in case you want to handle each regexp differently, you can
construct a dict {regexp : callback_function} that picks the right
action depending on which regexp matched. 


One word of caution:  dicts are unsorted, so if more than one 
regexp can match a given line, they either need to map to the 
same function, or you need to use a list of regexp-to-functions 
(see my previous post) for a determinate order.


-tkc




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


Re: Best way to extract from regex in if statement

2009-04-03 Thread Paul Rubin
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

Then your example would look something like:

save_re = Reg()

elif save_re.match("^DATASET:\s*(.+) ", line):
   print save_re.result.group(1)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to extract from regex in if statement

2009-04-03 Thread George Sakkis
On Apr 3, 9:56 pm, Jon Clements  wrote:
> On 4 Apr, 02:14, bwgoudey  wrote:
>
>
>
> > I have a lot of if/elif cases based on regular expressions that I'm using to
> > filter stdin and using print to stdout. Often I want to print something
> > matched within the regular expression and the moment I've got a lot of cases
> > like:
>
> > ...
> > elif re.match("^DATASET:\s*(.+) ", line):
> >         m=re.match("^DATASET:\s*(.+) ", line)
> >         print m.group(1))
>
> > which is ugly because of the duplication but I can't think of a nicer of way
> > of doing this that will allow for a lot of these sorts of cases. Any
> > suggestions?
> > --
> > View this message in 
> > context:http://www.nabble.com/Best-way-to-extract-from-regex-in-if-statement-...
> > Sent from the Python - python-list mailing list archive at Nabble.com.
>
> How about something like:
>
> your_regexes = [
>     re.compile('rx1'),
>     re.compile('rx2'),
>     # etc
> ]
>
> for line in lines:
>     for rx in your_regexes:
>         m = rx.match(line)
>         if m:
>             print m.group(1)
>             break # if only the first matching regex is required,
> otherwise leave black for all
>
> Untested, but seems to make sense

Or in case you want to handle each regexp differently, you can
construct a dict {regexp : callback_function} that picks the right
action depending on which regexp matched. As for how to populate the
dict, if most methods are short expressions, lambda comes in pretty
handly, e.g.

{
  rx1: lambda match: match.group(1),
  rx2: lambda match: sum(map(int, match.groups())),
 ...
}

If not, you can combine the handler definition with the mapping update
by using a simple decorator factory such as the following (untested):

def rxhandler(rx, mapping):
  rx = re.compile(rx)
  def deco(func):
  mapping[rx] = func
  return func
   return deco

d = {}

@rxhandler("^DATASET:\s*(.+) ", d)
def handle_dataset(match):
   ...

@rxhandler("^AUTHORS:\s*(.+) ", d)
def handle_authors(match):
   ...

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


SendKeys not working in command line interface

2009-04-03 Thread Dhruv
hi everyone. I am fairly new to python. When I go to IDLE GUI for
python 2.6 and type:

>>> import SendKeys
>>> SendKeys.SendKeys('{LWIN} r notepad', pause=0.5)

it works fine. however when I write the same code using jEdit and run
it in command line, it does not give error but it doesn't run either.
Same problem if I start the command line shell of python 2.6 instead
of its IDLE Gui

Any suggestions/solutions?
Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-03 Thread Steven D'Aprano
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
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to extract from regex in if statement

2009-04-03 Thread Tim Chase

bwgoudey wrote:

I have a lot of if/elif cases based on regular expressions that I'm using to
filter stdin and using print to stdout. Often I want to print something
matched within the regular expression and the moment I've got a lot of cases
like:

...
elif re.match("^DATASET:\s*(.+) ", line):
m=re.match("^DATASET:\s*(.+) ", line)
print m.group(1))


which is ugly because of the duplication but I can't think of a nicer of way
of doing this that will allow for a lot of these sorts of cases. Any
suggestions?


I've done this in the past with re-to-function pairings:

  def action1(matchobj):
print matchobj.group(1)
  def action2(matchobj):
print matchobj.group(3)
  # ... other actions to perform

  searches = [
(re.compile(PATTERN1), action1),
(re.compile(PATTERN2), action2),
# other pattern-to-action pairs
]

  # ...
  line = ...
  for regex, action in searches:
m = regex.match(line)
if m:
  action(m)
  break
  else:
no_match(line)

(note that that's a for/else loop, not an if/else pair)

-tkc





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


Re: Best way to extract from regex in if statement

2009-04-03 Thread Jon Clements
On 4 Apr, 02:14, bwgoudey  wrote:
> I have a lot of if/elif cases based on regular expressions that I'm using to
> filter stdin and using print to stdout. Often I want to print something
> matched within the regular expression and the moment I've got a lot of cases
> like:
>
> ...
> elif re.match("^DATASET:\s*(.+) ", line):
>         m=re.match("^DATASET:\s*(.+) ", line)
>         print m.group(1))
>
> which is ugly because of the duplication but I can't think of a nicer of way
> of doing this that will allow for a lot of these sorts of cases. Any
> suggestions?
> --
> View this message in 
> context:http://www.nabble.com/Best-way-to-extract-from-regex-in-if-statement-...
> Sent from the Python - python-list mailing list archive at Nabble.com.

How about something like:

your_regexes = [
re.compile('rx1'),
re.compile('rx2'),
# etc
]

for line in lines:
for rx in your_regexes:
m = rx.match(line)
if m:
print m.group(1)
break # if only the first matching regex is required,
otherwise leave black for all

Untested, but seems to make sense

hth,

Jon

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


Re: python needs leaning stuff from other language

2009-04-03 Thread Giampaolo Rodola'
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.


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


Re: How to add lines to the beginning of a text file?

2009-04-03 Thread Jon Clements
On 4 Apr, 02:21, dean  wrote:
> Hello,
>
> As the subject says how would I go about adding the lines to the beginning
> of a text file? Thanks in advance.

I'd create a new file, then write your new lines, then iterate the
existing file and write those lines... If no errors occcur, issue a
delete for the old file, and a rename for new file to the old name.

hth

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


Re: How to add lines to the beginning of a text file?

2009-04-03 Thread Steven D'Aprano
On Sat, 04 Apr 2009 03:21:34 +0200, dean wrote:

> Hello,
> 
> As the subject says how would I go about adding the lines to the
> beginning of a text file? Thanks in advance.

I'm not aware of any operating system that allows you to insert data into 
the middle or beginning of a file, although I've heard rumours that some 
ancient operating systems (VAX?) may have.

To insert into a file, you have to do all the moving of data yourself. If 
the file is small enough to fit into memory, the easiest way is something 
like this:


# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open the file again for writing
f = open('filename', 'w')
f.write("This is the new first line\n")
# write the original contents
f.write(text)
f.close()


But note that this isn't entirely safe, if your Python session crashes 
after opening the file the second time and before closing it again, you 
will lose data. For quick scripts, that's a minuscule risk, but for 
bigger applications, you should use a safer method, something like this:


# read the current contents of the file
f = open('filename')
text = f.read()
f.close()
# open a different file for writing
f = open('filename~', 'w')
f.write("This is the new first line\n")
# write the original contents
f.write(text)
f.close()
# did everything work safely?
# if we get here, we're probably safe
os.rename('filename~', 'filename')


But note that even this is not entirely safe: it uses a predictable file 
name for the temporary file, which is generally a bad thing to do, it 
fails to flush data to disk, which means you're at the mercy of vagaries 
of the file system, and it doesn't do *any* error handling at all.

The standard library really needs a good "save data to file" solution.


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


Re: python needs leaning stuff from other language

2009-04-03 Thread Steven D'Aprano
On Fri, 03 Apr 2009 22:42:33 +0100, Tim Wintle wrote:

> On Fri, 2009-04-03 at 13:12 -0400, Mel wrote:
>> >>> I think it would also be better to have One (and prefereably Only
>> >>> One) Obvious Way To Do It. That obvious way, for those who work
>> >>> with Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best
>> >>> to have ‘list’ conform with this also.
>> >> 
>> >> Does that mean a one-off special case rule to forbid slices having a
>> >> default?
>> > 
>> > Why would it do that?
>> 
>> Well, if list.clear were truly and strictly to be the only way to clear
>> the contents of a list, then assigning nothing via the default slice
>> would have to be ruled out.  `somelist[:] = []` is just a special case
>> of assignment to a slice generally.
> 
> agreed. If .clear was to be added then really assignments to slices
> should be entirely removed.

That's total nonsense. Where do people get this ridiculous urban legend 
that there is "only one way to do it" in Python?

The Zen says:

"There should be one-- and preferably only one --obvious way to do it."

does not mean "only one way to do it". It is a *prescription* that there 
SHOULD be one OBVIOUS way to do a task, not a prohibition on more than 
one way to do a task.

Such a prohibition would be stupid *and* impossible to enforce:

# Four ways to remove trailing spaces from a string. There are others.

s.rstrip(" ")  # the one obvious way


while s.endswith(" "):
s = s[:-1]


while True:
if s[-1] == ' ':
s = s[0:-1]
else:
break


L = []
trailing_spaces = True
for c in reversed(s):
if c == ' ' and trailing_spaces:
 continue
trailing_spaces = False
L.append(c)
L.reverse()
s = ''.join(L)



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


How to add lines to the beginning of a text file?

2009-04-03 Thread dean
Hello,

As the subject says how would I go about adding the lines to the beginning
of a text file? Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


How to add lines to the beginning of a text file?

2009-04-03 Thread dean
Hello,

As the subject says how would I go about adding the lines to the beginning
of a text file? Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Best way to extract from regex in if statement

2009-04-03 Thread bwgoudey

I have a lot of if/elif cases based on regular expressions that I'm using to
filter stdin and using print to stdout. Often I want to print something
matched within the regular expression and the moment I've got a lot of cases
like:

...
elif re.match("^DATASET:\s*(.+) ", line):
m=re.match("^DATASET:\s*(.+) ", line)
print m.group(1))


which is ugly because of the duplication but I can't think of a nicer of way
of doing this that will allow for a lot of these sorts of cases. Any
suggestions?
-- 
View this message in context: 
http://www.nabble.com/Best-way-to-extract-from-regex-in-if-statement-tp22878967p22878967.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Undefined symbol PyUnicodeUCS2_DecodeUTF8

2009-04-03 Thread Manish Jain


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.


--

Thank you and Regards
Manish Jain
invalid.poin...@gmail.com
+91-99830-62246

NB : Laast year I kudn't spell Software Engineer. Now I are won.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hash of None varies per-machine

2009-04-03 Thread Steven D'Aprano
On Fri, 03 Apr 2009 10:50:08 -0700, ben.taylor wrote:

> 1. Is it correct that if you hash two things that are not equal they
> might give you the same hash value? 

Absolutely. From help(hash):

hash(...)
hash(object) -> integer

Return a hash value for the object.  Two objects with the same 
value have the same hash value.  The reverse is not necessarily 
true, but likely.


This is the pigeon-hole principle. On my PC, hash() returns a 32-bit 
integer between -2147483648 and 2147483647, so there are 2**32 unique 
hash values (the pigeon-holes). Presumably on 64-bit versions of Python, 
hash() will return a 64-bit result, giving 2**64 unique hash values. But 
there are an infinite number of possible objects which can be hashed (the 
pigeons), and so you have to have more than one pigeon per pigeon-hole.


> Like, for instance, None and the
> number 261862182320 (which is what my machine gives me if I hash None).
> Note this is just an example, I'm aware hashing integers is probably
> daft.

Hashing has a very important role in Python, and you will be using it 
very often behind the scenes. You couldn't use integers as keys in 
dictionaries if they couldn't be hashed: another name for a dict is a 
"hash table".


> I'm guessing that's fine, since you can't hash something to a
> number without colliding with that number (or at least without hashing
> the number to something else, like hashing every number to itself * 2,
> which would then mean you couldn't hash very large numbers)

You can hash numbers no matter how big they are.

>>> hash(float('inf'))
314159
>>> hash(2**999)
128



> 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.



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


Re: Unix programmers and Idle

2009-04-03 Thread Dale Amon
Just in case anyone else finds it useful, to be precise I use:

if opts.man:
p1 = Popen(["echo", __doc__], stdout=PIPE)
p2 = Popen(["pod2man"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["nroff","-man"], stdin=p2.stdout, stdout=PIPE)
output = p3.communicate()[0]
print output

inside the def main().


signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unix programmers and Idle

2009-04-03 Thread Dale Amon
On Mon, Mar 30, 2009 at 10:54:56PM -0700, Niklas Norrthon wrote:
> I make sure my scripts are on the form:
> 
> # imports
> # global initialization (not depending on sys.argv)
> def main():
> # initialization (might depend on sys.argv)
> # script logic
> # other functions
> if __name__ == '__main__':
> main()
> 
> Then I have a trivial debug script named debug_whatever.py, which I
> use as my entry point during debugging:
> 
> # debug_whatever.py:
> import sys
> sys.argv[1:] = ['arg1', 'arg2', 'arg3']
> import whatever
> whatever.main()

I've found this approach very useful in another way as well.
I write all my programs, in whatever language, with a perldoc
section at the very end of the file where it doesn't get in
the way of my seeing the code, but is still at least in the
same module. Due to the problems of forward referencing I
had not heretofore been able to use it inside the program
module as it was obviously not defined when the code ran.
However, with your method and with those two lines place at
the very end after the perldoc documentation the code 
execution is always delayed until I can stuff it into __doc__
and thus have it available to print with a --man command
line switch which I like to have in all my code. (I just
pipe the __doc__ string through perl2man there)

Works for me!



signature.asc
Description: Digital signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: Let-expressions

2009-04-03 Thread Chris Rebert
On Fri, Apr 3, 2009 at 4:18 PM, Terry Reedy  wrote:
> sloisel wrote:
>>
>> Dear All,
>>
>> I searched this group and found that there have been discussions about
>> introducing a let expression to the language so that you can define
>> local variables in a lambda. I.e., something like f=lambda x: let
>> y=x^2 in sin(y). (My syntax is unpythonic, but I hope you get it).
>>
>> Can someone tell me what eventually happened?
>
> The discussions ended.
> Proposals for assignment expressions have been rejected.

To elaborate slightly, if you need anything more complicated than a
single expression, then *don't use a lambda*. Just use a named
function. It's much clearer and easier.
Proposals to extend lambda usually spiral/evolve into wanting to make
lambda multi-line, which has repeatedly been found to be incompatible
with Python's indentation-based syntax; and, again, you can just use a
named function.

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-03 Thread Jon Clements
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...

Cheers,

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


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread Brett Cannon
On Fri, Apr 3, 2009 at 13:15, "Martin v. Löwis"  wrote:

> > Note that there is no such thing as a "defining namespace package" --
> > namespace package contents are symmetrical peers.
>
> With the PEP, a "defining package" becomes possible - at most one
> portion can define an __init__.py.
>
> I know that the current mechanisms don't support it, and it might
> not be useful in general, but now there is a clean way of doing it,
> so I wouldn't exclude it. Distribution-wise, all distributions
> relying on the defining package would need to require (or
> install_require, or depend on) it.
>
> > The above are also true for using only a '*' in .pkg files -- in that
> > event there are no sys.path changes.  (Frankly, I'm doubtful that
> > anybody is using extend_path and .pkg files to begin with, so I'd be
> > fine with a proposal that instead used something like '.nsp' files that
> > didn't even need to be opened and read -- which would let the directory
> > scan stop at the first .nsp file found.
>
> That would work for me as well. Nobody at PyCon could remember where
> .pkg files came from.
>
> > I believe the PEP does this as well, IIUC.
>
> Correct.
>
> >> * It's possible to have a defining package dir and add-one package
> >> dirs.
> >
> > Also possible in the PEP, although the __init__.py must be in the first
> > such directory on sys.path.
>
> I should make it clear that this is not the case. I envision it to work
> this way: import zope
> - searches sys.path, until finding either a directory zope, or a file
>  zope.{py,pyc,pyd,...}
> - if it is a directory, it checks for .pkg files. If it finds any,
>  it processes them, extending __path__.
> - it *then* checks for __init__.py, taking the first hit anywhere
>  on __path__ (just like any module import would)


Just so people know how this __init__ search could be done such that
__path__ is set from the .pkg is to treat it as a reload (assuming .pkg
files can only be found off of sys.path).


-Brett


> - if no .pkg was found, nor an __init__.py, it proceeds with the next
>  sys.path item (skipping the directory entirely)
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-03 Thread Christian Heimes
Aaron Scott wrote:
> 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.


First of all I like to highly recommend against mod_python and for
mod_wsgi. WSGI is *the* Python standard for web services.

Why are you using mod_python at all? If you neither need persistent
variables nor shared state then a CGI script is easier to use.

Christian


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


Re: python needs leaning stuff from other language

2009-04-03 Thread Robert Kern

On 2009-04-03 16:42, Tim Wintle wrote:

On Fri, 2009-04-03 at 13:12 -0400, Mel wrote:

I think it would also be better to have One (and prefereably Only One)
Obvious Way To Do It. That obvious way, for those who work with
Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
‘list’ conform with this also.

Does that mean a one-off special case rule to forbid slices having a
default?

Why would it do that?

Well, if list.clear were truly and strictly to be the only way to clear the
contents of a list, then assigning nothing via the default slice would have
to be ruled out.  `somelist[:] = []` is just a special case of assignment to
a slice generally.


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


Please tell me you are joking.

--
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: Let-expressions

2009-04-03 Thread Terry Reedy

sloisel wrote:

Dear All,

I searched this group and found that there have been discussions about
introducing a let expression to the language so that you can define
local variables in a lambda. I.e., something like f=lambda x: let
y=x^2 in sin(y). (My syntax is unpythonic, but I hope you get it).

Can someone tell me what eventually happened?


The discussions ended.
Proposals for assignment expressions have been rejected.

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


Re: Python Goes Mercurial

2009-04-03 Thread Ben Finney
Lawrence D'Oliveiro  writes:

> In message <49d65b62$0$30904$9b622...@news.freenet.de>, "Martin v. Löwis" 
> wrote:
> 
> > 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.

No, please, not in this forum. It would be quite off-topic, and Git
has its own discussion forums; please use those.

-- 
 \   Eccles: “I just saw the Earth through the clouds!”  Lew: “Did |
  `\  it look round?”  Eccles: “Yes, but I don't think it saw me.” |
_o__)—The Goon Show, _Wings Over Dagenham_ |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-03 Thread Ben Finney
Mel  writes:

> Well, if list.clear were truly and strictly to be the only way to
> clear the contents of a list

Who ever suggested that?

Note that the “OOW” in OOWTDI does *not* mean “Only One Way”. It
means “One Obvious Way”. Having other Ways To Do It is only mildly
deprecated, not forbidden.

-- 
 \   “It ain't so much the things we don't know that get us in |
  `\trouble. It's the things we know that ain't so.” —Artemus Ward |
_o__)   (1834-67), U.S. journalist |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unix programmers and Idle

2009-04-03 Thread MRAB

Dale Amon wrote:

On Mon, Mar 30, 2009 at 08:11:10PM -0500, Dave Angel wrote:
I don't know what Idle has to do with it.  sys.args contains the command  
line arguments used to start a script.


Dale Amon wrote:
I wonder if someone could point me at documentation on how to debug 
some of the standard Unix type things

in Idle. I cannot seem to figure out how to set my
argument line for the program I am debugging in an Idle
window. for example:

vlmdeckcheck.py --strict --debug file.dat

There must be a way to tell it what the command line args
are for the test run but I can't find it so far.



The line above represent what I want to emulate within idle.
If you run idle, select File->Open; then select the program name
as above to open; select Debug->Debugger; then start the program
with F5... which is lovely but I cannot find a way to tell idle
what the args are.

idle is really nice but I am stuck doing my debugging in pdb
because of this.


FYI I've just submitted a patch which adds a dialog for entering
command-line arguments in IDLE (issue #5680).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-03 Thread Aaron Scott
> 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
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-03 Thread Lawrence D'Oliveiro
In message <8bc55c05-19da-41c4-
b916-48e0a4be4...@p11g2000yqe.googlegroups.com>, 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


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


Re: Python Goes Mercurial

2009-04-03 Thread Lawrence D'Oliveiro
In message <49d65b62$0$30904$9b622...@news.freenet.de>, "Martin v. Löwis" 
wrote:

> 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.

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


Re: python needs leaning stuff from other language

2009-04-03 Thread MRAB

Tim Wintle wrote:

On Fri, 2009-04-03 at 13:12 -0400, Mel wrote:

I think it would also be better to have One (and prefereably Only One)
Obvious Way To Do It. That obvious way, for those who work with
Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
‘list’ conform with this also.

Does that mean a one-off special case rule to forbid slices having a
default?

Why would it do that?
Well, if list.clear were truly and strictly to be the only way to clear the 
contents of a list, then assigning nothing via the default slice would have 
to be ruled out.  `somelist[:] = []` is just a special case of assignment to 
a slice generally.


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


Should we also remove .update from dict?

I see no problem in collections having a .clear method. Saying that "if
c is a collection then c.clear() clears that collection" seems to be a
very duck-typy(?) thing to me.

Assignments to slices is just a feature of ordered collections (well,
lists), and clearing a list by assigning an empty list is just a special
case of that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Class methods read-only by default?

2009-04-03 Thread Piet van Oostrum
> "Emanuele D'Arrigo"  (ED) wrote:

>ED> Hi Everybody!
>ED> I just tried this:

> class C(object):
>ED> ...def method(self):
>ED> ...pass
>ED> ...
> c = C()
> delattr(c, "method")

>ED> Traceback (most recent call last):
>ED>   File "", line 1, in 
>ED> AttributeError: 'C' object attribute 'method' is read-only

>ED> How come? Who told the class to make the method read-only? I didn't!

Methods in a class are done with the descriptor protocol. All access to
the method through an instance is executed via the descriptor. The
delete calls the __delete__ method of the descriptor which isn't
implemented for functions. See
http://docs.python.org/reference/datamodel.html?highlight=descriptor#implementing-descriptors
(Actually, IIRC, the function object is its own descriptor)

>>> class C(object):
...   def method(self):
... pass
... 
>>> c=C()
>>> C.__dict__['method']

>>> C.__dict__['method'].__get__

>>> C.__dict__['method'].__delete__
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'function' object has no attribute '__delete__'
>>> 

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-03 Thread andrew cooke

are you an experienced python programmer?

a lot of newbies post here with problems related to unexpected results
because they make "the usual" mistakes about list mutability and default
function arguments.

i suspect that's not the case here, but it seemed worth mentioning, just
in case.

andrew


Aaron Scott wrote:
> Huzzah, another post.
>
> I just discovered that even physically deleting the variable doesn't
> work.
>
> The module storylab.game has the class InitGame, which contains
> "daemons = {}".
>
> A user runs the code, resulting in some values in "daemons":
> "{'berry2': , 'berry3': , 'berry1': }". These are pickled.
>
> The next user runs the code. I put this in to make sure "daemons" is
> getting reset:
>
>   req.write(str(lab.game.settings.daemons))
>   del lab.game.settings
>   req.write(str(lab.game.settings.daemons))
>   lab.game.settings = lab.game.InitGame()
>   req.write(str(lab.game.settings.daemons))
>
> Okay, that should wipe out any of the values and leave us with a clean
> slate, right?
>
>   {'berry2': , 'berry3': , 'berry1': }failed{'berry2': , 'berry3': ,
> 'berry1': }
>
> Oh, you'd be so lucky.
>
> Why? WHY? Why does these values persist? They persist if I change
> them, they persist if I delete them.
>
> Help... please :(
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


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


Re: Module caching

2009-04-03 Thread Aaron Scott
Huzzah, another post.

I just discovered that even physically deleting the variable doesn't
work.

The module storylab.game has the class InitGame, which contains
"daemons = {}".

A user runs the code, resulting in some values in "daemons":
"{'berry2': , 'berry3': , 'berry1': }". These are pickled.

The next user runs the code. I put this in to make sure "daemons" is
getting reset:

req.write(str(lab.game.settings.daemons))
del lab.game.settings
req.write(str(lab.game.settings.daemons))
lab.game.settings = lab.game.InitGame()
req.write(str(lab.game.settings.daemons))

Okay, that should wipe out any of the values and leave us with a clean
slate, right?

{'berry2': , 'berry3': , 'berry1': }failed{'berry2': , 'berry3': ,
'berry1': }

Oh, you'd be so lucky.

Why? WHY? Why does these values persist? They persist if I change
them, they persist if I delete them.

Help... please :(
--
http://mail.python.org/mailman/listinfo/python-list


Re: Module caching

2009-04-03 Thread Aaron Scott
Okay, I'm at my wit's end. I have a Python app, running via
mod_python. There are variables in this app that, when changed, save
their changes to a pickled file tied to a session ID. Then, when the
page is accessed again, the variables are loaded from the respective
file.

But, when one user uses the page and a number of variables are
changed, these changes persist, even if I try to load the saved values
over them. So, if my Python file has a value of "5", the "custom
values" file has a value of "10", but a user does something that
changes the variable to "20", the next user who accesses the page with
see the value as "20", even if their "custom values" file tries to set
it differently.

If anyone has experience with mod_python, either drop me a message
here or e-mail me at aaron(at)manlab.com. I'd really appreciate some
help with this.
--
http://mail.python.org/mailman/listinfo/python-list


Let-expressions

2009-04-03 Thread sloisel
Dear All,

I searched this group and found that there have been discussions about
introducing a let expression to the language so that you can define
local variables in a lambda. I.e., something like f=lambda x: let
y=x^2 in sin(y). (My syntax is unpythonic, but I hope you get it).

Can someone tell me what eventually happened?

Thanks,

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


Re: python needs leaning stuff from other language

2009-04-03 Thread Tim Wintle
On Fri, 2009-04-03 at 13:12 -0400, Mel wrote:
> >>> I think it would also be better to have One (and prefereably Only One)
> >>> Obvious Way To Do It. That obvious way, for those who work with
> >>> Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
> >>> ‘list’ conform with this also.
> >> 
> >> Does that mean a one-off special case rule to forbid slices having a
> >> default?
> > 
> > Why would it do that?
> 
> Well, if list.clear were truly and strictly to be the only way to clear the 
> contents of a list, then assigning nothing via the default slice would have 
> to be ruled out.  `somelist[:] = []` is just a special case of assignment to 
> a slice generally.

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

Tim W

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


Re: IIS python web application mapping issue - resolved

2009-04-03 Thread davidj411
I thought i was being clever but not only did i typo , but it does not
work with the "-u" for unbuffered option.

remove the "-u" to avoid the ugly message:

CGI Error
The specified CGI application misbehaved by not returning a complete
set of HTTP headers.

I am going to use the CGI script to upload files (.exe and .zip files)
and had read that "-u" would be needed.

i am going to need to research how this is done now that "-u" is a
known issue with IIS.
i think that i will need to baseencode64 the data before writing it to
a file. not sure really...
any thoughts are appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Module caching

2009-04-03 Thread Aaron Scott
Is there a way to make a Python app running in mod_python with zero
persistence? I have an app that should be resetting its variables
every time you access it, but sometimes -- and only sometimes -- the
variables persist through a couple refreshes. They'll even persist
through multiple browsers, so I know it's a Python issue and not a
browser caching issue.

Any assistance would be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread P.J. Eby

At 10:15 PM 4/3/2009 +0200, Martin v. Löwis wrote:

I should make it clear that this is not the case. I envision it to work
this way: import zope
- searches sys.path, until finding either a directory zope, or a file
  zope.{py,pyc,pyd,...}
- if it is a directory, it checks for .pkg files. If it finds any,
  it processes them, extending __path__.
- it *then* checks for __init__.py, taking the first hit anywhere
  on __path__ (just like any module import would)
- if no .pkg was found, nor an __init__.py, it proceeds with the next
  sys.path item (skipping the directory entirely)


Ah, I missed that.  Maybe the above should be added to the PEP to clarify.

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


SFTP libraries in pure Python?

2009-04-03 Thread hirudo #1







Hi, I am looking for SFTP libraries that are written in pure Python. I already 
checked out paramiko, but as far as I can see, it requires pycrypto, which is 
not pure Python. Another candidate, Twisted, isn't pure Python either. I don't 
really care about speed as much as about portability.

I'm hoping for some pointers here.

-Peter-


_
What can you do with the new Windows Live? Find out
http://www.microsoft.com/windows/windowslive/default.aspx--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread glyph

On 08:15 pm, mar...@v.loewis.de wrote:

Note that there is no such thing as a "defining namespace package" --
namespace package contents are symmetrical peers.


With the PEP, a "defining package" becomes possible - at most one
portion can define an __init__.py.


For what it's worth, this is a _super_ useful feature for Twisted.  We 
have one "defining package" for the "twisted" package (twisted core) and 
then a bunch of other things which want to put things into twisted.* 
(twisted.web, twisted.conch, et. al.).


For debian we already have separate packages, but such a definition of 
namespace packages would allow us to actually have things separated out 
on the cheeseshop as well.

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


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

2009-04-03 Thread Michael Torrie
'2+ wrote:
> i found a guy twittin supercollider code
> this means his followers can listen to a noiz by activating that 1 line
> (well if he has sc installed)
> if lots of sc users start twittin ... it would be no good to follow each
> 
> collecting a sc related twitt can be done with python?
> if there's a lib already any good pointers to start learnin thangs at?
> 
> maybe someday
> jython or pyjamas can be used to launch a
> sctwitt strreaming radio?
> (this should be the one listeners can mix his favorite sctwittists)

Oh wow.  If this is what Twitter does to one's ability to articulate
clearly, I hope Twitter dies a horrible death and any APIs and Python
bindings with it!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to pickle functions

2009-04-03 Thread Aaron Scott
> Why not use import ?  Simply recreate the source file, if necessary, and
> import it again.
>

Ah, you'd think it would be that easy :P

The problem with just importing a module is that the module is then
cached in memory. Multiple copies of the program are running on a
server, and each of them have something akin to a "randomfunctions"
module. When the first program is accessed, it loads
"randomfunctions". When the second program is accessed, it uses the
"randomfunctions" module already in memory, even though it doesn't
contain the right functions. So, I have to pull in these functions
dynamically.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread Martin v. Löwis
> Note that there is no such thing as a "defining namespace package" --
> namespace package contents are symmetrical peers.

With the PEP, a "defining package" becomes possible - at most one
portion can define an __init__.py.

I know that the current mechanisms don't support it, and it might
not be useful in general, but now there is a clean way of doing it,
so I wouldn't exclude it. Distribution-wise, all distributions
relying on the defining package would need to require (or
install_require, or depend on) it.

> The above are also true for using only a '*' in .pkg files -- in that
> event there are no sys.path changes.  (Frankly, I'm doubtful that
> anybody is using extend_path and .pkg files to begin with, so I'd be
> fine with a proposal that instead used something like '.nsp' files that
> didn't even need to be opened and read -- which would let the directory
> scan stop at the first .nsp file found.

That would work for me as well. Nobody at PyCon could remember where
.pkg files came from.

> I believe the PEP does this as well, IIUC.

Correct.

>> * It's possible to have a defining package dir and add-one package
>> dirs.
> 
> Also possible in the PEP, although the __init__.py must be in the first
> such directory on sys.path.

I should make it clear that this is not the case. I envision it to work
this way: import zope
- searches sys.path, until finding either a directory zope, or a file
  zope.{py,pyc,pyd,...}
- if it is a directory, it checks for .pkg files. If it finds any,
  it processes them, extending __path__.
- it *then* checks for __init__.py, taking the first hit anywhere
  on __path__ (just like any module import would)
- if no .pkg was found, nor an __init__.py, it proceeds with the next
  sys.path item (skipping the directory entirely)

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


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

2009-04-03 Thread Christian Heimes
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.

Christian

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


Re: Hash of None varies per-machine

2009-04-03 Thread Christian Heimes
Paul Rubin wrote:
> 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.

No, hashs are C longs. On most 64bit platforms a C long has 64bits. As
far as I know only 64bit Windows has a 32bit long type.

> If the docs say this shouldn't happen, then it's a bug.  Otherwise,
> it should probably be considered ok.

Can you show me the exact place in the docs? The NoneType code uses
_Py_HashPointer which returns the address of the PyObject* as hash. The
value may vary between platforms and compilers.

> Yes, anything that can be used as a dict key (basically all immutable
> values with equality comparison) should be hashable.

The __eq__ equality method is not related to the hash functions. But
__eq__ is very import to resolve hash collisions.

Christian

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


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread Martin v. Löwis
> I'd like to extend the proposal to Python 2.7 and later.

I don't object, but I also don't want to propose this, so
I added it to the discussion.

My (and perhaps other people's) concern is that 2.7 might
well be the last release of the 2.x series. If so, adding
this feature to it would make 2.7 an odd special case for
users and providers of third party tools.

> That's going to slow down Python package detection a lot - you'd
> replace an O(1) test with an O(n) scan.

I question that claim. In traditional Unix systems, the file system
driver performs a linear search of the directory, so it's rather
O(n)-in-kernel vs. O(n)-in-Python. Even for advanced file systems,
you need at least O(log n) to determine whether a specific file is
in a directory. For all practical purposes, the package directory
will fit in a single disk block (containing a single .pkg file, and
one or few subpackages), making listdir complete as fast as stat.

> Wouldn't it be better to stick with a simpler approach and look for
> "__pkg__.py" files to detect namespace packages using that O(1) check ?

Again - this wouldn't be O(1). More importantly, it breaks system
packages, which now again have to deal with the conflicting file names
if they want to install all portions into a single location.

> This would also avoid any issues you'd otherwise run into if you want
> to maintain this scheme in an importer that doesn't have access to a list
> of files in a package directory, but is well capable for the checking
> the existence of a file.

Do you have a specific mechanism in mind?

Regards,
Martin

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


Re: django model problem

2009-04-03 Thread Mark
> 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread Martin v. Löwis
Chris Withers wrote:
> Martin v. Löwis wrote:
>> I propose the following PEP for inclusion to Python 3.1.
>> Please comment.
> 
> Would this support the following case:
> 
> I have a package called mortar, which defines useful stuff:
> 
> from mortar import content, ...
> 
> I now want to distribute large optional chunks separately, but ideally
> so that the following will will work:
> 
> from mortar.rbd import ...
> from mortar.zodb import ...
> from mortar.wsgi import ...
> 
> Does the PEP support this? 

That's the primary purpose of the PEP. You can do this today already
(see the zope package, and the reference to current techniques in the
PEP), but the PEP provides a cleaner way.

In each chunk (which the PEP calls portion), you had a structure like
this:

mortar/
mortar/rbd.pkg (contains just "*")
mortar/rbd.py

or

mortar/
mortar/zobd.pkg
mortar/zobd/
mortar/zobd/__init__.py
mortar/zobd/backends.py

As a site effect, you can also do "import mortar", but that would just
give you the (nearly) empty namespace package, whose only significant
contents is the variable __path__.

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


confused with creating doctest in xmlrpc server

2009-04-03 Thread Krishnakant
hello all,
I am thinking of using the doctest module for my unit testing code in
python.
I have no problems doing this in usual classes but I am a bit confused
with my twisted based rpc classes.

given that I directly take the output of running functions on a python
prompt for the dockstrings, how do I get them for my twisted class which
has a published object?

What I mean is that in normal classes I would just start the python
prompt, import the module, create the object and run the methods to get
the output.

Then I take the output and put it into a file and then use those
dockstrings for my tests.
As you all know an rpc server app can't be run like this.  To my
knowledge an rpc server is a service that listens on a port on the given
ip address.

So how do I extract the dockstrings from the functions inside my xmlrpc
class?
obviously it is not run on a python prompt, so what is the solution?

happy hacking.
Krishnakant.




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


Re: [Python-Dev] PEP 382: Namespace Packages

2009-04-03 Thread Martin v. Löwis
> Perhaps we could add something like a sys.namespace_packages that would
> be updated by this mechanism?  Then, pkg_resources could check both that
> and its internal registry to be both backward and forward compatible.

I could see no problem with that, so I have added this to the PEP.

Thanks for the feedback,

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


Re: "Pythoner",Wish me luck!

2009-04-03 Thread barisa
On Apr 3, 8:58 pm, nrball...@gmail.com wrote:
> On Apr 3, 12:33 pm, barisa  wrote:
>
>
>
> > On Apr 3, 11:39 am, "Hendrik van Rooyen"  wrote:
>
> > > "Matteo"  wrote:
>
> > > On Apr 3, 9:05 am, Linuxwell  wrote:
>
> > > >> Starting today I would like to study Python,Wish me luck!
>
> > > >Good luck!
>
> > > >Don't forget to...
>
> > >  print 'Hello World!'
>
> > > This is better advice than what you may think,
> > > because the interactive interpreter is your very
> > > best friend when studying the language.
>
> > > You get there by typing "python" at the command
> > > line, and pressing enter.
>
> > > Using it, you will save yourself many hours of
> > > misunderstanding.
>
> > > - Hendrik
>
> > 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)
>
> I'm also a beginner in Python, but from my own experience the
> interactive interpreter is great for experimenting with new modules
> and output formatting because it allows you to see the immediate
> output of a function before you write it into your program.  The
> immediate result is that you'll see any errors and be able to fix them
> before they end up in your script.
>
> Nick Ballardhttp://90daysofpython.blogspot.com

thanks, i'll give it a try
--
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Apr 3)

2009-04-03 Thread Gabriel Genellina
QOTW:  "A programmer has to know the name of many data structures." - bearophile


Code organization: how to split a project into modules

http://groups.google.com/group/comp.lang.python/browse_thread/thread/56c320cea02796cc/

A speech generator, expert in leading-edge Web-based technologies:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/cc8013d5399dd65d/

Unladen-Swallow: a new runtime for Python based on LLVM

http://groups.google.com/group/comp.lang.python/browse_thread/thread/15f4f9bec82c80b9/

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ec66471ebe5948c6/

Why indexes start at 0, and ranges are semi-open?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ba73814384f7c0ef/

Advanced generator usage, a talk by David Beazley at PyCon2009:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/aacd809829d6b6ce/

Mercurial to be the new distributed version control system for Python

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1f99be59ea13bd22/

How to split a string at commas respecting quotes

http://groups.google.com/group/comp.lang.python/browse_thread/thread/aacac2d2a5c192e9/

Some tkinter design questions: why things are the way they are?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/75d3ce79c919b76d/

PEP 382: A proposal to add namespace packages

http://groups.google.com/group/comp.lang.python/browse_thread/thread/aebfb3311a2f5eb6/

Still discussing an ordered set implementation

http://groups.google.com/group/comp.lang.python/browse_thread/thread/90d818e016632a2c/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
The old Python "To-Do List" now lives principally i

Re: Hash of None varies per-machine

2009-04-03 Thread Dave Angel

ben.tay...@email.com wrote:

Found this while trying to do something unrelated and was curious...

If you hash an integer (eg. hash(3)) you get the same integer out. If
you hash a string you also get an integer. If you hash None you get an
integer again, but the integer you get varies depending on which
machine you're running python on (which isn't true for numbers and
strings).

This raises the following questions:
1. Is it correct that if you hash two things that are not equal they
might give you the same hash value? Like, for instance, None and the
number 261862182320 (which is what my machine gives me if I hash
None). Note this is just an example, I'm aware hashing integers is
probably daft. I'm guessing that's fine, since you can't hash
something to a number without colliding with that number (or at least
without hashing the number to something else, like hashing every
number to itself * 2, which would then mean you couldn't hash very
large numbers)
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.
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?

Bit esoteric perhaps, but like I said, I'm curious. ;-)

Ben

  
1. Most definitely.  Every definition of hash (except for "perfect 
hash") makes it a many-to-one mapping.  Its only intent is to reduce the 
likelihood of collision between dissimilar objects.  And Python's spec 
that says that integers, longs and floats that are equal are guaranteed 
the same hash value is a new one for me.  Thanks for making me look it up.


2. Nothing guarantees that the Python hash() will return the same value 
for the same object between implementations, or even between multiple 
runs with the same version on the same machine.  In fact, the default 
hash for user-defined classes is the id() of the object, which will 
definitely vary between program runs.  Currently, id() is implemented to 
just return the address of the object.


3. Normally, it's just mutable objects that are unhashable.  Since None 
is definitely immutable, it should have a hash.  Besides, if it weren't 
hashable, it couldn't be usable as a key in a dictionary.


All my opinions, of course.
DaveA

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


IIS python web application mapping issue - resolved

2009-04-03 Thread davidj411
i searched the internet for an hour , never found this info, and
figured it out myself.
posting this so that others won't have to look so hard.

ran across this issue and it seems that nobody really documented this
correctly on http://support.microsoft.com/kb/276494

in IIS i could not add the "python mapping" to the web mappings like
this:
"c:\\python.exe -u %s %s"


windows said the file does not exist, even when i unchecked the option
to make sure it exists (and it does exist!).

it would not allow the arguments, i.e. it allowed the mapping when i
just used "c:\\python.exe".

solution was to do it like this:
c:\\python.exe -u "%s %s"

making the arguments have there own set of quotes.


remember to also do the following
have web service extensions enabled for cgi.
register python using pyscript.py.

thanks!

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


Re: "Pythoner",Wish me luck!

2009-04-03 Thread Ravi Kumar
>
> Hi,
> I'm also begginer in python;
> i did few basic programs about graph etc..
>
> my question is : what benefit is using interactive intrepreter ?
>
>

the IDLE interractive python IDE is best comparing to any other most
advanced IDE available in world. Really, if you are learning the python at
any level, go for IDLE.

What you do, you write every step of statements and that is executed as soon
as you finish the block. So you have chance to understand the things step by
step. Just like learning by debugging..

Try it self, no one's review can satisfy you.

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


Re: "Pythoner",Wish me luck!

2009-04-03 Thread nrballard
On Apr 3, 12:33 pm, barisa  wrote:
> On Apr 3, 11:39 am, "Hendrik van Rooyen"  wrote:
>
>
>
> > "Matteo"  wrote:
>
> > On Apr 3, 9:05 am, Linuxwell  wrote:
>
> > >> Starting today I would like to study Python,Wish me luck!
>
> > >Good luck!
>
> > >Don't forget to...
>
> >  print 'Hello World!'
>
> > This is better advice than what you may think,
> > because the interactive interpreter is your very
> > best friend when studying the language.
>
> > You get there by typing "python" at the command
> > line, and pressing enter.
>
> > Using it, you will save yourself many hours of
> > misunderstanding.
>
> > - Hendrik
>
> 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)

I'm also a beginner in Python, but from my own experience the
interactive interpreter is great for experimenting with new modules
and output formatting because it allows you to see the immediate
output of a function before you write it into your program.  The
immediate result is that you'll see any errors and be able to fix them
before they end up in your script.

Nick Ballard
http://90daysofpython.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Goes Mercurial

2009-04-03 Thread Martin v. Löwis
 So what were these "strong antipathies" towards Git, exactly?
>>> i haven't read the article you link to, but compared to what i've read
>>> on
>>> dev "strong antipathies" sounds a bit over-hyped.
>> That was the phrase used by GvR.
> 
> well if you find any, please do report back.

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 (most of the
time including long sequences of hexdigits which I did not recognize,
or complaining about conflicts in long lists of files I knew I hadn't
touched at all). In some cases, I lost all my changes, and had to
do them all over again.

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


Re: Re: Best way to pickle functions

2009-04-03 Thread Dave Angel

Aaron Scott wrote:

Pickling the source code is much sturdier.  It's very unlikely that
the same code runs differently in different interpreters.  It's much
more likely that the same code runs the same, or not at all.



Okay, I've run into another problem. I've saved the code to a string,
so I can call it up when I need it. I want to keep these functions all
together, though, so I'm pushing them into a dictionary when I execute
it. It seems like when I put it in a dictionary, though, it messes up
the scope of the functions contained within. For example:

import cPickle
def Main():
holder =}
functiontest =def PickleTest():\n\tprint cPickle"
exec functiontest in holder
print holder["PickleTest"]()
Main()

... produces:

Traceback (most recent call last):
  File "pickletest.py", line 11, in 
Main()
  File "pickletest.py", line 9, in Main
print holder["PickleTest"]()
  File "", line 2, in PickleTest
NameError: global name 'cPickle' is not defined

Is there any way to do this so that the functions have access to the
higher scope?

Thanks.

  
Why not use import ?  Simply recreate the source file, if necessary, and 
import it again.


If you must import without it being in a clear text file, check out the 
deprecated imputil module, standard in 2.x, but removed in Python 3.0.  
And if you find some way to get __import__ or one of its relatives to 
work from a stream instead of a file, please let us know.



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


Re: minor revision encoded in SONAME in libpython.so

2009-04-03 Thread Martin v. Löwis
>> So no, no minor revision gets encoded into the SONAME.
> 
> Then what's the significance of the .1.0 at the end of the SONAME?  Is
> it just nipples for men?  (I hope no one objects to my extending the
> Monty Python theme to Time Bandits).

Some systems require that shared libraries have a version in their
SONAME, so we provide a version.

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


Re: HTML Generation

2009-04-03 Thread J Kenneth King
Stefan Behnel  writes:

> J Kenneth King wrote:
>> from tags import html, head, meta, title, body, div, p, a
>> 
>> mypage = html(
>>  head(
>>  meta(attrs={'http-equiv': "Content-Type",
>>  'content': "text/html;"}),
>>  title("My Page")),
>>  body(attrs={'background': "#ff;"},
>>  div(attrs={'id': "article-content"},
>>  p(a(attrs={'href': "http://python.org"},
>> "Python.org")
>> 
>> tabbed_file(mypage, open('myfile.html', 'w'))
>
> See here for another example that uses lxml.html:
>
> http://codespeak.net/lxml/lxmlhtml.html#creating-html-with-the-e-factory
>
> Stefan

Ah, looks good. Have never used nor finished the example I had given --
only meant as inspiration. I'm not surprised it has been done by someone
else.

I've been thinking about the co-routines presentation recently given at
Pycon and have been thinking about ways they could be used to extend the
grammar a bit.

At present, it looks like in my example and the lxml.html example that
the HTML structures created are declarative. Scripting the generation of
child elements for example would break up the flow...

code:


E.HTML(
E.HEAD(
E.TITLE("Best Page Evar!")
),
E.BODY(
E.H1(E.CLASS("best-articles-heading"), "Best Articles"),
E.UL(E.CLASS("articles"))
)
)

for article in articles:
E.HTML.BODY.UL.append(E.LI(article['title]))


... at least that's how I assume it would work.

I think in my prototype you could use list-comprehensions in-line to add
the elements, but it was quite an eyesore.

code:


my_html = html(
  head(
  title("Best Page Evar!")
  ),
  body(
  ul(
  [li(article['title']) for article in articles]
  )
  )
  )


I guess it's not that bad, but I had a feeling it could look prettier
like how naturally CL-WHO reads in Lisp. It's just that the list
comprehension doesn't read well in this context; it'd be more natural to
read it as "for each article in article, create a list element with the
article title" instead.

I get the impression that creating a chain of co-routines would reveal a
grammar for talking about generating web pages. Something like...

code:


html_to_file(
html(
head(
title("Best page evar")
),
body(
h1({'class': "underline-heading"},
   "Newest Articles"),
unordered_list(
articles,
['title', 'href'],
'%-10s: %s')
)
),
file=sys.stdout
)


Where `unordered_list` would walk the elements in its first argument,
extract the values from the keys specified by its second argument, and
format the results using the string from its third argument and simply
return a ul() object with nested li() objects with all the data inserted
into them.

Of course, this is very off-the-cuff; I only started picking up interest
in this old subject this morning. ;) I could be talking way out of my
ass here. No idea if any of it's even practical.

Anyway -- OP: there are many ways to approach HTML generation and it's a
good pursuit. If you come up with something new and unique, please
share! Down with templates! :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: "Pythoner",Wish me luck!

2009-04-03 Thread barisa
On Apr 3, 11:39 am, "Hendrik van Rooyen"  wrote:
> "Matteo"  wrote:
>
> On Apr 3, 9:05 am, Linuxwell  wrote:
>
> >> Starting today I would like to study Python,Wish me luck!
>
> >Good luck!
>
> >Don't forget to...
>
>  print 'Hello World!'
>
> This is better advice than what you may think,
> because the interactive interpreter is your very
> best friend when studying the language.
>
> You get there by typing "python" at the command
> line, and pressing enter.
>
> Using it, you will save yourself many hours of
> misunderstanding.
>
> - Hendrik

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


Re: Hash of None varies per-machine

2009-04-03 Thread Joshua Judson Rosen
Paul Rubin  writes:
>
> ben.tay...@email.com 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.

This is not true. CPython integers, at least up through the 2.x
series, are implemented as C *long integers*; on some platforms, this
means that they're 32 bits long. But on an increasing number of
platforms, long integes are 64 bits long.

But, more specifically, consider the following:

> > 2. Should the hash of None vary per-machine? 
> 
> If the docs say this shouldn't happen, then it's a bug.  Otherwise,
> it should probably be considered ok.
> 
> > 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?
> 
> Yes, anything that can be used as a dict key (basically all immutable
> values with equality comparison) should be hashable.

My recollection is that what you're seeing here is that, when hash()
doesn't have any `proper value' to use other than object-identity, it
just returns the result of id(). And id() is documented as:

 Return the "identity" of an object. This is an integer (or long
 integer) which is guaranteed to be unique and constant for this
 object during its lifetime. Two objects with non-overlapping
 lifetimes may have the same id() value. (Implementation note:
 this is the address of the object.)

So, not only is the return-value from id() (and hash(), if there's not
actually a __hash__ method defined) non-portable between different
machines, it's not even necessarily portable between two *runs* on the
*same* machine.

In practice, your OS will probably start each new process with the
same virtual memory-address range, and a given *build* of Python will
probably initialise the portion of its memory-segment leading up to
the None-object the same way each time, but

-- 
Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr.
--
http://mail.python.org/mailman/listinfo/python-list


Re: django model problem

2009-04-03 Thread Dave Angel

Mark wrote:

Hi,

Say I have these simple models:

class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)

class Album(models.Model):
artist = models.ForeignKey(Musician)
name = models.CharField(max_length=100)

  
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.



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


Re: Best way to pickle functions

2009-04-03 Thread Aaron Scott
Never mind. Solved the problem by putting the functions in a class and
dumping that into a string. Then, when I need it, I executed the
string to get myself the class, then created an instance of that class
which gave me access to those functions along with the correct scope.
Probably not the smartest solution, but it works for now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: A design problem I met again and again.

2009-04-03 Thread paul
一首诗 schrieb:
> 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?
Depends ;)

There are more ways to structure code than using classes. To avoid the
if-elif-elif-elif-else problem you could start using a dispatch table
which maps types to functions (fex using a dict)

start_methods = {
 'type1': startXX,
 'type2': startYY,
}

def start(type, id):
  func = start_methods.get(type, None)
  if func:
func(id)
  else:
raise ...

Or maybe look at trac's (http://trac.edgewall.com) use of Components and
Interfaces. Very lightweight and modular. You can start reading here:
http://trac.edgewall.org/browser/trunk/trac/core.py

cheers
 Paul

> 
> That's one reason why my interfaces grow fast.
> 
> On Apr 3, 1:51 am, Carl Banks  wrote:
>> On Apr 2, 8:02 am, 一首诗  wrote:
>>
>>> You get it.  Sometimes I feel that my head is trained to work in a
>>> procedural way.  I use a big class just as a container of functions.
>>> About the "data-based" approach, what if these functions all shares a
>>> little data, e.g. a socket, but nothing else?
>> Then perhaps your problem is that you are too loose with the
>> interface.  Do you write new functions that are very similar to
>> existing functions all the time?  Perhaps you should consolidate, or
>> think about how existing functions could do the job.
>>
>> Or perhaps you don't have a problem.  There's nothing wrong with large
>> classes per se, it's just a red flag.  If you have all these functions
>> that really all operate on only one piece of data, and really all do
>> different things, then a large class is fine.
>>
>> Carl Banks
> 
> --
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Hash of None varies per-machine

2009-04-03 Thread Paul Rubin
ben.tay...@email.com 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.

> 2. Should the hash of None vary per-machine? 

If the docs say this shouldn't happen, then it's a bug.  Otherwise,
it should probably be considered ok.

> 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?

Yes, anything that can be used as a dict key (basically all immutable
values with equality comparison) should be hashable.
--
http://mail.python.org/mailman/listinfo/python-list


platform.architecture, __path__, PYTHONPATH, and dist.utils

2009-04-03 Thread szager
Howdy,

I need to support both 32-bit and 64-bit versions of compiled python
modules that cannot be installed into the default search path of the
python interpreter(s).  I use PYTHONPATH to point to the module
installations, but I have a problem: I don't know, a priori, whether
the user will be running a 32-bit or 64-bit python interpreter.  So, I
would like to set up a hybrid installation that will be able to load
either version, based on the architecture of the currently-running
interpreter.

** How can I use dist.utils to create a hybrid installation of an
extension module? **

Currently, I'm manually hacking the build results, but my method is
very platform-dependent.  It would be nicer to have an automated,
platform-agnostic way to do this.

Here's what I'm doing now:

/path/to/foo/32bit/libfoo.so
/path/to/foo/64bit/libfoo.so

In /path/to/foo/__init__.py:

import os
import platform

# Note that I can't use platform.architecture(),
#   because that doesn't work when using embedded python
exe_arch = platform.architecture('/proc/self/exe')

__path__[0] = os.path.join(__path[0]__, exe_arch[0])

from libfoo import *



Thanks in advance,

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


Re: Best way to pickle functions

2009-04-03 Thread Aaron Scott
> Pickling the source code is much sturdier.  It's very unlikely that
> the same code runs differently in different interpreters.  It's much
> more likely that the same code runs the same, or not at all.

Okay, I've run into another problem. I've saved the code to a string,
so I can call it up when I need it. I want to keep these functions all
together, though, so I'm pushing them into a dictionary when I execute
it. It seems like when I put it in a dictionary, though, it messes up
the scope of the functions contained within. For example:

import cPickle
def Main():
holder = {}
functiontest = "def PickleTest():\n\tprint cPickle"
exec functiontest in holder
print holder["PickleTest"]()
Main()

... produces:

Traceback (most recent call last):
  File "pickletest.py", line 11, in 
Main()
  File "pickletest.py", line 9, in Main
print holder["PickleTest"]()
  File "", line 2, in PickleTest
NameError: global name 'cPickle' is not defined

Is there any way to do this so that the functions have access to the
higher scope?

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


Hash of None varies per-machine

2009-04-03 Thread ben . taylor
Found this while trying to do something unrelated and was curious...

If you hash an integer (eg. hash(3)) you get the same integer out. If
you hash a string you also get an integer. If you hash None you get an
integer again, but the integer you get varies depending on which
machine you're running python on (which isn't true for numbers and
strings).

This raises the following questions:
1. Is it correct that if you hash two things that are not equal they
might give you the same hash value? Like, for instance, None and the
number 261862182320 (which is what my machine gives me if I hash
None). Note this is just an example, I'm aware hashing integers is
probably daft. I'm guessing that's fine, since you can't hash
something to a number without colliding with that number (or at least
without hashing the number to something else, like hashing every
number to itself * 2, which would then mean you couldn't hash very
large numbers)
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.
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?

Bit esoteric perhaps, but like I said, I'm curious. ;-)

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


User or UserManager ? Problems of Observer Pattern

2009-04-03 Thread 一首诗
#This is a real world problem I met.
#
#We have a database containing serveral tables, like : user, role,
organization.  Each 2 of them has m:n relationships.  These relations
are stored in association tables.
#
#Not we have to load all these data in memory to gain higher
performances.  We create 3 classes , User, Role, Organization, to hold
these data.
#
#The question is : should I implement "add/delete/update" as methods
of User, or should I add another class UserManager?


#
# Choice 1
#

user_dict = {}
role_dict = {}

class User:
on_del_funcs = []
roles = []

def del(self):
user_dict.pop(self.name)

for f in self.on_del_funcs:
f(self)

# Using Observer Pattern to notify this user is deleted.
def addUserDelListener(self, on_del_func):
on_del_funcs.append(on_del_funcs)

def delUserDelListener(self, on_del_func):
on_del_funcs.remove(on_del_func)

class Role:

users = []

def addUsser(self, user):
self.users.append(user)
user.roles.append(self)
users.addUserDelListener(self.onUserDel)

def onUserDel(self, user):
self.users.remove(user)
user.delUserDelListener(self.onUserDel)

#
# 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)


# These codes are not complete, but that's enough to show my question.
# The first choice, which use Observer Pattern, has a very big
problem.
# When calling addUserDelListener, user got not only a callback
function, it
# also add reference count of role.  So when we want to delete a
role.  We have
# to carefully remove all *listener* hold by other objects, otherwise
this role
# will never be garbage collected.

# Not a big problem for only 2 classes.  But when there are 10
*subject* classes which
# Role want to *observe*, 10 listeners has to be removed when delete a
role.
# And if these *subject* have 5 different types of events, then 50
listeners has
# to be removed.

# Actually I tried this approach once, and it is still a big headache
for 10
# programmers. ( The company I worked at that time hate any change to
so-called
# working code )



# The second choice, which I am using right now, actually has nothing
to do with
# Object Oriented Designing.   The manager classes are not real
classes, just
# container of methods.   These User/Role classes are only container
of data,
# not behavior.
#
# For many times, I asked my self, "Is it too hard for me to see the
power of
# OO, or I have just never met a problem suitable for a OO resolution?"
--
http://mail.python.org/mailman/listinfo/python-list


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

2009-04-03 Thread gert
On Apr 3, 3:44 pm, "Gabriel Genellina"  wrote:
> En Thu, 02 Apr 2009 20:04:14 -0300, gert  escribió:
>
> > On Apr 2, 8:53 pm, Kushal Kumaran  wrote:
> >> On Thu, 2 Apr 2009 10:01:02 -0700 (PDT)
> >> gert  wrote:
> >> > from subprocess import *
> >> > check_call(['mode', 'COM1:9600,N,8,1,P'],shell=True)
> >> > while True:
> >> >     with open('com1', 'r') as f:
> >> >         for line in f:
> >> >              print(line)
>
> >> > This works very well except for one thing. After a reboot I have to
> >> > launch 1 time any windows serial exe application no mater with one,
> >> > that just opens an closes the com port, before i can launch this
> >> > script. The script keeps on working even after closing and reopening
> >> > it, until i reboot the pc. Then again I have to launch one time a
> >> > serial.exe and close it again. The exe does not run anything in the
> >> > background it just does something in windows python does not do when
> >> > it reads from the com port after a fresh reboot.
>
> >> > And i really appreciate it if somebody knew what it was.
>
> >> I don't know why you're getting this behaviour, but have you tried using
> >> a python library for accessing the serial port?  
> >> Seehttp://pyserial.wiki.sourceforge.net/pySerial.
>
> > I am sorry but I don't think pyserial will work on python3.x and I
> > also like to know whats going on before I consider it.
>
> A real Windows program accessing the serial port is likely to use  
> SetupComm, SetCommState, and other functions in addition to CreateFile.
> Seehttp://msdn.microsoft.com/en-us/library/aa363196(VS.85).aspx
>
> pySerial takes care of all those details, as suggested.
>
> > Maybe its a bug in open() on windows?
>
> open() doesn't care about the file name; it's the OS that interprets  
> "com1" as a serial port.

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.

Also I can not imaging activating a com port wouldn't be possible with
a check_call dos instruction. I can already configure com with mode.

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


Re: python needs leaning stuff from other language

2009-04-03 Thread Mel
Steven D'Aprano wrote:

> On Fri, 03 Apr 2009 11:41:10 -0400, Mel wrote:
> 
>> Ben Finney wrote:
>> 
>>> I think it would also be better to have One (and prefereably Only One)
>>> Obvious Way To Do It. That obvious way, for those who work with
>>> Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
>>> ‘list’ conform with this also.
>> 
>> Does that mean a one-off special case rule to forbid slices having a
>> default?
> 
> Why would it do that?

Well, if list.clear were truly and strictly to be the only way to clear the 
contents of a list, then assigning nothing via the default slice would have 
to be ruled out.  `somelist[:] = []` is just a special case of assignment to 
a slice generally.

Mel.


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


Re: python for loop

2009-04-03 Thread Aaron Brady
On Apr 3, 10:43 am, alex23  wrote:
> On Apr 3, 10:36 pm, Lou Pecora  wrote:
>
> >  Aaron Brady  wrote:
> > > Did I tell you guys that 'natural' has 38 definitions at
> > > dictionary.com?
>
> > Amazing.  I suggest you pick the one that fits best.
>
> You mean the one that feels most natural?

No, not feels.  *Is*.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to pickle functions

2009-04-03 Thread Aaron Brady
On Apr 3, 11:04 am, Aaron Scott  wrote:
> I have a number of functions that I need to pickle without necessarily
> knowing their names in advance. My first thought was to put all the
> functions in a class, then pickle the class, but it doesn't really
> work like I expected it to.
>
>         import cPickle
>         class PickleClass:
>                 def Awesome(self):
>                         pass
>         stored = cPickle.dumps(PickleClass)
snip
> So, the class itself isn't being pickled, just an instance of it.
>
> This being the case, what's the best way to store these functions?
> Maybe dump the class to a string and pull them back with an exec
> statement when I need them?

All pickling a class does is pickle its module and name.  You can't
pickle functions in principle because byte-code is sensitive and
volatile, and is least likely to run consistently later on.  'pickle'
is not just for serialization, it's for persistence.

Pickling the source code is much sturdier.  It's very unlikely that
the same code runs differently in different interpreters.  It's much
more likely that the same code runs the same, or not at all.

It's better yet to just get the source from the original place every
time: instead, pickle a file name and open the file.
--
http://mail.python.org/mailman/listinfo/python-list


Re: A design problem I met again and again.

2009-04-03 Thread Emile van Sebille

andrew cooke wrote:

Emile van Sebille wrote:

Whether you (generic you) choose to do so or not is a separate issue.

Also agreed - and that is really my point.  Doing so feels to me like
continuing to look for a lost object once you've found it.


i can see your point here, but there's two things more to consider:

1 - if you do need to refactor it later, because there is a bug say, it
will be harder to do so because you will have forgotten much about the
code.  


Yes, I generally count on it.  Refactoring at that time is precisely 
when you get the most benefit, as it will concisely focus your 
attentions on the sections of code that need to be clearer to support 
the debugging changes.  Face it, you'll have to get your head around the 
code anyway, be it 1, 5, or 10k lines and all beautifully structured or 
not.  Remember, proper refactoring by definition does not change 
functionality -- so that bug in the code will be there regardless.



so if it is likely that you will need to refactor in the future, it
may pay to do some of that work now.


Certainly -- and I envy those who know which sections to apply their 
attentions to and when to stop.  Personally, I stop when it works and 
wait for feedback.



2 - if someone else needs to work with the code then the worse state it is
in - even if it works - the harder time they will have understanding it. 
which could lead to them using or extending it incorrectly, for example.


Assuming you're talking about non-refactored code when you say worse, 
consider Zope vs Django.  I have no doubt that both meet an acceptable 
level of organization and structure intended in part to facilitate 
maintenance.  I've got multiple deployed projects of each. But I'll hack 
on Django if it doesn't do what I want and I find that easy, while 
hacking on Zope ranks somewhere behind having my mother-in-law come for 
a three-week stay on my favorite-things-to-do list.  Refactored code 
doesn't necessarily relate to easier understanding.



both of the above fall under the idea that code isn't just a machine that
produces a result, but also serves as documentation.  and working code
isn't necessarily good documentation.


Here I agree.  Once I've got it working and I have the time I will add 
minor clean up and some notes to help me the next time I'm in there. 
Clean up typically consists of dumping unused cruft, relocating imports 
to the top, and adding a couple lines of overview comments.  On the 
other hand, I do agree with Aahz's sometimes tag line quote accepting 
all comments in code as lies.  It's akin to believing a user -- do so 
only at your own peril.  They're really bad witnesses.



i don't think there's a clear, fixed answer to this (i don't think "stop
refactoring as soon as all tests work" can be a reliable general rule any
more than "refactor until it is the most beautiful code in the world" can
be).  you need to use your judgement on a case-by-case basis.


Well said.


in fact, the thing i am most sure of in this thread is that 15000 lines of
code in one module is a disaster.  


Agreed.  I took a quick scan and the largest modules I'm working with 
look to be closer to 1500 lines.  Except tiddlywiki of course, which 
comes in at 9425 lines in the current download before adding anything to 
it.  I bet I'd prefer even hacking that to zope though.


One programmer's disaster is another programmer's refactoring dream :)

Emile


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


Best way to pickle functions

2009-04-03 Thread Aaron Scott
I have a number of functions that I need to pickle without necessarily
knowing their names in advance. My first thought was to put all the
functions in a class, then pickle the class, but it doesn't really
work like I expected it to.

import cPickle
class PickleClass:
def Awesome(self):
pass
stored = cPickle.dumps(PickleClass)
del PickleClass
restored = cPickle.loads(stored)

Results:

Traceback (most recent call last):
  File "pickletest.py", line 7, in 
restored = cPickle.loads(stored)
AttributeError: 'module' object has no attribute 'PickleClass'

So, the class itself isn't being pickled, just an instance of it.

This being the case, what's the best way to store these functions?
Maybe dump the class to a string and pull them back with an exec
statement when I need them?
--
http://mail.python.org/mailman/listinfo/python-list


django model problem

2009-04-03 Thread Mark
Hi,

Say I have these simple models:

class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)

class Album(models.Model):
artist = models.ForeignKey(Musician)
name = models.CharField(max_length=100)


Now in `Musician` I want to add a field "last_album". 
How can I do that? I'd like to be able to write:

m = Musician(pk=1)
print m.last_album.name

When I try:
last_album = models.OneToOneField(Album)
it somehow works but creates a (useless) unique index for last_album.
And I don't need additional related field in the Album model (it's also
created now).


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


Re: python needs leaning stuff from other language

2009-04-03 Thread Steven D'Aprano
On Fri, 03 Apr 2009 11:41:10 -0400, Mel wrote:

> Ben Finney wrote:
> 
>> I think it would also be better to have One (and prefereably Only One)
>> Obvious Way To Do It. That obvious way, for those who work with
>> Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
>> ‘list’ conform with this also.
> 
> Does that mean a one-off special case rule to forbid slices having a
> default?

Why would it do that?


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


Re: python needs leaning stuff from other language

2009-04-03 Thread Steven D'Aprano
On Fri, 03 Apr 2009 08:23:22 -0700, Zamnedix wrote:

> On Apr 2, 3:25 pm, online.serv...@ymail.com 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
--
http://mail.python.org/mailman/listinfo/python-list


Re: python for loop

2009-04-03 Thread alex23
On Apr 3, 10:36 pm, Lou Pecora  wrote:
>  Aaron Brady  wrote:
> > Did I tell you guys that 'natural' has 38 definitions at
> > dictionary.com?
>
> Amazing.  I suggest you pick the one that fits best.

You mean the one that feels most natural?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python needs leaning stuff from other language

2009-04-03 Thread Mel
Ben Finney wrote:

> I think it would also be better to have One (and prefereably Only One)
> Obvious Way To Do It. That obvious way, for those who work with
> Python's ‘set’ and ‘dict’, is a ‘clear’ method. It seems best to have
> ‘list’ conform with this also.

Does that mean a one-off special case rule to forbid slices having a 
default?

Mel.


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


Re: Sending SMS using python script

2009-04-03 Thread Craig
There's a Python wrapper to the Skype API here:
http://sourceforge.net/projects/skype4py/
On Linux I've used the PyGTK GUI that uses this. It's called
SkySentials here:
http://www.kolmann.at/philipp/linux/skysentials/

Craig

On Apr 3, 6:50 am, "ISF (Computer Scientists without Frontiers,
Italy)"  wrote:
> On 2 Apr, 06:41, guptha  wrote:
>
>
>
> > hi group,
> > my application needs to sendSMSoccasionally to all the clients  .Is
> > there any library in python that supports in sendingSMS.
> > I like to conform few information i gathered in this regard.
>
> > I can sendSMSby two ways
>
> > 1. SendingSMSusing Email clients
> > 2. Usingsmsgateway to send message(we can implementSMSGateway API
> > 's ,provided by vendor and ,sendSMS-- we will be charged
> > accordingly )
>
> > In case of First approach
> > 1. We can make use of libgamil library to sendSMSusing gmail ( I
> > ref :http://blog.datasingularity.com/?p=63)
> > i suppose sendingsmsthrough gmail is not supported in India
> >  2. Can we use Skype4py library,
>
> > In case of second approach
> > 1. Is there any way to sendSMSfor free inside India ,or ,Any freeSMSgateway 
> > providers in India
> > Any information regarding this is appreciable
> >   Thanks
>
> A friend from India sent me this hint:
>
> the following link can be explored further for sending SMS on pyS60
> (python for symbian OS)http://mobilenin.com/pys60/menu.htm
>
> wkr,
> Aldo

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


Re: python needs leaning stuff from other language

2009-04-03 Thread Zamnedix
On Apr 2, 3:25 pm, online.serv...@ymail.com 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.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >