Re: A Universe Set

2006-10-04 Thread MonkeeSage
Jorgen Grahn wrote:
> - infinite xrange()s

Fun. How about in-memory objects which use no memory, and
self-referential anonymous functions, and object states without
objects...

Regards,
Jordan

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


Subclassing built-in classes

2006-10-05 Thread MonkeeSage
I know that python doesn't allow extending built-in objects like the
str class; but you can subclass them using a class of the same name and
thus shadow them to get the same general effect (albeit you have to use
the explicit constructor rather than literals).

class str(str):
  def display(self):
print self
str('blah').display()

I was just playing around and realized that assigning to
__builtins__.str (or if you prefer sys.modules['__builtin__'].str) has
the same effect.

class mystr(str):
  def display(self):
print self
__builtins__.str = mystr
str('blah').display()

So that made me wonder...couldn't python (in theory) allow for literals
to use extended classes by using the object in __builtins__. as
the class for literals? By default it would be the standard base class,
but it could also be a custom subclass. Would that be possible / easy /
worthwhile to do?

Regards,
Jordan

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


Re: Subclassing built-in classes

2006-10-05 Thread MonkeeSage
Steve Holden wrote:
> Unfortunately the literals are interpreted during bytecode generation,
> before the compiled program is available, and your modifications to
> __builtns__ haven't been made, so the answer is "no", I'm afraid.

Ah! That makes sense. I guess the only way to do it would be to add an
extra bit to every object to indicate whether it was constructed
literally and then re-initialize the object after compilation if that
bit is set. For some reason I just don't think that's gonna happen. ;)

Thanks for taking the time to explain.

Regards,
Jordan

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


Re: Asychronous execution *with* return codes?

2006-10-05 Thread MonkeeSage
utabintarbo wrote:
> pid = subprocess.Popen([app] + lstArgs).pid

Check out the poll() method and the returncode attribute:
http://docs.python.org/lib/node533.html

Regards,
Jordan

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


Re: building strings from variables

2006-10-05 Thread MonkeeSage
wesley chun wrote:
> from the performance standpoint, i believe that #4 (list join) from
> scott is the fastest. #1 (string formatting) is next preferred only
> because #3 (string concat) is the worst [think "realloc()"].  #2 is
> useful for when you have users who aren't as comfortable with #1.

I might have done something wrong here, but it looks like the %
operator would be the fastest (negligibly). And string.Template is
horribly slow(!).

import os, sys, string, timeit

hl = [['working_dir', os.getcwd()],
  ['ssh_cmd', 'ssh'],
  ['some_count' , 5],
  ['some_param1', 'cheese'],
  ['some_param2', 'burger']]

hd = dict(hl)
ht = tuple(map(lambda x: x[1], hl))
sys.modules['__main__'].__dict__.update(hd)

def make_string_fmt():
  out = "cd %s ; %s %d %s %s" % ht
def make_string_cat():
  out = "cd "+working_dir+" ; "+ssh_cmd+" "+str(some_count)+" "+\
some_param1+" "+some_param2
def make_string_lst():
  out = ' '.join(["cd", working_dir, ";", ssh_cmd,
 str(some_count), some_param1, some_param2])
def make_string_tmp():
  out = string.Template("cd $working_dir ; $ssh_cmd"
"$some_count $some_param1 $some_param2")\
   .substitute(hd)

print "String formatting time:"
print timeit.Timer("make_string_fmt()",
   "from __main__ import make_string_fmt").timeit()
print "String concatination time:"
print timeit.Timer("make_string_cat()",
   "from __main__ import make_string_cat").timeit()
print "List join time:"
print timeit.Timer("make_string_lst()",
   "from __main__ import make_string_lst").timeit()
print "Template substitution time:"
print timeit.Timer("make_string_tmp()",
   "from __main__ import make_string_tmp").timeit()



Output:

String formatting time:
4.62050509453
String concatination time:
5.90371489525
List join time:
6.72425699234
Template substitution time:
66.4205350876

Regards,
Jordan

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


Re: building strings from variables

2006-10-05 Thread MonkeeSage
Ps. For readability you can also roll your own sprintf function:

def format(s, *args, **kwargs):
  if args:
return s % args
  elif kwargs:
return s % kwargs
  else:
return s

s = 'I like %s and %s.'
print format(s, 'ham', 'cheese')

s = 'I like %(b)s and %(c)s.'
print format(s, b='butter', c='eggs')

> Regards,
> Jordan

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


Re: Metaprogramming question

2006-10-05 Thread MonkeeSage
Steve Menard wrote:
> So my question is, how to replicate new.instance() functionality with new
> classes?

class A(object):
  def __init__(self):
print "Class A"
A()
A.__new__(A) # <- this one

Regards,
Jordan

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


Re: printing variables

2006-10-05 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> Thanks all for the answers. Yup, i think i will use dicts/tuples/lists
> instead...

Even though you should be using some kind of container, you can still
do what you origianlly asked for with relative ease...you just have to
use the evil eval function (gasp!):

for i in xrange(5):
  if i == 0: continue
  print eval("var%d" % i)

Regards,
Jordan

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


Re: help on pickle tool

2006-10-05 Thread MonkeeSage
hanumizzle wrote:
> Why a subset?

I don't think JSON is a subset of YAML.

Regards,
Jordan

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


Re: help on pickle tool

2006-10-05 Thread MonkeeSage


On Oct 6, 1:06 am, hanumizzle <[EMAIL PROTECTED]> wrote:
> I'm happy with my Pythonesque YAML syntax, thank you. :)

YAML is a little more complex, and a little more mature. But JSON
should not be ruled out. I actually like JSON personally.

Regards,
Jordan

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


Re: help on pickle tool

2006-10-05 Thread MonkeeSage


On Oct 6, 1:28 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> when did you last look at the spec?

I'm fairly versed in JS objects, having written 10 or so extensions for
firefox; but I've only used YAML for trivial tasks like config files.
So I can't really say how they stack up in "the big picture". But from
what I have seen, JSON is a simpler and easier to use format than YAML.

Regards,
Jordan

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


Re: Subclassing built-in classes

2006-10-06 Thread MonkeeSage


On Oct 6, 4:58 am, Maric Michaud <[EMAIL PROTECTED]> wrote:
> As the first post said "...couldn't python (in theory)...", I was discussing
> if it would be possible for python (in some future version) to manage the
> literals so that they use the constructors in the __builtin__ module, I
> didn't say it works actually (I'm aware it's not the case).

Hi Maric,

I think the problem Steve was pointing out is this: how do you make a
literal use a constructor that is not available until *after* the
literal has been constructed? In other words, python currently does
this: 1) parses plaintext into bytecode (at which point literals are
constructed), 2) executes bytcode (at which point custom constructors
are available). The only way I can see to do what I asked is to, during
bytecode compilation, mark a literal in the AST as being a literal (+1
bits, at least, on every literal until it is constructed) but not
actually constructing it until the point of execution (+? time to go
back through the object space looking for marked objects and
constructing them). I don't know enough about python internals to know
if that would be a problem, but I seriously doubt it would be
implemented without some pressing use cases. So it is possible, but
probably not plausible.

Regards,
Jordan

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


Re: Names changed to protect the guilty

2006-10-06 Thread MonkeeSage


On Oct 6, 6:27 pm, [EMAIL PROTECTED] (Aahz) wrote:
> The following line of lightly munged code was found in a publicly
> available Python library...

Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh),
which was written by the very finger of God when the world was still in
chaotic darkness. But I guess I'm an atheist when it comes to PEP 8. If
it is clearer to you to make the condition explicit ("blah not False"),
rather than implicit ("not blah"), then use the former. I say write the
code the way *you* (and your team if applicable) are best able to read,
write and maintain it. Then when other people tell you that it isn't
good style, or isn't "pythonic," just stab them in the face with
soldering iron ala Chris Walken. :)

Regards,
Jordan

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


Re: Names changed to protect the guilty

2006-10-06 Thread MonkeeSage


On Oct 6, 8:02 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
> it is clearer to you to make the condition explicit ("blah not False"),

"blah not False" -> "blah is False"

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


Re: Names changed to protect the guilty

2006-10-06 Thread MonkeeSage

On Oct 6, 8:34 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> And in the original case, I'd agree that "if X.has_key():" is
> quite clear, already yielding a boolian value, and so doesn't
> need to be tested for if it's False. But I wouldn't like to test
> for an empty list or for None implicitly.

I agree that predicates are explicit in themselves, if they are named
intuitively like "has_key". I assumed that the OP was upset about "is
False" not that an explicit check was done on a predicate method.

On Oct 6, 8:38 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> It's not about style or being pythonic: a condition may be false, but
> not the False object itself, so writing
> if something is False:
> is the wrong way to test if something is false (isn't clear? :) )

Yes, I understand, and it's true that in a mixed context it could bite
you (or you could check equality rather than identity), but assuming a
strictly boolean context you don't have that problem (or perhaps you
even *want* to differentiate between False, None and 0 in a mixed
context).

Ps. I mostly use the "if (not) cond" form. But I take the style guide
as a, well, *guide*, rather than a style *law* and I tend to get
annoyed when people get religious about things like that. Subjective
taste, be it GvR's or the Pope's, is -- subjective. On the other hand,
if lightening is flashing and seas are parting and stuff, I don;t tend
to argue too much in that case. ;)

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-06 Thread MonkeeSage


On Oct 6, 8:23 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> if 2 in [1,2,3]: print "Use the same (in) operator"
> elif 'E' in ('E','r','i','k'): print "Works for any sequence"
> elif 'o' in 'hello': print "Even strings"

This isn't really analogous is it? For "somedict.has_key(k)" or "k in
somedict", you don't need to know the value of somedict[k] ahead of
time. So you can avoid KeyError by asking if the key exists first
before trying to get the value. Wouldn't that be more like this for
lists (and other sequences):

def has_index(seq, index):
  try:
seq[index]
return True
  except IndexError:
return False

I've often wondered why there is no built-in method like that for
sequence objects. And also why not the equivalent of dict.get for other
sequences:

def get(seq, index, default=None):
  if has_index(seq, index):
return seq[index]
  else:
return default

Seems useful...

Regards,
Jordan

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


Re: problem with split

2006-10-06 Thread MonkeeSage


On Oct 6, 11:33 pm, hanumizzle <[EMAIL PROTECTED]> wrote:
> import re
>
> 
>
> if line.startswith('instr'):
>   p = re.compile(r'(\d+)\s+;(.*)$')
>   m = p.search(line)
>
> return (m.group(1), m.group(2))

You probably don't want startswith, in case there are initial spaces in
the line. Also, since the regexp is single use, you can just use the
re.search class method, which will compile the regexp implicitly. May
also want to strip the second grouped match, in case of trailing
spaces.

if 'instr' in line:
  m = re.search(r'(\d+)\s+;(.*)$', line)
  if m:
return (m.group(1), m.group(2).strip())

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage


On Oct 7, 3:27 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> The meaning comes from the most common usage.

I wasn't suggesting that the "in" keyword have a different sematic for
sequence types. I was just saying that regarding the question whether
there is anything similar to "dict.has_key / k in dict" for lists, the
"in" keyword is not semantically analogous.

> Because it's not needed at all: valid sequence indexes are *exactly*
> range(len(seq)). This is the basic point of being a sequence: when
> indexes are not contiguous, in fact you have a mapping, not a sequence.

True. But valid dictionary keys are exactly d.keys(). The has_key
method is just sugar.

> Sometimes, maybe... But since you can write it efficientely in a few
> lines when needed, I don't see the need to put it into the core language.

Couldn't the same be said for dictionaries? I could write for
sequences:

if index < len(seq) and seq[index]: ...

But I could also write for dictionaries:

if key in dic.keys() and dic[key]: ...

I just wonder why the syntactic sugar was added for dicts, but not for
sequence types.

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage

On Oct 7, 12:37 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> for what?

  key in self.keys()

And d.get() looks like sugar for:

  if self.has_key(key):
return self[key]
  else:
return default_value

Why not have the same sugar for sequence types? E.g.,

  def has_index(self, index):
return index < len(self)

  def get(self, index, default=None):
if self.has_index(index):
  return self[index]
return default

I understand not wanting to add bloat without use cases and / or  when
the programmer can easily implement the functionality themselves; but I
don't see why the sugar would be added for dict but not sequence types.
The fact of easy implementation by the programmer without the
convenience method is the same in both cases, and I would assume (but
don't claim to know) that one could find many use cases for, e.g.,
list.has_index() / . get().

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage


On Oct 7, 7:14 pm, Duncan Smith <[EMAIL PROTECTED]> wrote:
> No.  The above constructs a list of keys and searches the list for the
> key, O(n).  "key in somedict" is a lookup, O(1).

My point wasn't in regard to implementation details, but in regard to
convenience methods. Obviously the sugary dict methods are tweaked for
the best performance (one would hope!), as would be sugary sequence
methods were they to be added. What I was wondering is why
dict.has_key() and get() are there but not list.has_index() and get().

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage

On Oct 7, 7:41 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Are you just making a philosophical point? In which case I agree: *if* you
> make the analogy "a dictionary key is analogous to a sequence index",
> *then* the operation of "in" isn't semantically analogous between mappings
> and sequences. But why should it be?

It shouldn't, and I'm making a pragmatic (not merely philosophic) point
regarding the OP's question whether there is a "similar" list method to
dict.has_key.

> In both mappings and sequences, "in" tests for membership. But *what* it
> tests for membership is different. There's no shame there.

I know / agree.

> Originally, if you wanted to
> test for key membership with a dict, you had three choices:

I know.

On Oct 7, 7:59 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> Because they aren't needed often, and when they are, they are easy to
> implement?

More often and easier to implement than dict.has_key / get?

> It is hard to see where list.get(index, default) would be useful, since
> accessing an index out of range of a list is generally an error, unlike
> accessing a missing key.

Uh, no. KeyError.

> But I like symmetry, and for symmetry I wouldn't
> object to sequences gaining a get method too. Not that I care about it
> enough to put in a feature request or a PEP, but if somebody else did, I
> wouldn't object.

Me neither. :)

> get() is easy enough to implement. Feel free to turn it into a method
> of a collection class if you like.

I already did, see previous posts.

> Not every piece of functionality needs to be a built-in.

Agreed. but why implement a certain functionality in one place but
leave it out of another?

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage


On Oct 7, 8:06 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
> More often and easier to implement than dict.has_key / get?

More -> Less

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


Re: Can't get around "IndexError: list index out of range"

2006-10-08 Thread MonkeeSage

On Oct 8, 5:57 am, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> No, *less* often. That's the point -- it is fairly common for people to
> want dictionary lookup to return a default value, but quite rare for them
> to want sequence lookup to return a default value. A sequence with a
> default value would be, in some sense, equivalent to an infinite list:

Ah, yes. Infinite dictionaries are much better! I guess you could think
of it like providing a infinitely indexed list (or infinitely keyed
dict), but a better way to think of it is as providing a
non-terminating exception where the default value is the exceptional
case. And I don't see why it would be so rare to do something like:

if sys.argv.get(1): ...

With list.has_index() / get(), the following (pretty common I think)
idiom:

try:
  data = some_unknown_seq[2]
except IndexError:
  data = None
if data: ...

Can become:

data = some_unknown_seq.get(2)
if data: ...

Perhaps list.get() wouldn't be used as often as dict.get(), but it
would be used a fair amount I think. Looking at the standard library
(2.5 source), I find 30 places where "except IndexError" appears, and
two places where a comment says that some method "raises IndexError" on
some condition. I haven't looked at the context of them, but I'd wager
that many of them would benefit from list.has_index() and / or get().
Here is my script to search the libs:

import os, re
found = {}
for path, dirs, files in os.walk('./Lib'):
  for afile in files:
afile = open(os.path.join(path, afile))
lines = afile.readlines()
afile.close()
for line in lines:
  match = re.search(r'((except|raises) IndexError)', line)
  if match:
found[afile.name] = match.group(1)
for item in found.items():
  print '%s (%s)' % item
print 'Found %d matches' % len(found)

> dict.get() doesn't raise KeyError. That's the whole point of get(), it
> returns a default value instead of raising KeyError.

Right. Exactly. Accessing a non-existent key raises a KeyError, but
dict.get() short-curcuits the exception and gives you a default value
(which is None unless explicitly changed). So instead of trying the key
and catching a KeyError, you can use a simple conditional and ask if
d.has_key(key), or assign d.get(key) and test the assignee. So, why
isn't there a list.has_index() / get()?

> If you don't care enough to even make a formal feature
> request, let alone a PEP, then why should people who care even less
> actually write the code?

I'm thinking about it. I just wanted to see if anyone knew of, or could
come up with, a good reason why it isn't / shouldn't be there.
Apparently not (at least not one that doesn't also bite the dict
convenience methods), so I'll probably go ahead and make a feature
request in the next few days.

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-08 Thread MonkeeSage

On Oct 8, 1:44 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> but "let's hypergeneralize and treat sequences and mappings as the same
> thing" proposals are nothing new; a trip to the archives might be help-
> ful.

Huh? I don't want to treat sequences and mappings as the same thing.
I'm talking about adding two similar convenience methods for sequences
as already exist for mappings. That may make the two APIs closer, but
that's not necessarily a bad thing (think the square-bracket accessor).
Besides, has_index is sufficiently different already. If it's really a
problem, change get() to at() for sequences. seq.at(2).

So far the reasons offered against adding those convenience methods
are:

Reason: It's unnecessary / bloat.
- Then the same thing is true of the dict methods.

Reason: It's not useful.
- I know of several use cases and could probably find others.

Reason: It takes effort to implement it. Why don't you do it yourself
if it's such a great idea!
- Mabye I will. But that is only a reason why they aren't currently
implemented, not why they *shouldn't* be.

Reason: It makes sequences and mapping to much alike.
- Then change the names for the sequences methods.

That is to say, no good reason has been offered for why these methods
shouldn't be implemented.

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-08 Thread MonkeeSage

On Oct 8, 3:05 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> No: you are proposing to add features to the sequence interface for
> which there are few demonstrable use cases.

If I really wanted to find them, how many instances do you think I
could find [in the standard lib and community-respected third-party
libs] of sequence index checking like "if 2 < len(seq)" and / or
try-excepting like "try: seq[2] ..."? Judging by the fact that there
isn't any other way to *safely* handle dynamic sequences (esp.
sequences which grow based on side-effects which may or may not be
present, depending on the execution path through the code); I'd guess
the number is alot higher than you seem to think.

> Well I certainly didn't find your last one particularly convincing: the
> attempt to reference a non-existent sequence member is almost always a
> programming error.

Unless you are interacting with user input, or other anomalous data
source. And in that case you need to do explicit index checking or wrap
your code with a try...except; that or you need a convenience function
or method that implements a non-terminating exception, and you just
check for the exceptional case, like dictionaries have with get(). I
find the latter approach to be easier to read and write (see link
below), as well as understand.

> I would argue exactly the opposite: the reason why they shouldn't be
> implemented is because no good reason has been presented why they *should*.

Pretend like there are no dict.has_key and dict.get methods. Can you
provide a good reason(s) why they should be implemented? Not necessity
-- since you can do the same thing more verbosely. Usefulness? --
Probably; but I think the list methods would also be useful (see
above). Succinctness [1]? -- The list methods have the same advantage.
Anything else?

[1] http://mail.python.org/pipermail/python-dev/1999-July/000594.html


On Oct 8, 3:11 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> > Huh? I don't want to treat sequences and mappings as the same thing.
> > I'm talking about adding two similar convenience methods for sequences
> > as already exist for mappings.so what makes you think you're the first one 
> > who's ever talked about that?

I looked yesterday and only found a few posts. A couple involved
Marc-Andre Lemburg, and mxTools, where he has a get() function that
works for sequences and mappings; that's not what I'm suggesting.
However, I found one from 1997 where he mentioned a patch to python 1.5
which added list.get, but I couldn't find the patch or any discussion
of why it was (presumably) rejected. The only other post I found that
was relevant was one on the dev-python list (mentioned in the July 1-15
summery [1]). And the only thing mentioned there as a reason against it
is that "It encourages bad coding. You
shouldn't be searching lists and tuples like that unless you know what
you're doing." (Whatever that is supposed to mean!).

Just point me to the discussion where the good reasons (or any at all)
against my suggestion can be found and I'll be glad to read it. I
couldn't find it.

[1]
http://www.python.org/dev/summary/2006-07-01_2006-07-15/#adding-list-get-and-tuple-get

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-09 Thread MonkeeSage

On Oct 9, 2:31 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Keep right on guessing.

I hope I'm not offending one whom I consider to be much more skilled
and versed than I am, not only in python, but in programming in
general; but I must say: it seems you are being rather obtuse here. I
think I laid out the principal clearly enough, and I know you have the
mental capacity to extrapolate from the principal to general use cases.
But even so, here is a simple use case from the standard library
(python 2.5 release source):

In Libs/site.py, lines 302-306:

try:
for i in range(lineno, lineno + self.MAXLINES):
print self.__lines[i]
except IndexError:
break

With my proposal, that could be written as:

for i in range(lineno, lineno + self.MAXLINES):
if self.__lines.has_index(i):
print self.__lines[i]
else:
break

Granted, in this particular case the amount of code is not reduced, but
(and I would hope you'd agree) the control flow is certainly easier to
follow.

> OK, so now we appear to be arguing about whether a feature should go
> into Python because *you* find it to be easier to read and write. But I
> don't see a groundswell of support from other readers saying "Wow, I've
> always wanted to do it like that".

*Someone* (other than me!) obviously found it nice to have the dict
convenience methods. As for garnishing support, I almost see that as
more of a cultural, rather than pragmatic issue. I.e., if it's not
there already, then it shouldn't be there: "what is is what should be".
Of course, consistently following that naive presumption would totally
stiffle *any* extension to python. However, (I think) I do understand
the psychology of the matter, and don't fault those who cannot see past
what already is (not meaning to implicate you or Fredrick or anyone
else -- the comment is innocent).

> In fact d.has_key(k) is a historical spelling, retained only for
> backwards compatibility, of k in dict. As to the d.get(k, default)
> method I really don't see a compelling use case despite your
> protestations, and I don't seem to be alone. Please feel free to start
> recruiting support.

As I stated to another poster; I'm not really concerned with
implementation details, only with the presence or absence of
convenience methods. You can write "if k in d" as easily as "if index <
len(seq)". But semantically, they are similar enough, in my (admittedly
lowly) estimation, to desevere similar convenience methods.

> The fact that nobody has listed the good reasons why I shouldn't try to
> make a computer from mouldy cheese doesn't make this a good idea.

Heh. True. I didn't mean to imply that I was arguing from the negative.
I was only tring to shift the perspective to include the reasons for
the dict convenience methods. If C is good for A, and A is sufficiently
similar to B, then C is good for B. But if C is just crud, then forget
it all around. ;)


On Oct 9, 12:24 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> But how do you handle the case of:
>
> l = []
> i = 10
>
> l[i] = l.get(i, 0) + 1

You don't; you just let the IndexError fall through. Same as a KeyError
for d[k]. My propopsal is in regard to convencience methods, not to
direct access.

Ps. Sorry if this comes through twice, Google is being wierd right now.

Regards,
Jordan

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


Re: Can't get around "IndexError: list index out of range"

2006-10-10 Thread MonkeeSage

On Oct 10, 1:57 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> I think we'll just have to agree to differ in this repsecrt, as I don't
> see your suggestions for extending the sequence API as particularly
> helpful.

No worries. :)


On Oct 10, 11:22 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> so to "improve" a piece of code that's been optimized for the common
> case, you're adding an extra method call and a test to the inner loop?
>
> and this because you think Python programmers don't understand try-
> except statements ?

Uh, yeah, "You're all idiots and I'm not really a 'Python
Programmer'(TM)" -- that's exactly what I was meaning to say. I'm
suprised your telepathic powers let you pick up on that, since I didn't
say anything that could even remotely be construed that way. Freaky.

And, FWIW, the "optimized" version is not much faster than that put
forth by the stupid peon (me), even when my suggestion is implemented
in pure python:

$ cat test.py
import timeit
ary = ['blah'] * 10

def has_index(seq, idx):
  return idx < len(seq)
def at(seq, idx):
  if has_index(seq, idx):
return seq[idx]

def t1():
  while 1:
try:
  for i in range(11):
ary[i]
except IndexError:
  break
def t2():
  go = True
  while go:
for i in range(11):
  if has_index(ary, i):
ary[i]
  else:
go = False
def t3():
  go = True
  while go:
for i in range(11):
  val = at(ary, i)
  if val:
val
  else:
go = False

print 't1 time:'
print timeit.Timer('t1()', 'from __main__ import t1').timeit()
print 't2 time:'
print timeit.Timer('t2()', 'from __main__ import t2').timeit()
print 't3 time:'
print timeit.Timer('t3()', 'from __main__ import t3').timeit()

$ python test.py
t1 time:
15.9402189255
t2 time:
18.6002299786
t3 time:
23.2494211197

> I think we can all safely ignore you now.

You could have done that all along. I'm no Max Planck, and this isn't
quantum mechanics. But more interesting than whether it's "safe" to
ignore suggestions for improvement is whether its actually beneficial
to do so.


On Oct 10, 11:35 am, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> > *) insert martelli essay here.for example:
>
> http://mail.python.org/pipermail/python-list/2003-May/163820.html

I don't think this is strictly a question of EAFP vs. LBYL, but more a
question of convenience. This very moment in python I can say both
"try: d[k] ..." and "if d.has_key[k] / k in d".

Regards,
Jordan

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


Re: how do you get the name of a dictionary?

2006-09-08 Thread MonkeeSage
Simon Brunning wrote:
> It's not inconcevable that Python could behave that way, it's just
> that it would impose an overhead on the 99.999% of Python users who
> would have no use for the feature. It's a price not worth paying.

I guess I don't get the problem with the OP's request, either. There is
already a name<->identifier mapping in place for objects. You can type
the object name and python magically gives you the object by matching
the name to the identifier. It would probably be pretty simple to
expose the name or names associated with the identifier, if any, via
built-in function or method. There would be no extra overhead. There
would be no speed hit if you didn't call the function/method. There
would be very little implementation expense (I would imagine), as the
code that is already in place to do look-ups from the parser to the
object map could probably be reused or hooked into. But seeing as it
isn't a general-purpose feature, and Steven's function would be
sufficient for most cases, I'm not saying it should be a core feature;
I'm just saying that I don't see what the big huff is about.

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


Re: how do you get the name of a dictionary?

2006-09-08 Thread MonkeeSage
Simon Brunning wrote:
> On 8 Sep 2006 02:24:49 -0700, MonkeeSage <[EMAIL PROTECTED]> wrote:
> > I guess I don't get the problem with the OP's request, either. There is
> > already a name<->identifier mapping in place for objects.
>
> Do you mean a name<->object mapping?
>
> This, I think, isn't true. There is a name->object mapping, but to
> make that a name<->object mapping *would* carry an overhead. It might
> (or might not) be a *small* overhead, but since every single Python
> program would suffer the consequences, it's just not worth it.
> Especially, as others have pointed out, that it wouldn't really be
> very useful at all.

I'm new here, and I've only been using python for about 6 months; so I
don't claim any deep knowledge of the inner workings of the interpreter
or anything.

Seemingly (and I realize that one or more of my premises may be wrong),
by simple deduction, there must be a two-way name (label) to identifier
mapping. I'm assuming that every object is accessed in the symbol table
by a unique identifier (exposed through id()), and that every name is
mapped to an identifier (some sort of heirarchy would seem to be
involved in the mapping, allowing for recursive objects, multiple names
for single ids, &c). Given this, some sort of look-up strategy would
seem to be in place for resolving objects from identifiers, and
identifiers from names. So if every name is mapped to an identifier,
and every identifier is mapped to an object; given any object, one
should be able to determine its identifier and all of the names
associated with that identifier (if any).

Obviously, that's based on several assumptions. Mabye I'm dead wrong on
some points. Anyhow, I don't think it's a feature that needs to be
there, or would even be useful in most cases; I just don't think it
would be a big issue if it were. If I'm correct, (lack of) usefulness
would be what militates against it being implemented as a core feature,
not the introduction of a size or speed overhead on objects.

Regards,
Jordan

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


Re: best split tokens?

2006-09-08 Thread MonkeeSage
John Machin wrote:
> Not picking on Tim in particular; try the following with *all*
> suggestions so far:
>
> textbox = "He was wont to be alarmed/amused by answers that won't work"

Not perfect, but would work for many cases:

s = "He was wont to be alarmed/amused by answers that won't work"
r = r'[()\[\]<>{}.,@#$%^&*?!-:;\\/_"\s\b]+'
l = filter(lambda x: not x == '', re.split(r, string))

Check out this short paper from the Natural Language Toolkit folks on
some problems / strategies for tokenization:
http://nltk.sourceforge.net/lite/doc/en/tokenize.html

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


Re: convert loop to list comprehension

2006-09-08 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> Cool ... and damn but you guys are fast with the answers. This appears
> to work find, but in a quick and dirty test it appears that the [list]
> version takes about 2x as long to run as the original loop. Is this
> normal?

You could also do it 'functionally' with map(), but it's ugly and would
probably fail (in this case) for non-unique list indicies; it is fast
though.

map(lambda x: tmp.extend([seq.index(x)]*x), seq)

Ps. I don't know if xrange is faster...I thought the difference was
that range created a temporary variable holding a range object and
xrange created an iterator?

Regards,
Jordan

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


Re: convert loop to list comprehension

2006-09-08 Thread MonkeeSage
Paul Rubin wrote:
> "MonkeeSage" <[EMAIL PROTECTED]> writes:
> > Ps. I don't know if xrange is faster...I thought the difference was
> > that range created a temporary variable holding a range object and
> > xrange created an iterator?
>
> There's no such thing as a "range object"; range creates a list, which
> consumes O(n) memory where n is the number of elements.  xrange
> creates an xrange object, which is a reusable iterator of sorts.

Aha, thanks for explaining. :)

Regards,
Jordan

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


Re: how do you get the name of a dictionary?

2006-09-08 Thread MonkeeSage
Dennis Lee Bieber wrote:
>   id() returns, in C based Python, the memory address at which an
> object is stored. That is all... Names in Python are mapped to the
> object -- essentially they are mapped to the address of the object.
> There is NO intermediate hidden identifier.
>
> [snip]
>
> Object 1 has two names bound to it. But the only way to find out what
> those names are requires first having some other reference bound to the
> object, and then asking each name if the id() (the address) matches the
> id() of the reference in question.

Ahh! I see. That makes sense. Thanks for taking the time to explain it
to a noob. :)

Regards,
Jordan

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


Re: How to get the "longest possible" match with Python's RE module?

2006-09-11 Thread MonkeeSage
Licheng Fang wrote:
> Basically, the problem is this:
>
> >>> p = re.compile("do|dolittle")
> >>> p.match("dolittle").group()
> 'do'

>From what I understand, this isn't python specific, it is the expected
behavior of that pattern in any implementation. You are using
alternation, which means "either, or", and you have the shorter
subexpression first, so the condition is satisfied by just 'do' and the
matching terminates.

> There's another example:
>
> >>> p = re.compile("one(self)?(selfsufficient)?")
> >>> p.match("oneselfsufficient").group()
> 'oneself'

Again, I don't think this has anything to do with python. You pattern
basically means "match 'one' whether it is followed by 'self' or not,
and whether it is followed by 'selfsufficient' or not". For this
particular example, you'd want something like
"one(self)?(sufficient)?".

I think you could construct a pattern that would do what you want in
python without any problem. If you post a (short) example of your data,
I'm sure someone could help you with it.

Regards,
Jordan

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


Re: How to get the "longest possible" match with Python's RE module?

2006-09-11 Thread MonkeeSage
Licheng Fang wrote:
> Hi, according to these regexp engine discussions, it's NOT a behavior
> true to any implementation.
> [snip]

Well, I just double-checked in ruby (oniguruma regexp engine):

r = Regexp.new("do|dolittle")
puts r.match("dolittle")[0]
# do

r = Regexp.new("one(self)?(sufficient)?")
puts r.match("oneselfsufficient")[0]
# oneself

And perl:

if ("doolittle" =~
/(do|dolittle)/) {
  print "$1\n";
  # do
}

if ("oneselfsufficient" =~
/(one(self)?(selfsufficient)?)/) {
  print "$1\n";
  # oneself
}

And Javascript (whatever regexp engine Spidermonkey uses):

var r = new RegExp(/do|dolittle/);
alert("dolittle".match(r)[0]);

var r = new RegExp(/one(self)?(selfsufficient)?/);
alert("oneselfsufficient".match(r)[0]);

So, it seems they are all broken, or python is correct as well.

Regards,
Jordan

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


Re: How to get the "longest possible" match with Python's RE module?

2006-09-11 Thread MonkeeSage
MonkeeSage wrote:
> So, it seems they are all broken, or python is correct as well.

Aha, sorry about that Licheng (re: Tim's post). I guess "broken"
depends on if you are expecting perl-compatible behavior or otherwise.
I have my own scripts I use to do (f)grep and sed-like operations, so I
almost never use those programs and forgot about the different pattern
semantics (part of the reason I made my own scripts).

Regards,
Jordan

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


Re: How to get the "longest possible" match with Python's RE module?

2006-09-11 Thread MonkeeSage
Licheng Fang wrote:
> Oh, please do have a look at the second link I've posted. There's a
> table comparing the regexp engines. The engines you've tested probably
> all use an NFA implementation.

Sorry! *blush* I admit I skipped over your links. I'll have a look now.

BTW, just an idea that may or may not work. What about finding all
matches that meet the absolute baseline pattern, then taking the
longest of them...something like this mabye:

def matcher(strings, pattern):
  out = ''
  reg = re.compile(pattern)
  for string in strings:
match = reg.match(string).group()
if (len(match) >= len(out)): # should this use > or >= ?
  out = match
  return out # empty is no matches, else longest match

p = ['dodad', 'dolittle', 'dodaday']
print matcher(p, r'do.*')
# dolittle

Just a thought...

Regards,
Jordan

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


Re: How to get the "longest possible" match with Python's RE module?

2006-09-11 Thread MonkeeSage
Or mabye something like this is better:

def matcher(string, pattern):
  out = ''
  for match in re.findall(r'\S*%s\S*' % pattern, string):
if (len(match) >= len(out)):
  out = match
  return out

p1 = 'dodad donkeykong dolittle dodaday'
p2 = 'oneself self-serving selfsufficient oneselfsufficient'
print matcher(p1, 'do')
# donkeykong
print matcher(p2, 'self')
# oneselfsufficient

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


Re: Is it just me, or is Sqlite3 goofy?

2006-09-12 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> But it was stated in the sqlite docs that ALL SQL databases
> use static types implying that sqlite will be incompatible
> with any "heavy" database should the need arise to migrate
> upwards. The issue is not that there will be compatibilty
> problems with any data migration but that the truth is exactly
> opposite of what's claimed in Section 13.13.
>
> I'm not saying sqlite can't be used, what I'm asking for
> is that the documentation lay the facts out and I'll decide
> whether I can make this work in my application. Lying about
> it makes you sound like Microsoft.

I thought your qualm was with the pysqlite docs, not the sqlite docs
(which apparently do make it plain how the database handles typing)?

Also, as others have mentioned, there are a number of ways to ensure
type safety, as long as you know how the database works (which as I
understand was your original point -- that it should be better
documented how it works in the pysqlite docs; and I am inclined to
agree -- at least a mention with link to the sqlite docs would be
helpful). But given that type safety is not an issue if you use those
ways of ensuring it, then the move to a fuller database _will_ be
relatively easy. If you don't want to change anything in your database
creation/update code ala check constraints, you can always explicitly
validate from python, which can be done programatically (very simple
example -- you could also use regexp patterns to validate; e.g., string
fields not only must be type str, but must not match '^\d+$', &c):

rows = [
['1', 'fred', '0051', '/home/fred'],
['2', 'bob', '0054', '/home/bob'],
['3', 'bork', '>056', '/home/bork']
]
def validate(row):
  return [int(row[0]), str(row[1]), int(row[2]), str(row[3])]
for i in xrange(len(rows)):
  rows[i] = validate(rows[i]) # <- throws an exception on the third row
  # database stuff here...

Regards,
Jordan

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


Re: SQLwaterheadretard3 (Was: Is it just me, or is Sqlite3 goofy?)

2006-09-12 Thread MonkeeSage

Oops! Sorry for the top-post!

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


Re: add without carry

2006-09-15 Thread MonkeeSage
Hugh wrote:
> Sorry, here's an example...
>
> 5+7=12
>
> added without carrying, 5+7=2
>
> i.e the result is always less than 10

def add(a, b, c=10):
  an = a + b
  if an >= c:
an -= c
  return an

add(5, 7) # = 2

?

Regards,
Jordan

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


Re: Finding dynamic libraries

2006-09-15 Thread MonkeeSage
Bill Spotz wrote:
> Is there a way to tell an executing python script where to look for
> dynamically-loaded libraries?

If I understand, you want to tell an already running python process to
import some extensions from arbitrary locations? If that is correct,
you could use a file to hold the dynamic load paths (e.g.,
path-per-line), and then before you want to import the extensions do
something like:

load_file = file('paths')
for path in load_file.read().split("\n"):
  if not path in sys.path:
sys.path.insert(0, path)
load_file.close()

Regards,
Jordan

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


Re: Finding dynamic libraries

2006-09-17 Thread MonkeeSage
Robert Kern wrote:
> No, his extensions link against other shared libraries which are not Python
> extensions. Those shared libraries are in nonstandard locations because he is
> running his tests before installing the libraries and his Python code.

In that case, couldn't it be done by placing a copy/symlink to the
shared library in the same directory as the python extension, then
reload()'ing the extension from the already running python process? I
think, but am not certain, so don't hold me to it, that dlopen and
kindred will search the working directory for a library before falling
back to the cache or LD_LIBRARY_PATH and so on. Worth a shot mabye.

Regards,
Jordan

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


Re: Finding dynamic libraries

2006-09-17 Thread MonkeeSage
Robert Kern wrote:
> It depends on the OS. Most Linux systems do not.

Hmm. Looks like 'man dlopen' confirms that (on my box anyway). It looks
like the working directory is never searched at all (unless it is
explicitly listed somewhere). Bummer. What about using ldconfig -l?

Regards,
Jordan

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


Re: CONSTRUCT - Adding Functionality to the Overall System

2006-09-19 Thread MonkeeSage
Ilias Lazaridis wrote:
> How do I do this?

It's easy:

def writeDebug(msg):
  print "I do not debug things, I _evaluate_ with professionals on the
industries! See ticket 547!\n" \
"Oh yeah, and %s" % msg
...
class Foo:
  writeDebug("how can I configure the interpreter for understand
Klingon participals and noun-phrases? Must I rectify the standard
dictionaries first?")

Regards,
Jordan

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


Re: CONSTRUCT - Adding Functionality to the Overall System

2006-09-19 Thread MonkeeSage
Ilias Lazaridis wrote:
> where do I place this function...

The place where you want it to be.

> ...thus it becomes available within class "Foo" and all other Classes?

Anything defined in the top-level (i.e., the sys.modules['__main__']
namespace) is accessible in every scope...but I assume you already know
that.

You could also use a super-duper super class from which to derive all
your other classes, and add/replace any methods you want there:

class lazaridis(object):
  def evaluate(self, community):
if 1 is 1:
  print "Evaluating %s... Result: failed!" % community

class Foo(lazaridis, str):
  pass

f=Foo('This has been a test of the lazaridis evaluation system')
f.evaluate('Python')
f.evaluate('Ruby')
f.evaluate('Java')
print f

> Something like a central import?

That would probably be the most logical thing to do.

But again, I assume you already know all this, so why are you asking?
Is this part of the evaluation process?

Regards,
Jordan

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


Re: Curious issue with simple code

2006-09-19 Thread MonkeeSage
codefire wrote:
> As above it all works as expected. However, on the marked line, if I
> use f instead of fp then that condition returns false! Surely,
> isfile(f) should return true, even if I just give a filename, rather
> than the full path?

Hi Tony,

Actually the file is in a different directory from the working
directory, so you need to give it the path where to find it. If you
started the script from 'c:\intent\docn' (i.e., start_dir), then just
using f would work.

Regards,
Jordan

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


Re: newbe's re question

2006-09-19 Thread MonkeeSage
Hi Eric,

Don't let people offput you from learning python. It's a great
language, and is fun to use. But really, George does have a point -- if
you want to learn python, then the best way is to swim with the tide
rather than against it. But still, don't worry too much about being
pythonic and whatnot (many people would disagree with me here), just
write the code that _you_ (and your team) feel the most comfortable
with, and helps you be the most productive. But again, many of the
conventional pythonic ways to do things are such because people have
tested various ways and found those to be the best. So don't just blow
off convention, either. Find a happy medium between your coding style
and the conventions, and then you'll really become as productive as you
can be. That's my opinion. And only my opinion. But if it helps you
too, that's good. :)

Ps. Do have a look at the tutorials and other guides available, they
should help you out alot (e.g., the regexp tutorial [1]).

[1] http://www.amk.ca/python/howto/regex/

Regards,
Jordan

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


Re: include statement

2006-09-19 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> Hello,
>
> is it possible in python to include another python source file into the
> current namespace, i.e.completely analogous to the #include statement
> in C.
>
> Regards Joakim

from blah import * # where blah is a blah.py file in sys.path

Also see:

http://pyref.infogami.com/import
http://effbot.org/zone/import-confusion.htm
http://docs.python.org/tut/node8.html

Regards,
Jordan

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


Re: byte count unicode string

2006-09-20 Thread MonkeeSage
John Machin wrote:
> The answer is, "You can't", and the rationale would have to be that
> nobody thought of a use case for counting the length of the UTF-8  form
> but not creating the UTF-8 form. What is your use case?

Playing DA here, what if you need to send the byte-count on a server
via a header, but need the utf8 representation for the actual data?

Regards,
Jordan

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


Re: new string method in 2.5 (partition)

2006-09-20 Thread MonkeeSage
s = "There should be one -- and preferably only one -- obvious way to
do it".partition('only one')
print s[0]+'more than one'+s[2]

;)

Regards,
Jordan

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


Re: byte count unicode string

2006-09-20 Thread MonkeeSage
OK, so the devil always loses. ;P

Regards,
Jordan

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


Re: CONSTRUCT - Adding Functionality to the Overall System

2006-09-20 Thread MonkeeSage
Ilias Lazaridis wrote:
> no, I don't know it.

OK...so how do you evaluate a language when you don't know its basic
operations? Hmmm, sounds fishy.

> how do I define something into the top-level namespace? I assume I
> could place it into the root-package of my project, into the __init__
> function.
>
> But how do I place it within my computers python installation (the big
> init)?

When you just say:

def blah(): pass

Now 'blah' function is in the top-level namespace, just like global
variables. Or if it's in a different file, you'd say 'from blah import
*'. You honestly don't know this?!??

> I am aware of this technique.
>
> But I want to modify existent classes, without touching their code.

The only way to do this is to explicitly subclass the existent classes
with your own class and modify what you want there in your subclass
(see below), or use multiple inheritence as I suggested previously.

> I've noticed some interesting code on you website:
>
> "
> class file(file):
>   def reopen(self, name=None, mode='w', bufsize=None):
> ...
>
> fh = file('test.txt', 'rb')
> print fh # 
> fh.reopen(mode='wb')
> "
> http://rightfootin.blogspot.com/2006/09/ruby-reopen.html
>
> does this mean that I can add a method to a class in a similar way with
> ruby? (by using class class-name(class-name): )

Basically, yes. In ruby you can reopen base classes; in python you can
get the same effect by subclassing the base classes with the same name
as the base class, then instantiating all your objects as that class.
This is the exact same idea as a "super-duper super class" as I
mentioned above.

> but the limitation is that I cannot do this with the python build-in
> types?:
>
> http://rightfootin.blogspot.com/2006/08/of-rocks-and-reptiles.html

You can subclass buit-in types using the same name as the parent class.
In fact here is what I use:

## my little library to make python more OO
## i.e., to get rid of the top-level junk...
## or at least to hide it behind some pretty
## object attributes :)
##
## YMMV - and don't complain if you don't
## like it; I wrote it for ME, not you
##
## Jordan Callicoat < [EMAIL PROTECTED] >

## some global methods so we can use them
## to set up the class methods
def rpr(self):
  return str(repr(self))
def stri(self):
  return str(self)
def inte(self):
  return int(self)
def leng(self):
  return int(len(self))
def say(self):
  print(self)
  return self
def joi(self, sep=''):
  return str(sep.join(self))
def ma(self, m):
  return list(map(m, self))
def filt(self, m):
  return list(filter(m, self))
def redu(self, m):
  return list(reduce(m, self))


## now build all the subclasses
class int(int):
  """
  Wrapper class for +int+
  Provided methods:
str(), int(), repr(), say(),
len(), plus(), minus(),
times(), divided_by()
  """
  def plus(self, i):
return int(self + i)
  def minus(self, i):
return int(self - i)
  def times(self, i):
return int(self * i)
  def divided_by(self, i):
return int(self / i)

int.str  = stri
int.repr = rpr
int.len  = leng
int.int  = inte
int.say  = say

class str(str):
  """
  Wrapper class for +str+
  Provided methods:
str(), int(), repr(), say(),
len(), plus(), times()
  """
  def plus(self, s):
return str(self + s)
  def times(self, i):
return str(self * i)

str.str  = stri
str.repr = rpr
str.len  = leng
str.int  = inte
str.say  = say

class list(list):
  """
  Wrapper class for +list+
  Provided methods:
str(), int(), repr(), say(),
len(), plus(), times(), join()
  """
  def plus(self, l):
return list(self + l)
  def times(self, i):
return list(self * i)

list.str= stri
list.repr   = rpr
list.len= leng
list.say= say
list.join   = joi
list.map= ma
list.filter = filt
list.reduce = redu

class tuple(tuple):
  """
  Wrapper class for +tuple+
  Provided methods:
str(), int(), repr(), say(),
len(), plus(), times(), join()
  """
  def plus(self, l):
return tuple(self + l)
  def times(self, i):
return tuple(self * i)

tuple.str= stri
tuple.repr   = rpr
tuple.len= leng
tuple.say= say
tuple.join   = joi
tuple.map= ma
tuple.filter = filt
tuple.reduce = redu

class dict(dict):
  """
  Wrapper class for +dict+
  Provided methods:
str(), int(), repr(), say(),
len()
  """
  pass

dict.str  = stri
dict.repr = rpr
dict.len  = leng
dict.say  = say
dict.join = joi


## done with the global methods, remove them
del(rpr, stri, inte, say, joi, ma, filt, redu)


## show examples if called standalone
if (__name__ == '__main__'):
  i = int(5)
  n = i + 5
  n.say()
  i = i.times(5).divided_by(3).plus(2)
  i.str().int().str().repr().say()

  s = 'Tree'
  i = str(s)
  i = i.plus(' and dog\n').times(2)
  i.repr().say()

  def test(item):
return '%s!' % item
  l = ['test', 'this', 'out', 'now']
  i = list(l)
  i = i.times(2)
  i.join(' ').say()
  i.map(test).say()

  t = ('test', 'this', 'out', 'now')
  i = tuple(t)
  i = i.plus(('hi', 'there'))
  i.join('+').repr().sa

Re: Is it possible to save a running program and reload next time ?

2006-09-21 Thread MonkeeSage
[EMAIL PROTECTED] wrote:
> Is it possible that the program can save all running data to a file when
> I want it to stop, and can reload the data and continue to run from
> where it stops when the computer is free ?

This isn't what you asked for (I have no idea how to do that), but
given your description, perhaps a different solution would work.

If you're using a *nix type OS (or possibly Cygwin, never tried) with a
bash-style shell, then you probably already have job control built in.
For example, in bash you can type Z to stop the current process,
and you can see all jobs and their states and job numbers with the
'job' command, and you can resume a stopped job with '%[job_number]'.
So for example, if only one job is in he queue, just stop it and then
when you're ready do %1.

Another *nix option would be to use the nice command to set the
schedular priority of the process so that when something with a higher
priority needs the CPU then it gets it first rather than your nice'd
process (something like 'nice -n 15 python your_program.py' should do
well -- very low priority). I'm pretty sure windows has some kind of
priority option for tasks as well, in fact, IIRC you open the task
manager and right click on a task and can set the priority lower.

Regards,
Jordan

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


Re: Evaluation of Truth Curiosity

2006-09-21 Thread MonkeeSage
James Stroud wrote:
> What is the logic of the former expression not evaluating to True (or
> why the latter not 1?)? Is there some logic that necessitates the first
> operand's dictating the result of the evaluation? Or is this an artefact
> of the CPython implementation?

If I understand correctly, OR'ing an int and a bool (your first
example) returns an int by coercing the bool to an int; and OR'ing two
bools (your second example) returns a bool.

Regards,
Jordan

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


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage

[EMAIL PROTECTED] wrote:
> When I run my code from within the derived class, self.weight
> and self.colour are not  inherited (although methods are inherited as I
> would have expected).

Animal is never initialized and you're not passing weight and color
into it anyway. You need something like:

class animal: # (object): # <- new-style class
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour

class bird(animal):
  def __init__(self, weight, color, wingspan):
#super(bird, self).__init__(weight, color) # <- new-style init
animal.__init__(self, weight, color) # <- old-style init
self.wingspan = wingspan
print self.weight, self.colour, self.wingspan

class fish(animal):
  def __init__(self, weight, color, length):
#super(fish, self).__init__(weight, color)
animal.__init__(self, weight, color)
self.length = length
print self.weight, self.colour, self.length

HTH,
Jordan

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


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage
Hi Lorcan,

Mabye thinking of it like this will help: birds and fishes (I love that
word, even if it is incorrect) can _do_ all the things that all animals
have in common: eat, drink, die, reproduce, &c; but that is generic.

class animal(object):
  def eat(self, food): pass
  ...
class bird(animal): pass
class fish(animal): pass

If you want to talk about a specific bird or fish, then you have to say
more than just that it is an animal. Now, if all animals have a weight
and a color, but not all have the same weight or color, then you want
to say that this bird or fish is an animal which is colored X and
weighes Y.

class animal(object):
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal): pass # __init__ from animal is called implicitly
class fish(animal): pass

Now what if a bird and a fish have other attributes that not all
animals share (or at least specialized versions)? Well then you need to
say this bird is an animal which is colored X and weighs Y, but unlike
other animals, has a wingspan or length of Z.

class animal(object):
  def __init__(self, weight, colour):
self.weight = weight
self.colour = colour
class bird(animal):
  # override __init__ so we can say what _this_ animal is like
  def __init__(self, weight, color, wingspan):
super(bird, self).__init__(weight, color)
self.wingspan = wingspan
class fish(animal):
  def __init__(self, weight, color, length):
super(fish, self).__init__(weight, color)
self.length = length

Does this make more sense?

Regards,
Jordan

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


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage

[EMAIL PROTECTED] wrote:
> If you have multiple inheritance do you need the old style init anyway?

I guess so, I'm not really sure. This page
 talks about super() and MRO and such,
but I have only glanced over it the other day. I will read it more
fully sometime. I tend not to use multiple inheritance very often, and
when I do I usually don't need to initialize the superclasses. So I've
never really thought about it or researched into it. Someone smarter
than me would probably know (hey wait a second -- you're smarter than
me! I've seen your code golf score, buddy! ;) ).

Regards,
Jordan

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


Re: Can I inherit member variables?

2006-09-21 Thread MonkeeSage
Ps. Aristotle can rest easy tonight:

class mortal(object): pass
class man(mortal): pass
Socrates = man()
all_men  = mortal()
if Socrates == all_men:
  print "Socrates == all_man"
else:
  print "Undistributed Middle is indeed a fallacy"

;)

Regards,
Jordan

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


Re: Does Python provide "Struct" data structure?

2006-09-22 Thread MonkeeSage
Hi Daniel,

To avoid problems you could vendor the ipython file you require, but an
easier solution may just be to implement your own version of the class
(it's extreemly easy):

class struct():
  def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
  setattr(self, k, v)

mystruct = struct(echo = 1,
  verb = 'Verbose',
  filedir = 'C:/temp')

print mystruct.filedir

Regards,
Jordan

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-22 Thread MonkeeSage
Hi Saizan,

I don't really see anything wrong with creating a custom class for
evaluating those kinds of logical statements. It does make the code for
statements more concise and easy to follow (with less binding
ambiguity). Mabye something like this would help:

class logic(int):
  def __sub__(self):
return logic(not self)
  def eval(self, statement):
return bool(statement)
  def make_logical(self, *args):
out = []
for arg in args:
  out.append(logic(arg))
return out

l = logic()
# init a buch of variables (or a list) at once
x, y, z = l.make_logical(True, False, True)
# or one at a time
v = logic(False)
# evaluate a statement
print l.eval((x and y) or (-z or -v)) # True

Regards,
Jordan

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


Re: Python Input from keyboard

2006-09-22 Thread MonkeeSage
utab wrote:
> I want to read some input continuously from keyboard and then I would
> like to process these input.
>
> I have a code like this but getting errors, I would like to terminate
> when there is an empty string in the input, why is not this easy as the
> "cin" or "scanf". I had to search for even this easy operation. Is
> there a way to send EOF signal to terminate input(ctrl+??)

You can send a signal (check the signal module in the docs), but you
can also just do what you wanted:

x = []
y = []
while True:
  msg = 'input x and y values :   '
  uin = raw_input(msg).strip()
  if not uin:
print 'you have not entered x or y, quiting'
break
  else:
xt, yt = uin.split(' ', 1)
x.append(float(xt))
y.append(float(yt))

for i in range(len(x)):
  print x[i]

Regards,
Jordan

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-23 Thread MonkeeSage
Steve Holden wrote:
> Is this a serious suggestion, or simply an attempt at sardonic obscurantism?

Well, I was being serious, but now I'm afraid to see what kind of evils
I've acidentally stepped in, heh!? I honestly don't see anything wrong
with creating a DSL for a given problem domain. Where did I go astray?

Regards,
Jordan

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


Re: grabbing random words

2006-09-23 Thread MonkeeSage
Another approach would be to just scrape a CS's random (5.75 x 10^30)
word haiku generator. ;)

import urllib
import libxml2
import random

uri   = 'http://www.cs.indiana.edu/cgi-bin/haiku'

sock  = urllib.urlopen(uri)
data  = sock.read()
sock.close()

doc   = libxml2.htmlParseDoc(data, None)
words = [p.content for p in doc.xpathEval('//a')[8:-3]]
doc.freeDoc()

print random.choice(words)

Regards,
Jordan

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-23 Thread MonkeeSage
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>,
> MonkeeSage wrote:
>
> > I don't really see anything wrong with creating a custom class for
> > evaluating those kinds of logical statements. It does make the code for
> > statements more concise and easy to follow (with less binding
> > ambiguity).
>
> Why not express everything in Conjunctive Normal Form?

Because: (¬Can add all the literal operators ∧ Already existed a
concise/unambiguous mechanism for all but negation) ├ Used existing
scheme but added concise/unambiguous negation mechanism.

Regards,
Jordan

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

Re: Isn't bool __invert__ behaviour "strange"?

2006-09-23 Thread MonkeeSage

MonkeeSage wrote:
> > Why not express everything in Conjunctive Normal Form?
>
> [snip]

Oh, you meant the actual form. Duh! Yeah, that would work. For some
reason I was thinking you were asking why I didn't implement the
standard symbols, sorry.

Regards,
Jordan

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-23 Thread MonkeeSage
Bjoern Schliessmann wrote:
> Lawrence D'Oliveiro wrote:
>
> > Which is why C++ allows "not", "and" and "or".
>
> Is this standards compliant? My reference (book) doesn't contain it,
> but g++ allows it.

"The C++ standard provides _operator keywords_ (Fig. 21.8) that can be
used in place of several C++ operators." (Deitel & Deitel, 2001; 1082).

Regards,
Jordan

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


Re: Need compile python code

2006-09-23 Thread MonkeeSage
mistral wrote:
> Just to comple python ode - it creates html page, nothing more, nothing
> else.. Just generate one html page.

I *think* this is what you want:

python -O -m py_compile file.py
python file.pyo

See: http://docs.python.org/lib/module-pycompile.html

Regards,
Jordan

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


Re: Need compile python code

2006-09-23 Thread MonkeeSage
mistral wrote:
> this not work for me, show compilation error.  Is there simple way
> compile pythone file? its absolutely unclear with command line. Just
> show me exact command I need run(from python interactive shell?)

OK...

# cd to where the file.py is
$ cd /some/dir

# start python interactively, enable optimized compiling
$ python -O
...

# import your file.py -- if this doesn't work then
# your file has errors and will not compile --
# if it works then your file is now compiled --
# file.pyo should now exist with file.py
>>> import file

# you can also do it explicitly --
# import the compiler
>>> import py_compile
>>> py_compiler.compile('file.py')

If that still doesn't work, show us the error, or we can't help you
very easily.

Regards,
Jordan

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


Re: Need compile python code

2006-09-23 Thread MonkeeSage
MonkeeSage wrote:
> >>> import py_compile
> >>> py_compiler.compile('file.py')
  ^^^

Should be:

>>> py_compile.compile('file.py')

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


Re: Need compile python code

2006-09-23 Thread MonkeeSage
mistral wrote:
> No, something is wrong there. what I need is just compile one python
> file which will generate html page, with parameters:
> "exec" "python" "-O" "$0" "$@"
>
>  just need simple way do this(script is correct), i will not set any
> patches anywhere, can i do this wrom normal GUI?

Hmmm... Are you talking about _RUNNING_ python scripts? Is that what
you mean by "compile" -- you mean execute? Is that what this broken
shell script means?

"exec" "python" "-O" "$0" "$@"

You don't need exec, the double quote on every word breaks it, and
passing $0 (which is the shell script itself) to python is sure to
break. Try this:

#!/bin/sh
python -O "$@"

Then:

$ run_python.sh file.py arg1 arg2 arg3

Regards,
Jordan

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


Re: webbrowser module's Firefox support

2006-09-23 Thread MonkeeSage
Dustan wrote:
> I did do a search here, but came up empty-handed. Can anyone tell me
> how to get the webbrowser module to recognize firefox's existence,
> given this information?

Looks like it is checking %PATH% for firefox.exe. Try:

>>> import os
>>> os.environ["PATH"] = r"C:\Program Files\Mozilla Firefox;"
>>> import webbrowser
>>> webbrowser._browsers 

Regards,
Jordan

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


Re: webbrowser module's Firefox support

2006-09-23 Thread MonkeeSage
Dustan wrote:
> >>> cont=webbrowser._browsers['firefox'][1]

Why not use the api? cont=webbrowser.get('firefox')

> ValueError: close_fds is not supported on Windows platforms
>
> Looking in the docs on subprocess.Popopen
> (http://docs.python.org/lib/node529.html), it says "If close_fds is
> true, all file descriptors except 0, 1 and 2 will be closed before the
> child process is executed. (Unix only)". I have to be frank; I have no
> idea what this means. What should I do to fix this?

It just means that on *nix there is an option to close all open file
handles except stdin, out and err before the browser is called. I'm
thinking that mabye get() does an OS check to see how to call
subprocess.Popen, and you effectively bypassed it by using the
lower-level _browsers attribute. But I could be wrong. Try it with
get() and see how that goes.

Regards,
Jordan

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


Re: Isn't bool __invert__ behaviour "strange"?

2006-09-23 Thread MonkeeSage
Bjoern Schliessmann wrote:
> Thanks. Only if I'd known that earlier ;)

NP. I had to look it up 'cause I'd never seen them used either.

Regards,
Jordan

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


Re: webbrowser module's Firefox support

2006-09-23 Thread MonkeeSage
Dustan wrote:
> That didn't work either.

Well, I'm out of ideas. It's also odd that it was being read as
webbrowser.BackgroundBrowser...whatever that is! It should have been
webbrowser.Mozilla.

> Another thing: your fix is only temporary. Is there a way to make it
> work even after I close IDLE? I changed the command you gave me a bit
> so it doesn't get rid of the other paths:
>
> os.environ["PATH"]+=";C:\Program Files\Mozilla Firefox;" # can't
> remember the path for firefox right now...
>
> But either way, it ends up going right back to the previous value after
> I close IDLE.

Yeah, sorry about that, I meant to mention that changes to os.environ
only last for the life of the python process. To set / change
environment variables like PATH permanently, check out this page:
http://www.cims.nyu.edu/systems/platforms/windows/setpath.html

Regards,
Jordan

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


Re: grabbing random words

2006-09-24 Thread MonkeeSage
Steven D'Aprano wrote:
> That isn't 5.75e30 words, it is the number of possible haikus. There
> aren't that many words in all human languages combined.

Doh! This is why _I'm_ not a computer scientist. I'm kinda slow. ;)

> (Note however that there are languages like Finnish which allow you to
> stick together words into a single "word" of indefinite length, sort of as
> if we could say in English "therearelanguageswhichallowyou" to
> "sticktogetherwordsintoasinglewordofindefinitelength". Such languages
> might be said to have an infinite number of words, in some sense.)

Imagine an agglutinating (sp?) programming language, heh!

Regards,
Jordan

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


Re: HTTP GET Explodes...

2006-09-24 Thread MonkeeSage
Pete wrote:
> So, I looked at my search path under the account that was experiencing
> the problem. That wasn't it... Then I'm thinking there's an
> environmental variable causing this. Too many to work right now. Will
> investigate later.

You can see all environment variables with the declare command:

$ declare
BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
...
XTERM_SHELL=/bin/bash
XTERM_VERSION='XTerm(220)'
_=declare

Regards,
Jordan

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


Re: gtk.Entry Colors

2006-09-24 Thread MonkeeSage
Tuomas wrote:
> I would like to manipulate PyGTK Entry widget's background and
> foreground colors. Is it possible? How?

Yes, it is possible:

# widget color
entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF"))
# frame color
entry.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FF"))
# text color
entry.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse("#00FF00"))

See:
http://www.pygtk.org/pygtk2reference/class-gtkwidget.html
http://www.pygtk.org/pygtk2reference/class-gdkcolor.html

Regards,
Jordan

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


Re: ruby %w equivalent

2006-09-24 Thread MonkeeSage
Tim Chase wrote:
> to give it that perl/ruby-ish feel of terseness and obscurity.

Don't feel bad, you always have things like r'%s\%s' % (u'blah',
u'blah') and so on. But of course, it's only the other guys who are
evil / ugly / stupid. As the human torch says, "Flame On". :)

[Full disclosure: I like ruby _and_ I like python (gasp!), and see no
need to artificially criticize one or the other; I try rather to
utilize the strengths of both.]

Regards,
Jordan

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


Re: gtk.Entry Colors

2006-09-25 Thread MonkeeSage
Tuomas wrote:
> Yes, I read the reference before posting here. I tried something like:

Hi Tuomas,

I didn't mean to say that you hadn't read the docs (I had a hard time
finding the right methods in the docs too, even though I know the
methods); I just wanted to give you the references so you could see the
method signatures and the other gdk.Color options. :)

Regards,
Jordan

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


Re: Emphasizing a gtk.Label

2006-09-25 Thread MonkeeSage
ravenheart wrote:
> What would be the best solution? How to do it? I have found how to
> change colors and underscoring but nothing else.

I don't know about the best, but I would use:

label = gtk.Label()
# Pango markup should be on by default, if not use this line
#label.set_use_markup(True)
label.set_markup("Look, I'm bold")

Regards,
Jordan

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


Re: ruby %w equivalent

2006-09-25 Thread MonkeeSage
hg wrote:
> Why would they want to make such an obscure API ? ... didn't they have
> Python to learn from (I am truly amazed - nothing cynical ...just ...
> why ?)

In ruby there are several special literal notations, just like python.
In ruby it goes like this:

%{blah} / %Q{blah} # same as "blah" but igornes " and '
%q{blah} # same as 'blah' but no interpolation
%w{blah blah} # same as "blah blah".split
%r{blah} # same as /blah/
%x{ls} # same as `ls`

Sometimes they are very useful, and sometimes they are cumbersome. It's
up to the programmer to implement them effectively.

Regards,
Jordan

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


Re: ruby %w equivalent

2006-09-25 Thread MonkeeSage
hg wrote:
> But today ? what is the cost of replacing %w("blah blah") by
> Hi_I_Want_To_Split_The_String_That_Follows( "blah blah")

How about r'blah', u'blah', """blah""", and '''blah'''. :)

Regards,
Jordan

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


Re: Survival of the fittest

2006-09-26 Thread MonkeeSage
James Stroud wrote:
> Out of curiosity, what are these features that ruby has that python
> lacks. I've always wondered whether I should look at ruby--whether, as a
> language, it has anything to teach me that say python, C, and Java don't
> (LISP/Scheme is on my short-list to learn.)

Just a guess, myself not being the OP; but I would imagine that true
blocks / continuation passing and overriding / extending built-in
classes would rank high on the list. You can do the same things in
python (by using a different implementation), but it's not always as
clear or easy (e.g., coroutines in ruby as alot clearer using a callcc
approach than python's generator approach, imo at least -- but that's
also highly subjective).

Ps. I agree with the OP on the point I like python alot. :)

Regards,
Jordan

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


Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-28 Thread MonkeeSage
Bruno Desthuilliers wrote:
> Brendon Towle wrote:
> > Some of your Lisp translations are subtly off...
>
> Seems correct to me. Lisp lists are linked lists, not arrays.

Actually, Brendon was correct. In lisp / scheme:

(cons 1 '(2 3)) -> (1 2 3)
(car '(1 2 3)) -> 1
(cdr '(1 2 3)) -> (2 3)

But Brendon's code also needs a correction: [a].extend(b) is wrong,
because extend is in-place and returns None, and [a] is anonymous...it
needs to be something like:

def cons(a, b):
  b.insert(0, a)
  return b

Regards,
Jordan

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


Re: Resuming a program's execution after correcting error

2006-09-28 Thread MonkeeSage
Georg Brandl wrote:
> As I said before, this can be done by finding out where the error is raised,
> what the cause is and by inserting an appropriate try-except-statement in
> the code.

I could be mistaken, but I *think* the OP is asking how to re-enter the
stack at the same point as the exception exited from and continue with
the execution as if the exception never happened. AFAIK, that isn't
possible; however, given that he has a file to work from that indicates
a portion of the state at the time of the exception, I think he may be
able simulate that kind of functionality by reading in the file on
exception and then returning a call to the function where the exception
occured with the data from the file. Something like this mockup:

def faulty_function(a, b, c=None):
  if not c:
c = 0
  try:
# modify c, write c to file...
# oops hit an exception
c += a / b
  except:
# read from the file here
# c = ...
# and fix the error
b += 1
return faulty_function(a, b, c)
  return c

print faulty_function(2, 0) # => 2

Of course, it's probably much better to just fix the code and avoid the
exception in the first place. ;)

Regards,
Jordan

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


Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-28 Thread MonkeeSage
sturlamolden wrote:
> Thus I stand by my original claim. Essentlially:
>
> def cons(car,cdr): return (car,cdr) # or [car,cdr]
> def car(cons): return cons[0]
> def cdr(cons): return cons[1]

I guess you were talking about implementing the _structure_ of lisp
lists in python syntax (as you seem to imply), not trying to emulate
their _behavior_ with one-dimensional python lists. That makes sense,
and your code is correct in that case; but in the other case Brendon's
code is correct. So everyone was right (only, about different things).
:)

Regards,
Jordan

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


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread MonkeeSage
So far as unobfuscated versions go, how about the simple:

def to_bin(x):
  out = []
  while x > 0:
out.insert(0, str(x % 2))
x = x / 2
  return ''.join(out)

Regards,
Jordan

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


Re: Questions on Using Python to Teach Data Structures and Algorithms

2006-09-28 Thread MonkeeSage
Dennis Lee Bieber wrote:
>   Though if this suddenly inspires the creation of a Common LISP
> interpreter written in Python, I may want to close my eyes 

Hehe! I actually thought of trying that once, but I realized that I'm
too stupid and / or lazy to pull it off. ;)

Regards,
Jordan

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


Re: Can string formatting be used to convert an integer to its binary form ?

2006-09-28 Thread MonkeeSage
Steve Holden wrote:
>   >>> to_bin(0)
> ''

Doh! Oh, yeah...that! ;)

OK...

def to_bin(x):
  out=[]
  while x > 0:
out.insert(0, str(x % 2))
x /= 2
  else:
out.append(str(x))
  return ''.join(out)

Regards,
Jordan

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


Re: retry in exception

2006-09-29 Thread MonkeeSage
Sybren Stuvel wrote:
> Antoine De Groote enlightened us with:
> > I hope I don't upset anybody by comparing Python to Ruby (again). Is
> > there something like Ruby's retry keyword in Python?
>
> Please don't assume that everybody knows Ruby through and through...

In ruby, the equivalent to try...except is begin...rescue. In the
rescue section you can ask it to retry the begin section. So, for
example:

b=0
begin
  puts 1/b
rescue
  b=1
  retry # <- this little guy
end

I don't think python has any equivalent (could be wrong). You can do
something like this however:

b=0
def do_stuff():
  print 1/b
try:
  do_stuff()
except:
  b=1
  do_stuff()

Regards,
Jordan

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


Re: retry in exception

2006-09-29 Thread MonkeeSage
Everyone wrote:
> [cool stuff]

Ps. I've only used retry a handful of times in about 3 or 4 years of
using ruby; I wasn't advocating it or criticizing python, just trying
to explain the OPs request.

Regards,
Jordan

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


Re: storing variable names in a list before they are used?

2006-09-29 Thread MonkeeSage
John Salerno wrote:
> If I want to have a list like this:
>
> [(first_name, 'First Name:'), (last_name, 'Last Name:').]

Do you need the data to be ordered? If not, just use a dictionary:

d = {'First Name:': '', 'Last Name:': ''}
d['First Name:'] = 'Bob'
d['Last Name:']  = 'Smith'
print "Hi, I'm %s %s." % (d['First Name:'], d['Last Name:'])

If so, check out the ordered dictionary module [1]:

from odict import OrderedDict as odict
od = odict([('First Name:', ''), ('Last Name:', '')])
od['First Name:'] = 'James'
od['Last Name:']  = 'Bond'
for k,v in od.items():
  print "%s => %s" % (k,v)

[1] http://www.voidspace.org.uk/python/odict.html

Regards,
Jordan

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


Re: DAT file compilation

2006-09-29 Thread MonkeeSage
Jay wrote:
> Is there a way through python that I can take a few graphics and/or
> sounds and combine them into a single .dat file?  If so, how?  And how
> can I access the data in the .dat file from inside the python script?

How about in a sqlite database? Sqlite has built-in bindings in python
2.5 and is available as a third-party extension in previous versions.
It's also pretty easy to use, but makes you data harder to tamper with
by an average windows user.

http://docs.python.org/lib/module-sqlite3.html (See also the "See Also"
section ;) ).

Regards,
Jordan

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


Re: File I/O

2006-09-30 Thread MonkeeSage
Diez B. Roggisch wrote:
> Good to know that you can get drunk under any circumstances.

+(++)1 heh!

> I have seen a bazillion bad xml/html parsing-hacks using regexes and the
> like, which stopped working after somehow the xml came all in one line, or
> some other implicit assumption about its layout failed to be met.

Seriously, I fully agree with you. To manipulate X/HT/ML data reliably
you need to use a parser. And usually the parser API is much cleaner
and easier to work with than trying to cobble together regexps anyhow!

Regards,
Jordan

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


Re: The Python world tries to be polite [formerly offensive to another language]

2006-09-30 Thread MonkeeSage
Steve Holden wrote:
> Perhaps so, but none the less comp.lang.perl has a demonstrable history
> of newbie-flaming. Don't know what it's like now, as it's years since I
> read that group, but they used to just love the smell of crisply-toasted
> newbie in the morning ;-)

C'mon! No reason why a newbie should be confused by a hyper-fatugly,
err, "hyper-fatarrow" every now and then [1]! What, are newbies totally
dense or something?! ;))

[1] http://www.nntp.perl.org/group/perl.perl6.language/25946

Regards,
Jordan

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


Re: Hot new programming languages - according to the TIOBE index

2006-09-30 Thread MonkeeSage
vasudevram wrote:
> Ruby and Python are doing well, according to the latest TIOBE index.

Doing well?? Ruby is up 14 points, relatively...ghea! ruby p0wns!11 ;)

D is an interesting language, though, I must say. Looks like they did
all the things right that C++ did wrong.

Regards,
Jordan

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


Re: for: else: - any practical uses for the else clause?

2006-09-30 Thread MonkeeSage
Sybren Stuvel wrote:
> I must say that the for/else construct is a LOT more readable than the
> rewritten alternatives.

+1

I just wish it had a more intuitive name like "after:" or "then:", as
"else:" seems like a choice between the loop and the other block (but
really the choice is between StopIteration and break).

Regards,
Jordan

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


Re: Hot new programming languages - according to the TIOBE index

2006-09-30 Thread MonkeeSage
MonkeeSage wrote:
> vasudevram wrote:
> > Ruby and Python are doing well, according to the latest TIOBE index.
>
> Doing well?? Ruby is up 14 points, relatively...ghea! ruby p0wns!11 ;)

Sorry my fellow pythonistas! I didn't see that this was cross-posted. I
was of course being silly, but I wanted to make that clear so as not to
unduely offend!

Regards,
Jordan

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


Re: ruby %w equivalent

2006-09-30 Thread MonkeeSage
Nick Craig-Wood wrote:
> These are snatched straight from perl.  In perl they are spelt
> slightly differently

Yup, they are; perl had _some_ good ideas; no doubt. ;)

> In perl (and maybe in ruby I don't know) the { } can be replaced with
> any two identical chars, or the matching pair if bracketty, so q/blah/
> or q(blah).

Yes; same thing in ruby.

Regards,
Jordan

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


  1   2   3   >