Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread John Machin
On 22/09/2007 1:44 PM, Carl Banks wrote:
> Anyone with me here?  (I know the deadline for P3 PEPs has passed; this 
> is just talk.)
> 
> Not many people are bit-fiddling these days.  One of the main uses of bit 
> fields is flags, but that's not often done in Python because of keyword 
> arguments and dicts, which are lot more versatile.  Another major use, 
> talking to hardware, is not something oft done in Python either.

You need to get out more often :-)

Python's bitwise operators are useful for and *used* for:

(1) packing and unpacking arcane structs used in communication protocols 
and in proprietary file formats

(2) trial implementations of pseudocode from academic papers, before 
transliterating to pyrex or C

E.g. main loop for a bit-parallel O(N) algorithm for a Levenshtein distance:
   for c in t:
  pm_new = pm[ord(c)]
  d0 = (((pm_new & vp) + vp) ^ vp) | pm_new | vn
  hp = vn | ~(d0 | vp)
  hn = d0 & vp
  if hp & mask:
 x += 1
  if hn & mask:
 x -= 1
  hp = (hp << 1) | 1
  vp = (hn << 1) | ~(d0 | hp)
  vn = d0 & hp
   return x

> 
> It seems like this occasional usage wouldn't justify having built-in 
> operators on its own.  And with the int/long unification, it makes a bit 
> less sense to think of integers as a bit field.

"to think of integers as a bit field" makes no sense to me. Possibly you 
meant "to think of an integer as a collection of bit fields" -- but this 
is putting the cart before the horse. Simply: if the data is a 
collection of bit fields, and the data is held in an int or a long or 
the unification thereof, then you need bitwise operators to extract/pack 
the bit fields.


>  Python has these 
> operators because of its heritage, but Python continues to move away from 
> the bad habits of its ancestors (integer division and so on), and I 
> wonder if this isn't another one.
> 
> Of course I'm not suggesting to get rid of bitwise operations altogether; 
> just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and 
> so on.

Function call overhead?? No thanks. E.g. from real working code:

 r = Rowinfo()
 # Using upkbits() is far too slow on a file
 # with 30 sheets each with 10K rows :-(
 #upkbits(r, bits2, (
 #( 0, 0x0007, 'outline_level'),
 #( 4, 0x0010, 'outline_group_starts_ends'),
 #( 5, 0x0020, 'hidden'),
 #( 6, 0x0040, 'height_mismatch'),
 #( 7, 0x0080, 'has_default_xf_index'),
 #(16, 0x0FFF, 'xf_index'),
 #(28, 0x1000, 'additional_space_above'),
 #(29, 0x2000, 'additional_space_below'),
 #))
 # So:
 r.outline_level = bits2 & 7
 r.outline_group_starts_ends = (bits2 >> 4) & 1
 r.hidden = (bits2 >> 5) & 1
 r.height_mismatch = (bits2 >> 6) & 1
 r.has_default_xf_index = (bits2 >> 7) & 1
 r.xf_index = (bits2 >> 16) & 0xfff
 r.additional_space_above = (bits2 >> 28) & 1
 r.additional_space_below = (bits2 >> 29) & 1


> Is it worth it to make such a change?  It would remove a lot of operators 
> (11 by my count), vastly simplifying syntax,  Which, IMHO, is no small 
> thing.  New numerical types would have fewer operations to support.

Specious argument. A new numerical type doesn't have to support bitwise 
operations now, if they make no sense for that type.

> And 
> let's face it: unlike arithmetic opertaions, there's not a lot of 
> different meanings for bit operations. And it would also, um, make new 
> special characters available *cough*.
> 
> Obviously, how widespread their usage is would matter.  But keep in mind 
> it would also be easy to convert the code automatically, because the 
> Python parser could reliably find all bitwise operations reliably.  (The 
> problem would be types that overloaded them to be something other than 
> bitwise operations: I'm looking at you, set.  That could very well be a 
> deal breaker.  I've never approved of things with completely different 
> meanings being deliberately overloaded to have the same spelling; this is 
> one reason why.)

Too late. That instance of Pandora's box had its lid nailed open ab initio.

> 
> If anyone says, "But that takes away an easy test for oddness (x&1)!", 
> or, "But you can multiply powers of two using left shift!  Isn't that 
> cool?", I'm not buying it.  Those are gimmicks.  Arithmetic operations 
> should be done with arithmetic operators.  The bitwise operators make the 
> code much less readable, especially to people unfamiliar with this usage.

Agreed, but this is beside the point. People will write obfuscated code 
  u

Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Paul Rubin
Kay Schluehr <[EMAIL PROTECTED]> writes:
> If you feel you can transform it into another unambigous grammar
> mixing statements and expressions it's up to you.

We got rid of the print statement for python 3.0.  Why not get rid
of the rest of them too?  Just use expressions for everything, as
works fine for plenty of other languages.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Ron Adam


Scott David Daniels wrote:
> Cristian wrote:
>> On Sep 21, 3:44 pm, Ron Adam <[EMAIL PROTECTED]> wrote:
>>
>>> I think key may be to discuss names and name binding with your friend.
> 
> Here's an idea:
> 
> import math
> 
> def sin_integral(start, finish, dx):
>  total = 0.0
>  y0 = math.sin(start)
>  for n in range(1, 1 + int((finish - start) / float(dx))):
>  y1 = math.sin(start + n * dx)
>  total += (y0 + y1)
>  y0 = y1
>  return total / 2. * dx
> 
> 
> def cos_integral(start, finish, dx):
>  total = 0.0
>  y0 = math.sin(start)
>  for n in range(1, 1 + int((finish - start) / float(dx))):
>  y1 = math.cos(start + n * dx)
>  total += (y0 + y1)
>  y0 = y1
>  return total / 2. * dx
> 
> generalize and separate the integration technique from the
> function it integrates.


How about this?

It's based on the apple basic program example in How to Enjoy Calculus.


Ron




import math

def integrate(fn, x1, x2, n=100):
 # Calculate area of fn using Simpson's rule.
 width = float(x2 - x1) / n
 area = fn(x1)
 if n % 2 != 0: # make sure its even
 n += 1
 for n in range(1, n):
 x = x1 + n * width
 if n % 2 == 0:
 area += 2.0 * fn(x)
 else:
 area += 4.0 * fn(x)
 area += fn(x2)
 return area * (width / 3.0)


def fn(x):
 return x**2

print "Area of fn:", integrate(fn, 0, 2)

print "Area of cos fn:", integrate(math.cos, 1, 2)

print "Area of sin fn:", integrate(math.sin, 1, 2)




Area of fn: 2.667
Area of cos fn: 0.0678264420216
Area of sin fn: 0.956449142468



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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Robert Kern
Carl Banks wrote:
> Anyone with me here?  (I know the deadline for P3 PEPs has passed; this 
> is just talk.)

I'm not.  :-)

We use them in numpy. The bitwise operations on int and float arrays aren't all
that useful, but they are very useful for bool arrays. We can't use the
"and"/"or"/"not" keywords since they can't be overloaded, but they bitwise
operators fill the need fairly well. We've had
logical_and()/logical_or()/logical_not() functions since forever, too, and
they're a pain in the ass.

-- 
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: Writing Object Data to Disk

2007-09-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Amit Kumar
Saha wrote:

> I would like to know if "Pickling" the class object is the only way of
> writing it to disk for persistent storage.

Wouldn't it be better to use a language-independent data representation that
wasn't tied to Python? Also tying your external data representation to your
internal program structure (objects) makes it harder to change the program
in future.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UTF-8 characters in doctest

2007-09-22 Thread John J. Lee
Peter Otten <[EMAIL PROTECTED]> writes:
[...]
>> Forgive me if this is a stupid question, but: What purpose does
>> function f serve?
>
> Like the OP's get_inventary_number() it takes a unicode string and
> returns a tuple of unicode strings. I'ts pointless otherwise. I hoped I
> had stripped down his code to a point where the analogy was still
> recognizable.

Ah, right.


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Carl Banks
On Sat, 22 Sep 2007 05:19:42 +, Grant Edwards wrote:
> On 2007-09-22, Carl Banks <[EMAIL PROTECTED]> wrote:
> 
>> Anyone with me here?  (I know the deadline for P3 PEPs has passed; this
>> is just talk.)
> 
> Not me.
> 
>> Not many people are bit-fiddling these days.
> 
> I do.

Your anecdotal evidence is noted and given all the consideration it's due.


>> One of the main uses of bit fields is flags, but that's not often done
>> in Python because of keyword arguments and dicts, which are lot more
>> versatile.  Another major use, talking to hardware, is not something
>> oft done in Python either.
> 
> I do it all the time.

Anecdotes again.  Do you have any stats on the usage of hardware 
interfacing in Python?  That would be a lot more useful.


> Bit fiddling is also required for implementing communications
> prototocols.

Fair enough.  That is a big issue, and defintely common on Python.


>> Is it worth it to make such a change?  It would remove a lot of
>> operators (11 by my count), vastly simplifying syntax,  Which, IMHO, is
>> no small thing.
> 
> If you don't want to use the bitwise operations, then ignore them. 
> Presto!  Simpler syntax.

Until people no longer need to read code written by others, this argument 
is utter bull.

It's completely besides the point, anyways.  The point is to make the 
language core smaller.  It would shift code implementing bitwise logic 
out the core parts of Python, and localize it in modulespace.  It's not 
about trying to make the mental footprint of the language smaller; in 
fact, wouldn't do that at all.


>> Obviously, how widespread their usage is would matter.  But keep in
>> mind it would also be easy to convert the code automatically, because
>> the Python parser could reliably find all bitwise operations reliably.
> 
> The resulting code wold be fugly.

Of course it would be.  The reason I mention it is that automatic 
convertibility is a key factor in whether a change can make it into 
Python 3.


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


Re: Odd files; just left behind?

2007-09-22 Thread John J. Lee
Robin Becker <[EMAIL PROTECTED]> writes:

> Bruno Desthuilliers wrote:
> 
>>>  >>>
>>>
>>> it would seem simpler to have the .so files inside the
>>> site-packages and there's the question of why this folder has to be
>>> obfuscated (name starts with .). Even if these files are
>>> "resources" why should they be assumed to belong to the user?
>>
>> Notice that you did install your lib/python in /myhome, not in /usr[/local]
>
> yes, so should I then assume that the root installs will put all the
> .so files in /usr/local/lib/.python-eggs?

No no -- the extraction of these .so files happens at *runtime*, so it
has to write the files somewhere it has permission to write to.  It's
like RL's zipapp resource extraction feature in fact, except the
resource extraction happens at runtime.  See those web pages I pointed
you at before.


> In fact when I look at my root installed pythons they seem quite happy
> to put the _mysql.so underneath site-packages. I suspect that if I
> just installed from source I'd get that behaviour, but the egg stuff
> is different.

Not sure without all the details, but I suspect those are non-egg
installs.


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


calling the function of one class from another class

2007-09-22 Thread Mridula Ramesh
hi.

i currently have code structured like this:

classA():
> def __init__():
>  ..
>  ..
>
> def fnc1():
> 
> 
>
>
> classB():
>def __init__():
> 
> 
> classA.fnc1()#this is where i get an error
>

TypeError: unbound method fnc1() must be called with classA instance as
first argument (got nothing instead)

when i do  fnc1(classA) i get:

NameError: global name 'fnc1' is not defined

am i violating some programming rule by trying to call fnc1 in classB? i am
only now learning OO alongside python, so i'm not sure! also, can someone
please tell me where to go for more articles on the classes and functions
and calling them from other places?

thanks a lot!

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

Re: An Editor that Skips to the End of a Def

2007-09-22 Thread John J. Lee
Paul Rubin  writes:

> [EMAIL PROTECTED] (John J. Lee) writes:
>> Seriously for a moment, I read something recently (maybe here?) about
>> an Apple study that claimed to show that people who perceived keyboard
>> bindings as being much faster than mouseing did not, on average, take
>> less time to complete the actions that were studied (they took more
>> time, in fact).  The plausible explanation for this was that people's
>> subjective perception of time is affected by the greater mental work
>> involved in typing (as opposed to mousing) for a given action.
>
> I think mousing takes more mental work than typing, and that's why it
> subjectively seems slower even if a stopwatch shows it to be faster.
[...]

I'm not sure this is a matter for debate, as much as physical
measurement.


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


Re: An Editor that Skips to the End of a Def

2007-09-22 Thread John J. Lee
Gary Coulbourne <[EMAIL PROTECTED]> writes:

> John J. Lee wrote:
>> Eclipse must be able to do this.
>
> Not by default... but I am certain there are plugins that provide python
> integration.  (And jython integration)

Well yes, obviously (?) I meant Eclipse with pydev installed.


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


Re: frange() question

2007-09-22 Thread John J. Lee
Carsten Haese <[EMAIL PROTECTED]> writes:

> On Thu, 2007-09-20 at 18:55 +, John J. Lee wrote:
>> Functions are never generators, senso stricto.  There are "generator
>> functions", which *return* (or yield) generators when you call them.
>
> Actually, a generator function is a function that returns a generator.

Read what I wrote again.  What makes you begin your sentence with
"Actually", rather than "Putting it another way"?


[...snip more sensible stuff I must assume was directed at the OP...]


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


Re: Writing Object Data to Disk

2007-09-22 Thread Hendrik van Rooyen

"Amit Kumar Saha"  wrote:

> I would like to know if "Pickling" the class object is the only way of
> writing it to disk for persistent storage.

look at marshall and shelve

>...Also, do we have a
concept
> similar to "array of objects" in Python? The number of objects is only
> known at "run-time".

I would use a list

- Hendrik

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Kay Schluehr
On 22 Sep., 08:56, Paul Rubin  wrote:
> Kay Schluehr <[EMAIL PROTECTED]> writes:
> > If you feel you can transform it into another unambigous grammar
> > mixing statements and expressions it's up to you.
>
> We got rid of the print statement for python 3.0.  Why not get rid
> of the rest of them too?  Just use expressions for everything, as
> works fine for plenty of other languages.

One might create a new dynamic functional+OO programming language,
where small statements like print, assert, raise etc. all become
functions and statements like while, for, with etc. become anonymous
closures. I think Logix had gone once in this direction but was
abandoned due to severe technical problems. So one might eventually
revive this project with another more sound technical base. Personally
I'm not sure it's worth a large effort and whether EasyExtend is the
right toolkit at hand. So it's definitely not Guido who will revive it
and also not me. Maybe some PyPy guys? What are we talking about -
really?

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 00:47:37 -0700, Kay Schluehr wrote:

> On 22 Sep., 08:56, Paul Rubin  wrote:
>> Kay Schluehr <[EMAIL PROTECTED]> writes:
>> > If you feel you can transform it into another unambigous grammar
>> > mixing statements and expressions it's up to you.
>>
>> We got rid of the print statement for python 3.0.  Why not get rid
>> of the rest of them too?  Just use expressions for everything, as
>> works fine for plenty of other languages.
> 
> One might create a new dynamic functional+OO programming language,
> where small statements like print, assert, raise etc. all become
> functions and statements like while, for, with etc. become anonymous
> closures.

Before someone starts to create such a thing he should take a look at Io
which has just objects and methods.

  http://www.iolanguage.com/

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


Re: Newbie completely confused

2007-09-22 Thread Roel Schroeven
Jeroen Hegeman schreef:
> ...processing all 2 files found
> --> 1/2: ./test_file0.txt
> Now reading ...
> DEBUG readLines A took 0.093 s
> ...took 8.85717201233 seconds
> --> 2/2: ./test_file0.txt
> Now reading ...
> DEBUG readLines A took 3.917 s
> ...took 12.8725550175 seconds
> 
> So the first time around the file gets read in in ~0.1 seconds, the  
> second time around it needs almost four seconds! As far as I can see  
> this is related to 'something in memory being copied around' since if  
> I replace the 'alternative 1' by the 'alternative 2', basically  
> making sure that my classes are not used, reading time the second  
> time around drops back to normal (= roughly what it is the first pass).

(First, I had to add timing code to ReadClasses: the code you posted 
doesn't include them, and only shows timings for ReadLines.)

Your program uses quite a bit of memory. I guess it gets harder and 
harder to allocate the required amounts of memory.

If I change this line in ReadClasses:

 built_classes[len(built_classes)] = HugeClass(long_line)

to

dummy = HugeClass(long_line)

then both times the files are read and your data structures are built, 
but after each run the data structure is freed. The result is that both 
runs are equally fast.

Also, if I run the first version (without the dummy) on a computer with 
a bit more memory (1 GiB), it seems there is no problem allocating 
memory: both runs are equally fast.

I'm not sure how to speed things up here... you're doing much processing 
on a lot of small chunks of data. I have a number of observations and 
possible improvements though, and some might even speed things up a bit.

You read the files, but don't use the contents; instead you use 
long_line over and over. I suppose you do that because this is a test, 
not your actual code?

__init__() with nothing (or only return) in it is not useful; better to 
just leave it out.


You have a number of return statements that don't do anything (i.e. they 
return nothing (None actually) at the end of the function). A function 
without return automatically returns None at the end, so it's better to 
leave them out.

Similarly you don't need to call sys.exit(): the script will terminate 
anyway if it reaches the end. Better leave it out.


LongClass.clear() doesn't do anything and isn't called anyway; leave it out.


ModerateClass.__del__() doesn't do anything either. I'm not sure how it 
affects what happens if ModerateClass gets freed, but I suggest you 
don't start messing with __del__() until you have more Python knowledge 
and experience. I'm not sure why you think you need to implement that 
method.
The same goes for HugeClass.__del__(). It does delete self.B4v, but the 
default behavior will do that too. Again, I don't get why you want to 
override the default behavior.


In a number of cases, you use a dict like this:

 built_classes  = {}
 for i in LINES:
 built_classes[len(built_classes)] = ...

So you're using the indices 0, 1, 2, ... as the keys. That's not what 
dictionaries are made for; lists are much better for that:

 built_classes = []
 for i  in LINES:
 built_classes.append(...)


HugeClass.B4v isn't used, so you can safely remove it.


Your readLines() function reads a whole file into memory. If you're 
working with large files, that's not such a good idea. It's better to 
load one line at a time into memory and work on that. I would even 
completely remove readLines() and restructure ReadClasses() like this:

def ReadClasses(filename):
  print 'Now reading ...'

  built_classes = []

  # Open file
  in_file = open(filename, 'r')

  # Read lines and interpret them.
  time_a = time.time()
  for i in in_file:
## This is alternative 1.
  built_classes.append(HugeClass(long_line))
## The next line is alternative 2.
##built_classes[len(built_classes)] = long_line

  in_file.close()
  time_b = time.time()
  print "DEBUG readClasses took %.3f s" % (time_b - time_a)

Personally I only use 'i' for integer indices (as in 'for i in 
range(10)'); for other use I prefer more descriptive names:

 for line in in_file: ...

But I guess that's up to personal preference. Also you used LINES to 
store the file contents; the convention is that names with all capitals 
are used for constants, not for things that change.


In ProcessList(), you keep the index in a separate variable. Python has 
a trick so you don't have to do that yourself:

 nfiles = len(input_files)
 for file_index, i in enumerate(input_files):
 print "--> %i/%i: %s" % (file_index + 1, nfiles, i)
 ReadClasses(i)


Instead of item0, item1, ... , it's generally better to use a list, so 
you can use item[0], item[1], ...


And finally, John Machin's suggestion looks like a good way to 
restructure that long sequence of conversions and assignments in HugeClass.


-- 
The saddest aspect of life right now is that s

Re: Writing Object Data to Disk

2007-09-22 Thread Bjoern Schliessmann
Amit Kumar Saha wrote:
> I have a Python class with data members, say:
> 
> class Foo:
> def __init__(self):
> 
> self.a=7
> self.b[]={1,3,4}
^^
This is invalid syntax.

> I would like to know if "Pickling" the class object is the only
> way of writing it to disk for persistent storage. 

It isn't. Every means of serialisation works, but pickling is
especially convenient if you only use Python.

> Also, do we have a concept similar to "array of objects" in
> Python? 

You can put all objects in lists, be it a string, an integer or some
complex class instance. 

> The number of objects is only known at "run-time".

class and function definitions also happen at runtime. I suggest you
worked through the Python tutorial to get a deeper insight in
Python's concepts.

http://docs.python.org/tut/

Regards,


Björn

-- 
BOFH excuse #89:

Electromagnetic energy loss

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Carl Banks
On Fri, 21 Sep 2007 23:38:38 -0700, Paul Rubin wrote:

> Carl Banks <[EMAIL PROTECTED]> writes:
>> Especially someone like an
>> engineer (in the classical sense), who isn't building versatile
>> software packages, won't need to resort to functional programming much.
> 
> http://www.math.chalmers.se/~rjmh/Papers/whyfp.html

>From the link:

"Abstract
As software..."

That's it, lost me already.  You ever see the kinds of programs 
mechanical engineers write?  It isn't software.


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Bjoern Schliessmann
Carl Banks wrote:
> On Sat, 22 Sep 2007 05:19:42 +, Grant Edwards wrote:

>> I do.
> 
> Your anecdotal evidence is noted and given all the consideration
> it's due.

Being funny, or being arrogant? Many today's network protocols work
with bit flags. It is /not/ anecdotal.
 
>> I do it all the time.
> 
> Anecdotes again.  Do you have any stats on the usage of hardware
> interfacing in Python?  That would be a lot more useful.

You want to take features out just because they are not widely used?
Let's get rid of metaclasses and operator overloading too then.
Let's create special object types for implementing this and pack
them into seperate modules.
 
>> If you don't want to use the bitwise operations, then ignore
>> them.
>> Presto!  Simpler syntax.
> 
> Until people no longer need to read code written by others, this
> argument is utter bull.

What is your goal already? Holy war against usage of bitwise
operators? I can't think of any other reason.
 
> It's completely besides the point, anyways.  The point is to make
> the language core smaller.  It would shift code implementing
> bitwise logic out the core parts of Python, and localize it in
> modulespace.  

And seriously, what is the point of this? Why do you want to enforce
banning bitwise operations?

Regards,


Björn

-- 
BOFH excuse #193:

Did you pay the new Support Fee?

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


Re: An Editor that Skips to the End of a Def

2007-09-22 Thread Paul Rubin
[EMAIL PROTECTED] (John J. Lee) writes:
> > I think mousing takes more mental work than typing,
> I'm not sure this is a matter for debate, as much as physical
> measurement.

I don't know of any way to physically measure mental work.
-- 
http://mail.python.org/mailman/listinfo/python-list


find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread Konstantinos Pachopoulos
Hi,
does any body now any such algorith? to find difference in days from 
MMDD to MMDD?
Or just an algorithm, that converts MMDD to seconds since the epoch?

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> That's it, lost me already.  You ever see the kinds of programs 
> mechanical engineers write?  It isn't software.

They do a lot of number crunching.  Certainly they can appreciate
higher order functions like integrate(f, x0, x1) to integrate the
function f from x0 to x1; or diff(f, x0) to find the derivative of f
at x0; etc.  Fortran had cheesy ways to do this as far back as the
1950's.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Kay Schluehr
On Sep 22, 10:40 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sat, 22 Sep 2007 00:47:37 -0700, Kay Schluehr wrote:
> > On 22 Sep., 08:56, Paul Rubin  wrote:
> >> Kay Schluehr <[EMAIL PROTECTED]> writes:
> >> > If you feel you can transform it into another unambigous grammar
> >> > mixing statements and expressions it's up to you.
>
> >> We got rid of the print statement for python 3.0.  Why not get rid
> >> of the rest of them too?  Just use expressions for everything, as
> >> works fine for plenty of other languages.
>
> > One might create a new dynamic functional+OO programming language,
> > where small statements like print, assert, raise etc. all become
> > functions and statements like while, for, with etc. become anonymous
> > closures.
>
> Before someone starts to create such a thing he should take a look at Io
> which has just objects and methods.
>
>  http://www.iolanguage.com/
>
> Ciao,
> Marc 'BlackJack' Rintsch

I checked out Io once and I disliked it. I expected Io's prototype OO
being just a more flexible variant of class based OO but Io couples a
prototype very closely to its offspring. When A produces B and A.f is
modified after production of B also B.f is modified. A controls the
state of B during the whole lifetime of B. I think parents shall not
do this, not in real life and also not in programming language
semantics.

There was another, similar and also abandoned project a while ago
heading for prototype OO called Prothon:

http://mail.python.org/pipermail/python-announce-list/2004-March/002966.html

When I remember correctly it was killed not because it was too
ambitious but the author lost his vision and didn't want to grow
Prothons ecosystem.


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


Re: calling the function of one class from another class

2007-09-22 Thread Furkan Kuru
On 9/22/07, Mridula Ramesh <[EMAIL PROTECTED]> wrote:
>
> hi.
>
> i currently have code structured like this:
>
> classA():
> > def __init__():
> >  ..
> >  ..
> >
> > def fnc1():
> > 
> > 
> >
> >
> > classB():
> >def __init__():
> > 
> > 
> > classA.fnc1()#this is where i get an error
> >
>
> TypeError: unbound method fnc1() must be called with classA instance as
> first argument (got nothing instead)
>
> when i do  fnc1(classA) i get:
>
> NameError: global name 'fnc1' is not defined
>
> am i violating some programming rule by trying to call fnc1 in classB? i
> am only now learning OO alongside python, so i'm not sure! also, can someone
> please tell me where to go for more articles on the classes and functions
> and calling them from other places?
>
> thanks a lot!
>
> mridula.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

you should create an instance of ClassA:

a = ClassA()
a.fnc1()

or if you want a static function you should declare the method as static

classA():
def __init__():
 ..
 ..
@staticmethod
def fnc1():


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

Re: Who can develop the following Python script into working application ?

2007-09-22 Thread Diez B. Roggisch
http://members.lycos.co.uk/dariusjack/ schrieb:
> On Sep 21, 1:26 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> 
>>
>>> Please help and let me know your terms.
>> There are websites dedicated to this - like e.g.
>>
>> http://www.guru.com/
>>
>> Make an offer there.
>>
>> Diez
> 
> Ok Diez,
> 
> Do you really think only Gurus from Guru.com can help me ?
> Do really need a middle-man ?

What middle-man?

> As you see, I am not developer of that code.
> Henri responded to me, code was intended for developers.
> It doesn't really look complicated or high-tech.
> Script should connect to a remote web site and get xml formatted data
> as a response to a query string http request, read data and inject
> into SQL database.
> Is Python not fit to a task of this kind ?
> Is there no a library of Python free scripts to accomplish the above
> like many for javascripts ?
> I am asking just of curosity, as an author of this script didn't
> respond to my second request  to tell me how complicated is the
> problem and what made him not to write that script as a fully working
> version.
> 
> Is Python so difficult, complicated, even for experienced developers ?

No, it's neither complicated nor difficult. And you know what? Not only 
for expierenced, but also for inexperienced developers it's an easy 
language.

And this community here is an extremely helpful and kind one.

But what it isn't is a forum to ask other to do your work FOR FREE. And 
get kinky about it if they refuse to do so...

And as you said yourself:

"""
Frankly speaking I would prefer to pay for your kind assistance
as it may take me to much time to learn some Python and understand the
following script.
"""

Now, again: http://www.guru.com/ There you can get devlopers for money. 
So what again is your problem?

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


Re: find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread Diez B. Roggisch
Konstantinos Pachopoulos schrieb:
> Hi,
> does any body now any such algorith? to find difference in days from 
> MMDD to MMDD?
> Or just an algorithm, that converts MMDD to seconds since the epoch?

See the modules datetime and time in the standard library.

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


Re: find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread John Machin
On 22/09/2007 7:37 PM, Konstantinos Pachopoulos wrote:
> Hi,
> does any body now any such algorith? to find difference in days from 
> MMDD to MMDD?


The literal answer to your question is, unsurprisingly, "Yes".

Now, what do you really want/need:

(a) details of an algorithm so that you can code it in Python
(b) an implementation of (a)
(c) a hint that Python might already have a standard module for date 
calculations
(d) a hint that there are things called search engines ... just copy 
your subject and paste it in


> Or just an algorithm, that converts MMDD to seconds since the epoch?
> 

There is no such thing as "the" (unqualified) epoch.

Try days_difference(from_date=your_chosen_epoch, to_date=some_date) * 24 
* 60 * 60
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote:

> I checked out Io once and I disliked it. I expected Io's prototype OO
> being just a more flexible variant of class based OO but Io couples a
> prototype very closely to its offspring. When A produces B and A.f is
> modified after production of B also B.f is modified.  A controls the
> state of B during the whole lifetime of B. I think parents shall not
> do this, not in real life and also not in programming language
> semantics.

Well it's like Python: inherited slots (attributes) are looked up in the
ancestors.  It should be easy to override `Object clone` in Io, so all
slots of the ancestor are shallow copied to the clone, but I guess this
might break existing code.  At least for your own code you could introduce
a `realClone` slot.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Carl Banks
On Sat, 22 Sep 2007 02:32:30 -0700, Paul Rubin wrote:

> Carl Banks <[EMAIL PROTECTED]> writes:
>> That's it, lost me already.  You ever see the kinds of programs
>> mechanical engineers write?  It isn't software.
> 
> They do a lot of number crunching.  Certainly they can appreciate higher
> order functions like integrate(f, x0, x1) to integrate the function f
> from x0 to x1; or diff(f, x0) to find the derivative of f at x0; etc. 
> Fortran had cheesy ways to do this as far back as the 1950's.

Well, I appreaciate it, as do many other engineers, but for a lot of 
engineers functional programming might as well not exist, either because 
they don't about it or don't care about it.  And it doesn't really affect 
them much, other than making them slightly less efficient then they could 
have been.  That's the key here.


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


Re: Writing Object Data to Disk

2007-09-22 Thread John Machin
On 22/09/2007 7:16 PM, Bjoern Schliessmann wrote:
> Amit Kumar Saha wrote:
>> I have a Python class with data members, say:
>>
>> class Foo:
>> def __init__(self):
>>
>> self.a=7
>> self.b[]={1,3,4}
> ^^
> This is invalid syntax.

So are the braces.

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


Re: Re: Writing Object Data to Disk

2007-09-22 Thread Amit Kumar Saha
> > From: Lawrence D'Oliveiro <[EMAIL PROTECTED]>
> > In message <[EMAIL PROTECTED]>,
> > Amit Kumar
> > Saha wrote:
> > 
> > > I would like to know if "Pickling" the class object is the only
> > way of
> > > writing it to disk for persistent storage.
> > 
> > Wouldn't it be better to use a language-independent data
> > representation that
> > wasn't tied to Python? Also tying your external data representation
> > to your
> > internal program structure (objects) makes it harder to change the
> > program
> > in future.

Actually, language independence is really not a consideration here. I am
happy at having it tied to Python :-)

BTW, do we have something like array of objects here? 
-- 
Amit Kumar Saha
me blogs@ http://amitksaha.blogspot.com
URL:http://amitsaha.in.googlepages.com


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


Re: Re: Writing Object Data to Disk

2007-09-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Amit Kumar
Saha wrote:

>> > From: Lawrence D'Oliveiro <[EMAIL PROTECTED]>
>
>> > In message <[EMAIL PROTECTED]>,
>> > Amit Kumar Saha wrote:
>> > 
>> > > I would like to know if "Pickling" the class object is the only
>> > way of writing it to disk for persistent storage.
>> > 
>> > Also tying your external data representation to your
>> > internal program structure (objects) makes it harder to change the
>> > program in future.
> 
> Actually, language independence is really not a consideration here. I am
> happy at having it tied to Python :-)

Even so, ignoring the issue of future changes is folly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml-rpc timeout

2007-09-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Steve
Holden wrote:

> Timeouts shouldn't be a normal feature of TCP communications.

On the contrary, they should. How else are you going to detect that the
other side has died?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing Object Data to Disk

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 17:13:14 +0530, Amit Kumar Saha wrote:

> BTW, do we have something like array of objects here?

Like someone already said: lists.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Grant Edwards
On 2007-09-22, Carl Banks <[EMAIL PROTECTED]> wrote:

>> If you don't want to use the bitwise operations, then ignore
>> them.  Presto!  Simpler syntax.
>
> Until people no longer need to read code written by others, this argument 
> is utter bull.
>
> It's completely besides the point, anyways.  The point is to
> make the language core smaller.

Since when has the size of Python been a concern?

> It would shift code implementing bitwise logic out the core
> parts of Python, and localize it in modulespace.  It's not 
> about trying to make the mental footprint of the language
> smaller; in fact, wouldn't do that at all.

I disagree.  Making the mental footprint of the language
smaller is far more important.  The small size of the mental
footprint is what helps readability, maintainability, and
productivity.  Space in my head is more valuable than space in
my computer.

>>> Obviously, how widespread their usage is would matter.  But
>>> keep in mind it would also be easy to convert the code
>>> automatically, because the Python parser could reliably find
>>> all bitwise operations reliably.
>> 
>> The resulting code wold be fugly.
>
> Of course it would be.  The reason I mention it is that
> automatic convertibility is a key factor in whether a change
> can make it into Python 3.

It matters not whether fugly code is automatically generated or
manually generated.  It's still hard to read and maintain.

-- 
Grant Edwards   grante Yow!  I feel... JUGULAR...
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Kay Schluehr
On Sep 22, 1:15 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote:
> > I checked out Io once and I disliked it. I expected Io's prototype OO
> > being just a more flexible variant of class based OO but Io couples a
> > prototype very closely to its offspring. When A produces B and A.f is
> > modified after production of B also B.f is modified.  A controls the
> > state of B during the whole lifetime of B. I think parents shall not
> > do this, not in real life and also not in programming language
> > semantics.
>
> Well it's like Python: inherited slots (attributes) are looked up in the
> ancestors.  It should be easy to override `Object clone` in Io, so all
> slots of the ancestor are shallow copied to the clone, but I guess this
> might break existing code.  At least for your own code you could introduce
> a `realClone` slot.
>
> Ciao,
> Marc 'BlackJack' Rintsch

But in class based OO most relevant attributes are defined during
object construction and they can't be simply changed by setting a
class attribute. Later you often create new attributes as but on
object level. You do not overuse the object/class relationship to
broadcast changes to all objects. While you might override 'Object
clone' I don't believe changing the way how the whole object model
works is a good idea and since it happens on source level you will get
also a performance hit.

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


Re: Sets in Python

2007-09-22 Thread sapsi
Thank you everyone for the assistance and for the very informative
discussion
Regards
SM

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


Re: Odd files; just left behind?

2007-09-22 Thread Robin Becker
Robert Kern wrote:
...
> 
> They're a cache.

they're actually the files that get used by the installed extension in 
this case (MySQLdb).

..
>>
>> it would seem simpler to have the .so files inside the site-packages and 
>> there's 
>> the question of why this folder has to be obfuscated (name starts with .). 
>> Even 
>> if these files are "resources" why should they be assumed to belong to the 
>> user?
> 
> Because they are unpacked at runtime by the user that imported the module.
> Usually, they won't have write access to site-packages.
> 

in this particular case the python being used was installed with a user 
prefix eg /myhome/PYTHON so everything belongs to the user; extensions 
installed by the same user can surely be installed in those folders. 
Upon checking I find that the same installs which produced the 
~/.python-eggs files also managed to put  the eggs like 
MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg inside the 
various site-packages directories.

I see no reason why the binary resources shouldn't be unpacked to 
site-packages at install time.

It seems reasonable that since install time is the only time an egg 
install can reasonably expect to write to the install area then that's 
when these resources should be unpacked. The zipapp install system 
referred to by John Lee does it that way because in practice we find we 
do need to install on CD's etc.

What happens if I as a naive idiot install an egg to a write once file 
system? I suppose the assumption is that we don't mind such files being 
created in the user's space. Spewing stuff all over some else's disk at 
run time instead of doing it once at install is wrong and may not even 
be possible. It also allows for the carefully crafted binary extensions 
to be substituted by anyone with write permission to the cache folder.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Who can develop the following Python script into working application ?

2007-09-22 Thread Andrey Khavryuchenko

 DBR> And as you said yourself:

 DBR> """
 DBR> Frankly speaking I would prefer to pay for your kind assistance
 DBR> as it may take me to much time to learn some Python and understand the
 DBR> following script.
 DBR> """

 DBR> Now, again: http://www.guru.com/ There you can get devlopers for
 DBR> money. So what again is your problem?

Actually, I am a python (and django) developer, looking for a contract,
owning Nokia 770 and contacted original poster with no response.

-- 
Andrey V Khavryuchenko   http://a.khavr.com/
Chytach - unflood your feeds http://www.chytach.com/
Software Development Company http://www.kds.com.ua/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Scott David Daniels
Ron Adam wrote:
> 
> 
> Scott David Daniels wrote:
>> Cristian wrote:
>>> On Sep 21, 3:44 pm, Ron Adam <[EMAIL PROTECTED]> wrote:
>>>
 I think key may be to discuss names and name binding with your friend.
>>
>> Here's an idea:
>>
>> import math
>>
>> def sin_integral(start, finish, dx): ...
>> def cos_integral(start, finish, dx): ...
>> generalize and separate the integration technique from the
>> function it integrates.
> 
> How about this?
> It's based on the apple basic program example in How to Enjoy Calculus.
>Ron
> 
> import math
> def integrate(fn, x1, x2, n=100):...
> def fn(x): ...
> print "Area of fn:", integrate(fn, 0, 2)
> print "Area of cos fn:", integrate(math.cos, 1, 2)

The point was a pedagogic suggestion, i.e. "Try taking your
friend along this path."   I wasn't trying to do a particularly
good job integrating, simply trying to show how you could
motivate first-class functions by showing a "useful" and
"fun" (at least to an engineer) function that cries out
for higher order functions.  In my experience engineers
often want a "reason its useful" before engaging with an
idea.  I'll bet that after a few such experiences he'll see
how passing around functions and (later) making functions from
from functions is a great tool to have in his toolbox.  Once
he sees that, there will be no problem.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Paddy
Sorry Carl,
I think *you* may not have much need for bitwise operators but others,
including myself do. No matter what the usage found, I would think
replacing bitwise operators by function calls a retrograde step.

- Paddy.

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


Re: Zope review

2007-09-22 Thread Sean Tierney
>From Twisted's website "Twisted is a networking engine written in
Python, supporting numerous protocols. It contains a web server,
numerous chat clients, chat servers, mail servers, and more.

Given that Zope is also a written in python, supports numerous
protocols, contains a webserver, has several chat packages available,
a comparison/contrast would be quite useful.

I will try to amass some info and bring it back here by midweek.

Thanks,

Sean

On 9/21/07, Istvan Albert <[EMAIL PROTECTED]> wrote:
> On Sep 21, 7:04 pm, "Sean Tierney" <[EMAIL PROTECTED]> wrote:
>
> > someone could contrast Zope w/ another Python framework like Twisted.
>
> > I've been investing some time in learning Zope/Plone and would love to
> > hear someone speak to alternatives.
>
> Twisted is a networking engine, Zope is a web application framework,
> Plone is a content management system, there is nothing to compare,
> these are different applications altogether, it is not like you'd
> replace one with the other
>
> For applications that can be compared see Zope vs Django vs Pylons vs
> web.py vs CherryPy. Google these and contrast away.
>
> i
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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


Re: find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread tokland
On 22 sep, 11:37, Konstantinos Pachopoulos <[EMAIL PROTECTED]>
wrote:

> does any body now any such algorith? to find difference in days from
> MMDD to MMDD?

Once I needed the same and I wrote:

def days_difference(s1, s2):
splitdate = lambda s: time.strptime(s, "%Y%m%d")[:3]
str2date = lambda s: datetime.date(*splitdate(s))
delta = str2date(s1) - str2date(s2)
return delta.days

print days_difference("20071112", "20061029") # 379

Although I'm sure there is a better way.

arnau

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


Re: uninstall python2.5 on debian

2007-09-22 Thread Martin v. Löwis
> I have tried make uninstall and searched the web, but that did not help me.
> I guess rm -Rf python2.5 is not a wise thing to do.

It's part of the solution. There is no automated install procedure; you
have to manually remove everything that got installed. In /bin,
it's most files that have 2.5 in their name, plus any links to them. In
/lib, it's python2.5. In /include, it's python2.5. Plus
a few things that I probably forgot.

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


Re: Building Python with VC8 on x64 Vista

2007-09-22 Thread Martin v. Löwis
> 1>py_dyn_test.obj : error LNK2001: unresolved external symbol
> _Py_NoneStruct

Could it be that py_dyn_test.obj is a x86 (not AMD64) object
file? Run dumpbin.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Bryan Olson
Carl Banks wrote:
> Not many people are bit-fiddling these days.  One of the main uses of bit 
> fields is flags, but that's not often done in Python because of keyword 
> arguments and dicts, which are lot more versatile.  Another major use, 
> talking to hardware, is not something oft done in Python either.
[...]
> Of course I'm not suggesting to get rid of bitwise operations altogether; 
> just make them builtin functions: "x & 1" becomes "bitwise_and(x,1)" and 
> so on.

Based on one informal survey (of my recollection), many
Pythoneers bit-twiddle, and all of them also know C. For
this population, Python's adoption of C's bitwise operators
helps avoid user-out-of-memory errors. Python even kept C's
counter-intuitive low precedence for shifts.

One surprising result was that more of the Python
programmers surveyed use bitwise operators than are aware
of the exponentiation operator, which C does not offer.

Possibly the study used a bias sample.


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


Re: Killing A Process By PID

2007-09-22 Thread Arvind Singh
> file('/var/lock/Application.lock', 'w').write(str(os.getpid()))
> >
> >  Which to be honest appears to run just fine, when I look in that file
> > it always contains the correct process ID, for instance, 3419 or something
> > like that.
> >
> I honestly doubt that. The I/O is buffered and you need to flush()/close()
> the file. Otherwise data may not get written until python interpreter exits.
>
>
> Isn't the file closed after the file().write()?  Seems to me that the
> great garbage collector in the sky will happily flush(), close() and forget
> it ever happened...
>

Yes, the GC will flush()/close() the file properly. My mistake, sorry about
that.

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

Re: Zope review

2007-09-22 Thread Bryan Olson
Sean Tierney wrote:
>>From Twisted's website "Twisted is a networking engine written in
> Python, supporting numerous protocols. It contains a web server,
> numerous chat clients, chat servers, mail servers, and more.
> 
> Given that Zope is also a written in python, supports numerous
> protocols, contains a webserver, has several chat packages available,
> a comparison/contrast would be quite useful.

You just got a useful comparison from Istvan Albert:

> Istvan Albert wrote:
>> Twisted is a networking engine, Zope is a web application framework,
>> Plone is a content management system, there is nothing to compare,
>> these are different applications altogether, it is not like you'd
>> replace one with the other
>>
>> For applications that can be compared see Zope vs Django vs Pylons vs
>> web.py vs CherryPy. Google these and contrast away.


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


can I run pythons IDLE from a command line??

2007-09-22 Thread [EMAIL PROTECTED]
Hi,
Is their a version of pythons IDLE that will run in a dos command
line?
The reason is that I would like to be able to run python code
interactively from my parable by connecting to my desktop using remote
command line or a telnet program.

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


Re: can I run pythons IDLE from a command line??

2007-09-22 Thread Thomas Jollans
On Saturday 22 September 2007, [EMAIL PROTECTED] wrote:
> Hi,
> Is their a version of pythons IDLE that will run in a dos command
> line?
> The reason is that I would like to be able to run python code
> interactively from my parable by connecting to my desktop using remote
> command line or a telnet program.

The Python interpreter should do fine. If your PATH environment variable is 
set up correctly, just run "python", otherwise it's somewhere in your Python 
installation directory.

-- 
  Regards,   Thomas Jollans
GPG key: 0xF421434B may be found on various keyservers, eg pgp.mit.edu
Hacker key :
v4sw6+8Yhw4/5ln3pr5Ock2ma2u7Lw2Nl7Di2e2t3/4TMb6HOPTen5/6g5OPa1XsMr9p-7/-6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frange() question

2007-09-22 Thread Carsten Haese
On Sat, 2007-09-22 at 07:27 +, John J. Lee wrote:
> Carsten Haese <[EMAIL PROTECTED]> writes:
> 
> > On Thu, 2007-09-20 at 18:55 +, John J. Lee wrote:
> >> Functions are never generators, senso stricto.  There are "generator
> >> functions", which *return* (or yield) generators when you call them.
> >
> > Actually, a generator function is a function that returns a generator.
> 
> Read what I wrote again.  What makes you begin your sentence with
> "Actually", rather than "Putting it another way"?

I was attempting to correct your interjection "(or yield)." A generator
function doesn't yield a generator; it returns a generator that yields
sequence values.

The second half of my post illustrates a difference of opinion about
what constitutes a generator function. You state that frange() is not a
generator function because it doesn't use yield, but it behaves like
one. My point is that it *is* a generator function because the generator
expression is merely syntactic sugar for an equivalent for/yield loop.

Of course, the distinction of whether frange() *is* a generator function
or merely *behaves* as one is immaterial in practice, and we can both be
right in the absence of a formal definition of what a generator function
is. PEP 255 says "A function that contains a yield statement is called a
generator function," but that was written before generator expressions
were introduced.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


unicode categories -- regex

2007-09-22 Thread koara
Hello all -- my question regards special meta characters for the re
module. I saw in the re module documentation about the possibility to
abstract to any alphanumeric unicode character with '\w'. However,
there was no info on constructing patterns for other unicode
categories, such as purely alphabetical characters, or punctuation
symbols etc.

I found that this category information actually IS available in python
-- in the standard module unicodedata. For example,
unicodedata.category(u'.') gives 'Po' for 'Punctuation, other' etc.

So how do i include this information in regular pattern search? Any
ideas? Thanks.


I'm talking about python2.5 here.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 06:58:57 -0700, Kay Schluehr wrote:

> On Sep 22, 1:15 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Sat, 22 Sep 2007 02:44:35 -0700, Kay Schluehr wrote:
>> > I checked out Io once and I disliked it. I expected Io's prototype OO
>> > being just a more flexible variant of class based OO but Io couples a
>> > prototype very closely to its offspring. When A produces B and A.f is
>> > modified after production of B also B.f is modified.  A controls the
>> > state of B during the whole lifetime of B. I think parents shall not
>> > do this, not in real life and also not in programming language
>> > semantics.
>>
>> Well it's like Python: inherited slots (attributes) are looked up in the
>> ancestors.  It should be easy to override `Object clone` in Io, so all
>> slots of the ancestor are shallow copied to the clone, but I guess this
>> might break existing code.  At least for your own code you could introduce
>> a `realClone` slot.
> 
> But in class based OO most relevant attributes are defined during
> object construction and they can't be simply changed by setting a
> class attribute. Later you often create new attributes as but on
> object level. You do not overuse the object/class relationship to
> broadcast changes to all objects.

You don't do this in Io either.  It's really like Python in this respect.
There's an `init` slot that gets called by (the default) `clone` and you
set "instance attributes" there, for example mutables so they are not
shared by all clones.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Bryan Olson
[EMAIL PROTECTED] wrote:
> There are already anonymous functions in Python.
> 
> lambda x, y, z: x + y + z
> 
> is the same as:
> 
> def _(x, y, z): return x + y + z

They are the same only in special cases:

 The special identifier "_" is used in the interactive
 interpreter to store the result of the last evaluation; it
 is stored in the __builtin__ module. When not in interactive
 mode, "_" has no special meaning and is not defined.
 [Python Reference Manual; 2.3.2 Reserved classes of
 identifiers. http://docs.python.org/ref/id-classes.html]


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread [EMAIL PROTECTED]
On Sep 21, 10:44?pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> Anyone with me here?  (I know the deadline for P3 PEPs has passed; this
> is just talk.)

Are you a loony?

Python doesn't have enough bit operations.

I'm always using the gmpy module's bit functions:

digits(...)
digits(x[,base]): returns Python string
representing x in the given base (2 to 36,
default 10 if omitted or 0); leading '-'
present if x<0, but no leading '+' if x>=0.
x must be an mpz, or else gets coerced into one.

getbit(...)
getbit(x,n): returns 0 or 1, the bit-value
of bit n of x; n must be an ordinary Python
int, >=0; x is an mpz, or else gets coerced
to one.

hamdist(...)
hamdist(x,y): returns the Hamming distance
(number of bit-positions where the bits
differ) between x and y.  x and y must be
mpz, or else get coerced to mpz.

lowbits(...)
lowbits(x,n): returns the n lowest bits of
x; n must be an ordinary Python int, >0;
x must be an mpz, or else gets coerced to one.

numdigits(...)
numdigits(x[,base]): returns length of string
representing x in the given base (2 to 36,
default 10 if omitted or 0); the value returned
may sometimes be 1 more than necessary; no
provision for any 'sign' characte, nor leading
'0' or '0x' decoration, is made in the returned
length.  x must be an mpz, or else gets coerced
into one.

popcount(...)
popcount(x): returns the number of 1-bits set
in x; note that this is 'infinite' if x<0,
and in that case, -1 is returned. x must be
an mpz, or else gets coerced to one.

scan0(...)
scan0(x, n=0): returns the bit-index of the
first 0-bit of x (that is at least n); n must
be an ordinary Python int, >=0.  If no more
0-bits are in x at or above bit-index n
(which can only happen for x<0, notionally
extended with infinite 1-bits), None is
returned. x must be an mpz, or else gets
coerced to one.

scan1(...)
scan1(x, n=0): returns the bit-index of the
first 1-bit of x (that is at least n); n
must be an ordinary Python int, >=0.  If no
more 1-bits are in x at or above bit-index
n (which can only happen for x>=0, notionally
extended with infinite 0-bits), None is returned.
x must be an mpz, or else gets coerced to one.

setbit(...)
setbit(x,n,v=1): returns a copy of the value
of x, with bit n set to value v; n must be
an ordinary Python int, >=0; v, 0 or !=0;
x must be an mpz, or else gets coerced to one.

And I don't do hardware, I do math research where
things like Hamming distance, popcount and scan1
are used extensively along with Python's bit
operators like >>.

Hey, I never use classes, maybe we should get rid of
them also, eh?

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Matthew Woodcraft
Cristian  <[EMAIL PROTECTED]> wrote:
> To me, the biggest setback for new programmers is the different
> syntax Python has for creating functions. Instead of the common (and
> easy to grasp) syntax of foo = bar Python has the def foo(): syntax.

[...]

> in a program like Python there doesn't seem to be any other reason to
> have it.

One reason for the different syntax is that functions, unlike most
other objects, know their own names (which can be shown in tracebacks
and the like).

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


Re: Help for Otsu implementation from C

2007-09-22 Thread azrael
Thanks Man, I did it. It works fantastic.


On Sep 19, 9:33 pm, azrael <[EMAIL PROTECTED]> wrote:
> I know. The translation is not so important to me, because this is
> going to just a little function that is working in the last step of
> the whole proces. The whole implementation wont be published and has
> just the meaning to implement a first alpha version of a face
> recognition system. It is nearly finished, and this is the only
> function I am missing. For this purpose I need it to work "EXACTLY".
>
> I know that it doesnt look pythonic. After I know that it works
> correctly, I am going to write a total Rewrite for the Beta Version.
>
> On Sep 19, 1:55 pm, Peter Otten <[EMAIL PROTECTED]> wrote:
>
> > azrael wrote:
> > > Can somone look at this
> > > def otsu(hi):
> > > fmax=-1.0
> > > border=len(hi)
> > > for i in range(border):
> > > if hi[i]!=0:break
> > > for j in range(border-1,0-1,-1):
> > > if hi[j] != 0:break
> > > s = sum([k*hi[k] for k in range(border)]) n = sum(hi) #
> > > product(im.size)
> > > n1=n2=csum=0.0
> > > for k in range(i,j):
> > > n1 += hi[k]
> > > n2  = n - n1
> > > csum+= k * hi[k]
> > > m1 = csum/ n1
> > > m2 = (s - csum)/n2
>
> > As I said in my previous post, try replacing this line
>
> > > sb = n1 * n2 * (m2 - m1)
>
> > with the original
>
> >   sb = n1 * n2 * (m1 - m2) * (m1 - m2)
>
> > that has been commented out.
>
> > > if sb > fmax:
> > > fmax = sb
> > > V=k+1
> > > print V
> > > I try to implement it from C from this location.
>
> > Personally, I would start with a literal translation and not try to
> > improve it until it works.
>
> > Peter


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


Video from image

2007-09-22 Thread azrael
I'd like to ask you if you know a module that makes it possible to
create a number of images and than to use them as frames and finaly
export them to a video file

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


Re: unicode categories -- regex

2007-09-22 Thread Martin v. Löwis
> So how do i include this information in regular pattern search? Any
> ideas?

At the moment, you have to generate a character class for this yourself,
e.g.

py> chars = [unichr(i) for i in range(sys.maxunicode)]
py> chars = [c for c in chars if unicodedata.category(c)=='Po']
py> expr = u'[\\' + u'\\'.join(chars)+"]"
py> expr = re.compile(expr)
py> expr.match(u"#")
<_sre.SRE_Match object at 0xb7ce1d40>
py> expr.match(u"a")
py> expr.match(u"\u05be")
<_sre.SRE_Match object at 0xb7ce1d78>

Creating this expression is fairly expensive, however, once compiled,
it has a compact representation in memory, and matching it is
efficient.

Contributions to support categories directly in re are welcome. Look
at the relevant Unicode recommendation on how to do that.

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


Re: Who can develop the following Python script into working application ?

2007-09-22 Thread http://members.lycos.co.uk/dariusjack/
On Sep 22, 4:25 pm, Andrey Khavryuchenko <[EMAIL PROTECTED]> wrote:
>  DBR> And as you said yourself:
>
>  DBR> """
>  DBR> Frankly speaking I would prefer to pay for your kind assistance
>  DBR> as it may take me to much time to learn some Python and understand the
>  DBR> following script.
>  DBR> """
>
>  DBR> Now, again:http://www.guru.com/There you can get devlopers for
>  DBR> money. So what again is your problem?
>
> Actually, I am a python (and django) developer, looking for a contract,
> owning Nokia 770 and contacted original poster with no response.
>
> --
> Andrey V Khavryuchenko  http://a.khavr.com/
> Chytach - unflood your feedshttp://www.chytach.com/
> Software Development Companyhttp://www.kds.com.ua/

Thanks Andrey,

if you mean having emailed me before.
I really sorry having to tell that I haven't got any email from you.
Don't use
Reply to author
feature by Google Groups
as any such email is not sent from your mailbox and you don't have a
copy of it.
Just read my e-mail and email me directly from your mailbox not Google
Groups.
At some groups Google diabled this option to contact original poster
personally
and even poster's email adresss is not avaliable.

Thanks for your interest.
Darius


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


Re: Video from image

2007-09-22 Thread Diez B. Roggisch
azrael schrieb:
> I'd like to ask you if you know a module that makes it possible to
> create a number of images and than to use them as frames and finaly
> export them to a video file

pymedia

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


Re: Who can develop the following Python script into working application ?

2007-09-22 Thread Diez B. Roggisch
Andrey Khavryuchenko schrieb:
>  DBR> And as you said yourself:
> 
>  DBR> """
>  DBR> Frankly speaking I would prefer to pay for your kind assistance
>  DBR> as it may take me to much time to learn some Python and understand the
>  DBR> following script.
>  DBR> """
> 
>  DBR> Now, again: http://www.guru.com/ There you can get devlopers for
>  DBR> money. So what again is your problem?
> 
> Actually, I am a python (and django) developer, looking for a contract,
> owning Nokia 770 and contacted original poster with no response.

Well, I presume the above quoted wasn't exactly true - in the end, the 
whole attitude of the OP smelled after "I want you to do work for me for 
free that I'm unwilling to bother myself with - as it would mean putting 
effort into it."

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread richyjsm
On Sep 22, 11:13 am, Bryan Olson <[EMAIL PROTECTED]> wrote:
> One surprising result was that more of the Python
> programmers surveyed use bitwise operators than are aware
> of the exponentiation operator, which C does not offer.

On that subject, I'd suggest that the pow() builtin (not the **
operator - just the pow() function) should also be a candidate for
removal...

Richard


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


Properties and Objects...

2007-09-22 Thread George V. Neville-Neil
I have been reading the mailing list and I am unfortunately going to
open up discussion I've seen twice in the last two years but which
still bugs me, so please accept my apologies in advance.

I have been working on a set of modules that make objects which look
like network packets (http://pcs.sf.net) in that you can set up a
class, say ipv4, which when instantiated has the following properties:

>>> from pcs.packets.ipv4 import *
>>> ip = ipv4()
>>> ip.bytes
'@[EMAIL PROTECTED]'
>>> ip.ttl
64
>>> ip.ttl=32
>>> ip.bytes
'@\x00\x00\x00\x00\x00\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> 

Note that setting the ttl in the packet changes the underlying bytes.
Doing this makes writing network tests, and other networking code,
extremely easy.

This is done by having Field classes which are collected into a list
in a Packet class (the layout) and by doing special setattr/getattr
calls.

I have been trying to switch this over to using properties, which seem
at first glance to be cleaner, but which I am having a lot of problems
with.  In particular I want to add a property to an object, not a
class.  The field list in a class is actually relatively static but I
wind up with ugly code like:

class ethernet(pcs.Packet):
"""Ethernet"""
__layout__ = pcs.Layout()
_map = ethernet_map.map

src = pcs.StringField("src", 48)
dst = pcs.StringField("dst", 48)
type = pcs.Field("type", 16)

def __init__(self, bytes = None, timestamp = None):
"""initialize an ethernet packet"""

src = pcs.StringField("src", 48)
dst = pcs.StringField("dst", 48)
type = pcs.Field("type", 16)

pcs.Packet.__init__(self, [dst, src, type], bytes = bytes)
self.description = inspect.getdoc(self)

and assigning the properties at class time means that it's hard to
have variations, packets with the same name but with slightly varying
field lists.

So, is there a way to assign a property to an object, like this:

def __init__(
 self.src = property()

or something like that?

And, failing that, is there a clean way to modify the class in it's
__init__() method so I don't have to call the Field objects twice,
once for the property effect and once to put into the list in the base
Packet class?

With my somewhat convoluted setattr/getattr implementation the
Ethernet class looked like this:

class ethernet(pcs.Packet):
"""Ethernet"""
__layout__ = pcs.Layout()
_map = ethernet_map.map

def __init__(self, bytes = None, timestamp = None):
"""initialize an ethernet packet"""

src = pcs.StringField("src", 48)
dst = pcs.StringField("dst", 48)
type = pcs.Field("type", 16)

pcs.Packet.__init__(self, [dst, src, type], bytes = bytes)
self.description = inspect.getdoc(self)

which was much more straightforward for someone to understand and to
code.  Since one of the project goals is to have the creation of new
packets classes be as easy as possible I would like to be able to do
something closer to the above.

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


Re: frange() question

2007-09-22 Thread John J. Lee
Carsten Haese <[EMAIL PROTECTED]> writes:

> On Sat, 2007-09-22 at 07:27 +, John J. Lee wrote:
>> Carsten Haese <[EMAIL PROTECTED]> writes:
>> 
>> > On Thu, 2007-09-20 at 18:55 +, John J. Lee wrote:
>> >> Functions are never generators, senso stricto.  There are "generator
>> >> functions", which *return* (or yield) generators when you call them.
>> >
>> > Actually, a generator function is a function that returns a generator.
>> 
>> Read what I wrote again.  What makes you begin your sentence with
>> "Actually", rather than "Putting it another way"?
>
> I was attempting to correct your interjection "(or yield)." A generator
> function doesn't yield a generator; it returns a generator that yields
> sequence values.

OK.  There's an obvious second language issue here (the first being
the generator / generator function), which I was trying to draw
attention away from, in the interests of explaining the concept, and
the first language issue.  Probably a bad idea!


> The second half of my post illustrates a difference of opinion about
> what constitutes a generator function. You state that frange() is not a
> generator function because it doesn't use yield, but it behaves like
> one. My point is that it *is* a generator function because the generator
> expression is merely syntactic sugar for an equivalent for/yield loop.

Seems to me that's a definitional thing, with no conceptual content,
so "difference of opinion" seems an odd choice of words.  It would be
nice to nail the definitions down.  Do the Python docs do that?


> Of course, the distinction of whether frange() *is* a generator function
> or merely *behaves* as one is immaterial in practice, and we can both be
> right in the absence of a formal definition of what a generator function
> is. PEP 255 says "A function that contains a yield statement is called a
> generator function," but that was written before generator expressions
> were introduced.

Ah, they do -- thanks.  Though I'm now left puzzled why you express
your "difference of opionion" above...


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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Paul Rubin
Bryan Olson <[EMAIL PROTECTED]> writes:
> [EMAIL PROTECTED] wrote:
> > There are already anonymous functions in Python.
> > lambda x, y, z: x + y + z
> > is the same as:
> > def _(x, y, z): return x + y + z
> 
> They are the same only in special cases:
>  The special identifier "_" is used in the interactive
>  interpreter to store the result of the last evaluation...

I'm not sure what Chris was really getting at, since among other
things lambda:... is an expression while def... is a statement.
But Python certainly has anonymous functions without lambda:

   def compose(f,g):
 def h(*a, **k):
   return f(g(*a, **k))
 return h

   x = compose(math.sin, math.cos)(1.0)

computes sin(cos(1.0)) where a function equivalent to 
  lambda x: sin(cos(x))
is constructed and used without being bound to a symbol.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Paul Rubin
Carl Banks <[EMAIL PROTECTED]> writes:
> If anyone says, "But that takes away an easy test for oddness (x&1)!", 
> or, "But you can multiply powers of two using left shift!  Isn't that 
> cool?", I'm not buying it.  Those are gimmicks.  Arithmetic operations 
> should be done with arithmetic operators.  The bitwise operators make the 
> code much less readable, especially to people unfamiliar with this usage.

The bitwise operators are used for set operations, which were
added fairly recently, if that hasn't been mentioned yet.  They
make good sense for that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread Zentrader
On Sep 22, 2:37 am, Konstantinos Pachopoulos <[EMAIL PROTECTED]>
wrote:
> Hi,
> does any body now any such algorith? to find difference in days from
> MMDD to MMDD?
> Or just an algorithm, that converts MMDD to seconds since the epoch?
>
> Thanks

For some reason, to-seconds-since-epoch is in the calendar class.
calendar.timegm() takes a tuple and returns the epoch seconds
import time
import calendar

today_secs = calendar.timegm( (2007, 9, 22, 0, 0, 0) )
print today_secs
one_day = 24*60*60
print time.gmtime( today_secs+one_day )

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Bryan Olson
Cristian wrote:
> [...] Specifically, he's having trouble
> thinking of functions as first order data (don't worry, I haven't
> confused him with such terminology yet). 
[...]
> And, after we finally
> get a hold of first order functions, we appreciate its incorporation
> into languages. It would be a shame if my friend just learns the
> motions and never incorporates first order functions into his
> programs. 


The terminology I've heard for this is that functions are
"first-class values". There's a minor name-collision on
"class", but people have heard "first-class" in other
contexts, and it means the same thing here: no second-class
status for such values.

"First order" has other usages, some contradicting what you
mean. First-order functions are exactly those that cannot
take functions as arguments. It would be a shame if your
friend never incorporates *higher order* functions.
[http://en.wikipedia.org/wiki/Higher-order_function]


[...]
> my_function = function(foo, bar): pass
> an_instance_method = function(self, foo): pass
> a_method_declaration = method(self, foo): pass

I just argued for adopting mainstream terminology, but here
I like yours better. The keyword "lambda" sucks. All the
other keywords, having been so carefully chosen to relate
to their conversational usage, have mis-trained to look
at this spelling-out of the name of an arbitrary symbol.

Alonzo Church's calculus used the *symbol*. He just needed
it to be distinct. Could as well have been the '$-calculus'.

Function-as-value is not a trivial concept. I remember
wrestling with it, and I've seen many others do the same.
The 'lambda' keyword is so awful as to pass for deep
mystery long after students have grasped first-class
functions.


"function" would be a much better keyword. Or follow ML and
abbreviate to "fn", or choose another term that clues one
in to the meaning. I'd have caught on much quicker given a
a hint to read:

lambda x, y: x + y

as: "the function of two variables, call them x and y, that
returns x + y."


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


Re: I could use some help making this Python code run faster using only Python code.

2007-09-22 Thread Python Maniac
On Sep 21, 11:39 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Fri, 21 Sep 2007 16:25:20 -0700, Python Maniac wrote:
> > On Sep 21, 3:02 pm, "Matt McCredie" <[EMAIL PROTECTED]> wrote:
>
> >> Isn't D compiled to machine code? I would expect it to win hands down.
> >> That is, unless it is horribly unoptimized.
>
> > Well D code is compiled into machine code that runs via a VM.
>
> About which D are we talking here?  Not digital mars' successor to C++,
> right!?
>
> Ciao,
> Marc 'BlackJack' Rintsch

Yes, Digital Mars D is what I was referring to and yes I know D is not
as efficient as C++.  If I knew of a good C++ compiler that is not
from Microsoft that works natively with Windows I would be happy to
consider using it but alas the only one I have found so far is from
Digital Mars.  Digital Mars D has nice integration with Python via pyd
and this is another plus, in my mind.


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


Re: I could use some help making this Python code run faster using only Python code.

2007-09-22 Thread Python Maniac
On Sep 21, 12:56 am, Duncan Booth <[EMAIL PROTECTED]>
wrote:
> George Sakkis <[EMAIL PROTECTED]> wrote:
> > It has to do with the input string length; try multiplying it by 10 or
> > 100. Below is a more complete benchmark; for largish strings, the imap
> > version is the fastest among those using the original algorithm. Of
> > course using a lookup table as Diez showed is even faster. FWIW, here
> > are some timings (Python 2.5, WinXP):
>
> > scramble:   1.818
> > scramble_listcomp:  1.492
> > scramble_gencomp:   1.535
> > scramble_map:   1.377
> > scramble_imap:  1.332
> > scramble_dict:  0.817
> > scramble_dict_map:  0.419
> > scramble_dict_imap: 0.410
>
> I added another one:
>
> import string
> scramble_translation = string.maketrans(''.join(chr(i) for i in xrange
> (256)), ''.join(chr(i|0x80) for i in xrange(256)))
> def scramble_translate(line):
> return string.translate(line, scramble_translation)
>
> ...
> funcs = [scramble, scramble_listcomp, scramble_gencomp,
>  scramble_map, scramble_imap,
>  scramble_dict, scramble_dict_map, scramble_dict_imap,
>  scramble_translate
>  ]
>
> and I think I win:
>
> scramble:   1.949
> scramble_listcomp:  1.439
> scramble_gencomp:   1.455
> scramble_map:   1.470
> scramble_imap:  1.546
> scramble_dict:  0.914
> scramble_dict_map:  0.415
> scramble_dict_imap: 0.416
> scramble_translate: 0.007

Some benchmarks showing the effectiveness of using Psyco:

scramble:   4.210
scramble_listcomp:  2.343
scramble_gencomp:   2.599
scramble_map:   1.960
scramble_imap:  2.231
scramble_dict:  2.387
scramble_dict_map:  0.535
scramble_dict_imap: 0.726
scramble_translate: 0.010

Now with Psyco...
psyco.bind(scramble)...
scramble:   0.121   4.088   34.670x faster
scramble_listcomp:  0.215   2.128   10.919x faster
scramble_gencomp:   2.563   0.036   1.014x faster
scramble_map:   2.002   -0.043  0.979x slower
scramble_imap:  2.175   0.056   1.026x faster
scramble_dict:  0.199   2.188   11.983x faster
scramble_dict_map:  0.505   0.029   1.058x faster
scramble_dict_imap: 0.728   -0.001  0.998x slower
scramble_translate: 0.009   0.001   1.111x faster

Overall, Psyco helped my little process of converting 20 MB worth of
ASCII into what may not look like the original at 6x faster than
without Psyco.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Carl Banks
On Sat, 22 Sep 2007 12:57:35 +, Grant Edwards wrote:
> On 2007-09-22, Carl Banks <[EMAIL PROTECTED]> wrote:
>> Of course it would be.  The reason I mention it is that automatic
>> convertibility is a key factor in whether a change can make it into
>> Python 3.
> 
> It matters not whether fugly code is automatically generated or manually
> generated.  It's still hard to read and maintain.

By my understanding, it really doesn't matter that much.

The transition tool's purpose is to allow a subset of 2.x code to run on 
3.x, so that developers don't have to maintain separate codebases to 
support both.  The 3.x code that is produced isn't intended to be read or 
maintained.  So no big deal if it's a little ugly.  (But there's still 
tracebacks to read and regressions to debug, so I guess it can't be too 
ugly.)


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Carl Banks
On Sat, 22 Sep 2007 14:50:12 +, Paddy wrote:
> Sorry Carl,
> I think *you* may not have much need for bitwise operators but others,
> including myself do. No matter what the usage found, I would think
> replacing bitwise operators by function calls a retrograde step.

Well, if people are going to take the suggestion this personally, maybe 
that's reason enough not to bother.


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Terry Reedy

"Carl Banks" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| | Is it worth it to make such a change?  It would remove a lot of 
operators
| (11 by my count), vastly simplifying syntax,  Which, IMHO, is no small
| thing.  New numerical types would have fewer operations to support.

Py3 adds an abstract base class module.  Bit-integers (with the above 
operations) are a separate subclass of abstract int/rats (forget the 
detail), so new numerical types do not have to support those ops unless 
declared as deriving from the bit-int class.

Some people consider having lots of operators available to overload in 
their classes to be a good thing.  Operator notation is much nicer that 
function notation for binary functions.mapping pairs of objects of a class 
to an object of the class.

tjr



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


Re: An Editor that Skips to the End of a Def

2007-09-22 Thread Stefan Behnel
W. Watson wrote:
> Bruno Desthuilliers wrote:
>> W. Watson a écrit :
>>> How about in the case of MS Win?
>>>
>>> Ben Finney wrote:

 (Please don't top-post. Instead, reply below each point to which
 you're responding, removing quoted text irrelevant to your response.)

>>
>> Wayne, may I second Ben on his suggestion to stop top-posting ?
> 
> Well, you may. Unfortunately, there are many NGs that do the opposite.

Well, not this one.

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

Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Bryan Olson
Paul Rubin wrote:
> Bryan Olson <[EMAIL PROTECTED]> writes:
>> [EMAIL PROTECTED] wrote:
>>> There are already anonymous functions in Python.
>>> lambda x, y, z: x + y + z
>>> is the same as:
>>> def _(x, y, z): return x + y + z
>> They are the same only in special cases:
>>  The special identifier "_" is used in the interactive
>>  interpreter to store the result of the last evaluation...
> 
> I'm not sure what Chris was really getting at, 

I was big-time unsure. At first, I thought Chris's latter
form to be equivalent to a pass statement. I've long used
the Python convention of assigning throw-away values to '_',
and I was under the mistaken impression Python defined _
as a discard target.

When I looked it up, I was surprised to find that my
understanding of the _ variable was wrong, and shocked that
there really is an interesting context where Chris's claim
has a strong case.


> since among other
> things lambda:... is an expression while def... is a statement.

True fact, but note that one form of statement is an expression.

> But Python certainly has anonymous functions without lambda:
> 
>def compose(f,g):
>  def h(*a, **k):
>return f(g(*a, **k))
>  return h
> 
>x = compose(math.sin, math.cos)(1.0)
> computes sin(cos(1.0)) where a function equivalent to 
>   lambda x: sin(cos(x))
> is constructed and used without being bound to a symbol.

How anonymous is that function when we can see that its name is 'h'?

 import math

 f = compose(math.sin, math.cos)
 print f.__name__

Am I making a bogus argument? Kind of. Most authors of "anonymous"
works do in fact have real names. The term really means that they
entered the context at issue dissociated from their given name.
Nevertheless, def is never a real anonymous function constructor.

If our concern is Python's suitability for studying principles of
programming, I think I'm on stronger ground. Python is great for
getting things done. It is easy to learn in the sense of learning
to to use if for practical tasks. Python's actual semantics are not
as neat and clean as some other languages.


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


Re: frange() question

2007-09-22 Thread Carsten Haese
On Sat, 2007-09-22 at 18:21 +, John J. Lee wrote:
> Carsten Haese <[EMAIL PROTECTED]> writes:
> > The second half of my post illustrates a difference of opinion about
> > what constitutes a generator function. You state that frange() is not a
> > generator function because it doesn't use yield, but it behaves like
> > one. My point is that it *is* a generator function because the generator
> > expression is merely syntactic sugar for an equivalent for/yield loop.
> 
> Seems to me that's a definitional thing, with no conceptual content,
> so "difference of opinion" seems an odd choice of words.  It would be
> nice to nail the definitions down.  Do the Python docs do that?
> 
> 
> > Of course, the distinction of whether frange() *is* a generator function
> > or merely *behaves* as one is immaterial in practice, and we can both be
> > right in the absence of a formal definition of what a generator function
> > is. PEP 255 says "A function that contains a yield statement is called a
> > generator function," but that was written before generator expressions
> > were introduced.
> 
> Ah, they do -- thanks.  Though I'm now left puzzled why you express
> your "difference of opionion" above...

It's a matter of opinion whether the excerpt from the PEP constitutes
the formal definition of what a generator function is or isn't. A formal
definition needs conditions that are both sufficient and necessary. The
PEP only says that having a yield statement is sufficient for making a
generator function. It doesn't say that a yield statement is necessary
for making a generator function. In other words, it doesn't say that a
function that doesn't contain a yield statement isn't a generator
function.

The language reference is equally wishy-washy: "Using a yield statement
in a function definition is *sufficient* to cause that definition to
create a generator function instead of a normal function." [emphasis
mine]

Again, no indication that a yield statement is necessary for making a
generator function. It then proceeds to saying "When a generator
function is called, it returns an iterator known as a generator
iterator, or more commonly, a generator." That condition seems to be
true for the OP's frange() function, even though it doesn't have a yield
statement.

Until somebody can point out a definition that says unequivocally "an
object is a generator function if and only if ...", it's up in the air
whether frange() is a generator function or merely impersonates a
generator function. Ultimately, though, this is a purely academic
question without a useful answer. The useful conclusion is that a
function can behave like a generator function without a yield statement,
and we have reached that conclusion a long time ago.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


too many values with string.split

2007-09-22 Thread Shawn Minisall
I'm trying to unpack a list of 5 floats from a list read from a file and 
python is telling me 5 variables are too many for the string.split 
statement.  Anyone have any other idea's?  NOTE: the only reason I 
convert it to a float instead of just leaving it as a string in the loop 
is because I have to have it printed out as a float besides the names 
and then the average displayed underneath

thx

#read in data line by line
for line in infile:
mylist = string.split(line)
firstName[counter] = mylist[0]
lastName[counter] = mylist[1]
grades[counter] = float(mylist[2])
print firstName[counter], 
lastName[counter],":","\t\t",grades[counter]
#increment counter
counter = counter + 1

#calculates and prints average score
grades = str(grades)
num1, num2, num3, num4, num5 = string.split(grades,",")
average = float(num1 + num2 + num3 + num4 + num5) / 5
print
print "Average:"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Paul Rubin
Bryan Olson <[EMAIL PROTECTED]> writes:
> How anonymous is that function when we can see that its name is 'h'?

h is out of scope after compose returns, so the function is anonymous
in the sense that there is no symbol bound to the function, through
which you can refer to it.

>  import math
> 
>  f = compose(math.sin, math.cos)
>  print f.__name__

I prefer to think of __name__ as just some debugging info stuck inside
the closure, though actually Python is introspective enough to be able
to let you locate and call a function whose __name__ is "h".  Of
course there might be more than one:

f = compose(math.sin, math.cos)
g = compose(math.sqrt, math.tan)
print f.__name__, g.__name__

> Nevertheless, def is never a real anonymous function constructor.

Well, def constructs a function with a name, but the function can stay
around after the name goes away, after which I'd say the function is
nameless.  One could otherwise say that (lambda x: x+x) is not
anonymous either, since id(lambda ...) is a unique label stuck to it
like a __name__.

> If our concern is Python's suitability for studying principles of
> programming, I think I'm on stronger ground. Python is great for
> getting things done. It is easy to learn in the sense of learning
> to to use if for practical tasks. Python's actual semantics are not
> as neat and clean as some other languages.

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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Erik Max Francis
Kay Schluehr wrote:

> I checked out Io once and I disliked it. I expected Io's prototype OO
> being just a more flexible variant of class based OO but Io couples a
> prototype very closely to its offspring. When A produces B and A.f is
> modified after production of B also B.f is modified. A controls the
> state of B during the whole lifetime of B. I think parents shall not
> do this, not in real life and also not in programming language
> semantics.

It sounds like you're talking about some language other than Io, or 
didn't delve deeply enough into it, since Io makes no such requirements.

The attribute and method (not made distinct in Io; they're called 
"slots") is much the same as with Python; the current instance is 
checked for the object, then its parents, then _its_ parents, and so on.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   No man quite believes in any other man.
-- H.L. Mencken
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Bryan Olson
[EMAIL PROTECTED] wrote:
> Bryan Olson  wrote:
>> One surprising result was that more of the Python
>> programmers surveyed use bitwise operators than are aware
>> of the exponentiation operator, which C does not offer.
> 
> On that subject, I'd suggest that the pow() builtin (not the **
> operator - just the pow() function) should also be a candidate for
> removal...

A darn good candidate, I'd say. I'm biased because I once took
quite a while to figure out that importing the math module's
'pow' was how I broke my code.

The operator module offers pow(). Is there any good reason for
pow() as a built-in?


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


Re: An Editor that Skips to the End of a Def

2007-09-22 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote:

> Lawrence D'Oliveiro wrote:
>
>> After two decades of putting up with vi just to ensure
>> compatibility with every proprietary *nix system I might come
>> across, let me just say ...
>> 
>> USE EMACS!
> 
> Nah. Use vim.

Every other text editor I have ever used understands that the current
position in a file is _between_ two characters (or before the first
character, or after the last character), not _on_ a character. But not vi
and its ilk.

Try the following in vi/vim: Move to some point in the middle of a line.
Press "i" to get into insert mode. Press escape to get out again. You'll
end up one position to the left of where you were before. Press "i", and
then escape again--you've moved another position left. Why is it incapable
of keeping track of such a simple thing as your current position in the
file?

Why does it need two different insert commands, "i" versus "a"? Because one
of them can't insert at the end of a line, and the other can't insert at
the beginning.

And why have command-versus-insert mode at all? No other text editor still
surviving uses such an antiquated concept.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: too many values with string.split

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 17:00:47 -0400, Shawn Minisall wrote:

> I'm trying to unpack a list of 5 floats from a list read from a file and 
> python is telling me 5 variables are too many for the string.split 
> statement.

Please post the *real* message which I suspect is something like 'too many
values to unpack', which is the other way around.  The 5 names are not
enough to take all the items from the split.

> #read in data line by line
> for line in infile:
> mylist = string.split(line)

Functions in the `string` module that are also available as methods on
strings are deprecated.

> firstName[counter] = mylist[0]
> lastName[counter] = mylist[1]
> grades[counter] = float(mylist[2])
> print firstName[counter], 
> lastName[counter],":","\t\t",grades[counter]
> #increment counter
> counter = counter + 1

Do you really need the counter?  Can't you just append the values to the
lists?

> #calculates and prints average score
> grades = str(grades)
> num1, num2, num3, num4, num5 = string.split(grades,",")
> average = float(num1 + num2 + num3 + num4 + num5) / 5

This is very strange.  You have a list of floats (I guess), convert that
list to a string, split that string at commas, concatenate the *strings*
between commas and then try to convert it to a `float`!?  This is likely
not what you want and should fail in most cases anyway.

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


Re: I could use some help making this Python code run faster using only Python code.

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 13:00:27 -0700, Python Maniac wrote:

> On Sep 21, 11:39 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Fri, 21 Sep 2007 16:25:20 -0700, Python Maniac wrote:
>>
>> > Well D code is compiled into machine code that runs via a VM.
>>
>> About which D are we talking here?  Not digital mars' successor to C++,
>> right!?
> 
> Yes, Digital Mars D is what I was referring to and yes I know D is not
> as efficient as C++.

But D code doesn't run in a VM unless you see hardware processors as VMs.

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


Re: too many values with string.split

2007-09-22 Thread Alain
Shawn Minisall a écrit :
> I'm trying to unpack a list of 5 floats from a list read from a file and 
> python is telling me 5 variables are too many for the string.split 
> statement.  Anyone have any other idea's?  NOTE: the only reason I 
> convert it to a float instead of just leaving it as a string in the loop 
> is because I have to have it printed out as a float besides the names 
> and then the average displayed underneath
> 
> thx
> 
>#read in data line by line
>for line in infile:
>mylist = string.split(line)
>firstName[counter] = mylist[0]
>lastName[counter] = mylist[1]
>grades[counter] = float(mylist[2])
>print firstName[counter], 
> lastName[counter],":","\t\t",grades[counter]
>#increment counter
>counter = counter + 1
> 
>#calculates and prints average score
>grades = str(grades)
>num1, num2, num3, num4, num5 = string.split(grades,",")
>average = float(num1 + num2 + num3 + num4 + num5) / 5
>print
>print "Average:"

As I can see, grades is a string that looks like '[12.0,12.0, ...]'

So you can't split it just with string.split ()

Rather than doing grades = str(grades) and split it,
you have just to do :

avarage = sum (grades) / len (grades)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode categories -- regex

2007-09-22 Thread koara
> At the moment, you have to generate a character class for this yourself,
> e.g.
> ...


Thank you Martin, this is exactly what i wanted to know.

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Grant Edwards
On 2007-09-22, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Sat, 22 Sep 2007 12:57:35 +, Grant Edwards wrote:
>> On 2007-09-22, Carl Banks <[EMAIL PROTECTED]> wrote:
>>> Of course it would be.  The reason I mention it is that automatic
>>> convertibility is a key factor in whether a change can make it into
>>> Python 3.
>> 
>> It matters not whether fugly code is automatically generated or manually
>> generated.  It's still hard to read and maintain.
>
> By my understanding, it really doesn't matter that much.
>
> The transition tool's purpose is to allow a subset of 2.x code to run on 
> 3.x, so that developers don't have to maintain separate codebases to 
> support both.  The 3.x code that is produced isn't intended to be read or 
> maintained.  So no big deal if it's a little ugly.

Eh?  If you remove bitwise operators, then doing bitwise
operations is going to be ugly, hard to write, and hard to read
and maintain.  I don't see what 2.x vs. 3.x vs. a "transition
tool" has to do with it.

-- 
Grant Edwards   grante Yow!  People humiliating
  at   a salami!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Marc 'BlackJack' Rintsch
On Sat, 22 Sep 2007 21:17:38 +, Bryan Olson wrote:

> The operator module offers pow(). Is there any good reason for
> pow() as a built-in?

The `operator.pow()` is  just the function for ``**``, it lacks the
optional third argument of the built in `pow()`.

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


database persistence with mysql, sqlite

2007-09-22 Thread coldpizza
Hi,

I want to run a database query and then display the first 10 records
on a web page. Then I want to be able to click the 'Next' link on the
page to show the next 10 records, and so on.

My question is how to implement paging, i.e. the 'Next/Prev' NN
records without reestablishing a database connection every time I
click Next/Prev? Is it at all possible with cgi/mod_python?

For example, in a NON-web environment, with sqlite3 and most other
modules, I can establish a database connection once, get a cursor
object on which I run a single 'SELECT * FROM TABLE' statement and
then use cursor.fetchmany(NN) as many times as there are still results
left from the initial query.

How do I do the same for the web? I am not using any high-level
framework. I am looking for a solution at the level of cgi or
mod_python (Python Server Pages under Apache). To call
cursor.fetchmany(NN) over and over I need to pass a handle to the
database connection but how do I keep a reference to the cursor object
across pages? I use mysql and sqlite3 as databases, and I am looking
for an approach that would work with both database types (one at a
time). So far I have successfully used the following modules for
database access: sqlite3, mysqld, and pyodbc.

So far, with mysql I use 'SELECT * FROM TABLE LIMIT L1, L2' where L1
and  L2 define the range for the 'Next' and 'Previous' commands. I
have to run the query every time a click a 'Next/Prev' link. But I am
not sure that this is the best and most efficient way. I suppose using
CURSOR.FETCHMANY(NN) would probably be faster and nicer but how do I
pass an object reference across pages? Is it possible without any
higher-level libraries?

What would be the proper way to do it on a non-enterprise scale?

Would SqlAlchemy or SqlObject make things easier with regard to
database persistence?

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


Threading preemption questions

2007-09-22 Thread Kurtis Heimerl
Hi, I'm developing my first python application, a multi-threaded cell phone
gadget on ubuntu 7.10. I've just split off my first thread, and I've noticed
something extremely strange: There doesn't seem to be any preemption. There
are currently two threads, one that pings a storage service to see if there
are messages available, and the other that runs the gtk windows. If I do not
explicitly yield either one, it runs forever. I'm assuming this is a setting
somewhere, but that's a very strange default behavior.

How do I get this to go about preempting these threads? Any advice would be
helpful. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread richyjsm
On Sep 22, 7:04 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sat, 22 Sep 2007 21:17:38 +, Bryan Olson wrote:
> > The operator module offers pow(). Is there any good reason for
> > pow() as a built-in?
>
> The `operator.pow()` is  just the function for ``**``, it lacks the
> optional third argument of the built in `pow()`.
>
> Ciao,
> Marc 'BlackJack' Rintsch

But does the three-argument version of pow() really belong in the
core?  Who uses it?  It seems very much like a specialist's function
to me:  certainly it wouldn't be out of place in the standard library
somewhere (perhaps a cryptography or number theory module), but in its
three argument form it has to be one of the least used core functions.

Richard

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Steven D'Aprano
On Sat, 22 Sep 2007 18:09:49 +, richyjsm wrote:

> On that subject, I'd suggest that the pow() builtin (not the ** operator
> - just the pow() function) should also be a candidate for removal...

Help on built-in function pow in module __builtin__:

pow(...)
pow(x, y[, z]) -> number

With two arguments, equivalent to x**y.  With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).


Everybody forgets that pow can take three arguments, except of course for 
those who use that functionality and would be mighty peeved if it went 
away.



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


Re: Would Anonymous Functions Help in Learning Programming/Python?

2007-09-22 Thread Steven D'Aprano
On Sat, 22 Sep 2007 14:09:13 -0700, Paul Rubin wrote:

>> Nevertheless, def is never a real anonymous function constructor.
> 
> Well, def constructs a function with a name, but the function can stay
> around after the name goes away, after which I'd say the function is
> nameless.  One could otherwise say that (lambda x: x+x) is not anonymous
> either, since id(lambda ...) is a unique label stuck to it like a
> __name__.

If you want to be tediously pedantic, lambda doesn't construct anonymous 
functions either: you can bind them to a name, and whether you do or not, 
they have a name.

>>> f = lambda: 3
>>> f.__name__
''

It's just that all functions created by lambda share the same name.

If you really want an anonymous function...

>>> def foo():
... return 3
...
>>> foo.__name__ = ''
>>> foo



I know, I know, I'm being tediously pedantic... and that's not what the 
anonymity of lambda refers to. What it actually means is that the lambda 
doesn't create a name in a namespace. In that regard, calling a factory 
function is also anonymous, because the function isn't added to the 
calling code's namespace.

Or, to put it another way...

def factory():
def foo():
return 3
return foo


Within factory(), foo() is not an anonymous function, because 'foo' is in 
the local namespace. But the result of factory() is anonymous in the same 
sense that lambda is: although the function object has a attribute 
__name__ set to 'foo', calling factory() doesn't modify the caller's 
namespace (unless you assign the result to a name).


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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread richyjsm
On Sep 22, 7:50 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> Everybody forgets that pow can take three arguments, except of course for
> those who use that functionality and would be mighty peeved if it went
> away.

And who is it who uses this functionality?  It's useful in elementary
number theory, sure, but I'd argue that if there are going to be
number theoretical functions in the core then there are other things,
like gcd(), that are far more deserving of inclusion.  It comes up in
the RSA cryptosystem, but if you're using Python's pow for this then
you're surely only writing a toy RSA implementation, perhaps for
educational purposes(?).  Neither of these seem like compelling
arguments to have pow in the core.

Richard

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread George Sakkis
On Sep 22, 3:29 pm, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Sat, 22 Sep 2007 14:50:12 +, Paddy wrote:
> > Sorry Carl,
> > I think *you* may not have much need for bitwise operators but others,
> > including myself do. No matter what the usage found, I would think
> > replacing bitwise operators by function calls a retrograde step.
>
> Well, if people are going to take the suggestion this personally, maybe
> that's reason enough not to bother.
>
> Carl Banks

If you want to push it further, one argument could be along the lines
of "ok, apparently bit fiddling is important for some classes of
problems but so are regular expressions. Are bit operations so
frequent and/or important to grant them around a dozen of operators
while there are none for regexps ?"

George

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


Re: Odd files; just left behind?

2007-09-22 Thread Robert Kern
Robin Becker wrote:
> Robert Kern wrote:
> ...
>> They're a cache.
> 
> they're actually the files that get used by the installed extension in 
> this case (MySQLdb).

Yes. They are extracted from the zipfile at runtime and left there so they don't
have to be extracted again. That's why I called it a cache. I didn't mean
anything else by the term.

> ..
>>> it would seem simpler to have the .so files inside the site-packages and 
>>> there's 
>>> the question of why this folder has to be obfuscated (name starts with .). 
>>> Even 
>>> if these files are "resources" why should they be assumed to belong to the 
>>> user?
>> Because they are unpacked at runtime by the user that imported the module.
>> Usually, they won't have write access to site-packages.
> 
> in this particular case the python being used was installed with a user 
> prefix eg /myhome/PYTHON so everything belongs to the user; extensions 
> installed by the same user can surely be installed in those folders. 
> Upon checking I find that the same installs which produced the 
> ~/.python-eggs files also managed to put  the eggs like 
> MySQL_python-1.2.2-py2.3-freebsd-6.1-SECURITY-i386.egg inside the 
> various site-packages directories.
> 
> I see no reason why the binary resources shouldn't be unpacked to 
> site-packages at install time.

Then do so: Use the -Z argument to easy_install such that it always unpacks the
zip file. If you don't, then the egg will be left zipped, and the resources
extracted at runtime. Zipped eggs have benefits over the unzipped eggs in that
they decrease the amount of import overhead of having many items in your 
sys.path.

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


Small changes in side library

2007-09-22 Thread [EMAIL PROTECTED]
Hi, all!

May be this question have been already discussed, but I found nothing
closer :-/
I have the side library which provides wide set of different
functions, but I'm going to replace some of them with mine and
provided such 'modified' library thought my project.

The following way works well for my purpose:

--- mylib.py ---
import sidelib

import os, sys, 

def func():
.
sidelib.func = func
..
?!?!?!?!
--

But this cause to write mylib.sidelib.func() to function call, is it
any way to 'map' definitions from sidelib to mylib (possible at point
marked ?!?!?!?!) such that constructions like mylib.func() will be
provided and client code don't see difference between changed and
original library in syntax way?

One my idea was to do from sidelib import * and then modify globals()
dictionary, but this isn't good too because mylib imports many other
modules and they all mapped into it's namespace (like mylib.os,
mylib.sys).

Thanks for attention!

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


Re: find difference in days from YYYYMMDD to YYYYMMDD

2007-09-22 Thread chaelon
On Sep 22, 5:37 am, Konstantinos Pachopoulos <[EMAIL PROTECTED]>
wrote:
> Hi,
> does any body now any such algorith? to find difference in days from
> MMDD to MMDD?
> Or just an algorithm, that converts MMDD to seconds since the epoch?
>
> Thanks

Seen some complex answers here.  Let's keep it dead simple.  Use the
datetime module to do the heavy lifting.  Go to IDLE, write this.

import datetime.

Then start to write this:

difference = datetime.date(

and at that point IDLE will tell you to put in year,month,day.  That's
convenient.  Do as IDLE asks, obey IDLE!  Wind up with this (put date
later in history first, here are two I've used):

difference = datetime.date(2007,9,25) - datetime.date(1970,12,25)
print difference

13419 days, 0:00:00

Hey now!  Date math!  Yeah!

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


Re: Getting rid of bitwise operators in Python 3?

2007-09-22 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> And who is it who uses this functionality? 

I use it but I agree it's easy to implement given the underlying
bignum arithmetic.

> It's useful in elementary number theory, sure, but I'd argue that if
> there are going to be number theoretical functions in the core then
> there are other things, like gcd(), that are far more deserving of
> inclusion.  

Certainly xgcd should be in the math library or somewhere similar.

> It comes up in the RSA cryptosystem, but if you're using
> Python's pow for this then you're surely only writing a toy RSA
> implementation, perhaps for educational purposes(?).  

Not necessarily.  See for example http://trevp.net/tlslite
-- 
http://mail.python.org/mailman/listinfo/python-list


Preemption in python

2007-09-22 Thread Kurtis Heimerl
Hi, I'm developing my first python application, a multi-threaded cell phone
gadget on ubuntu 7.10. I've just split off my first thread, and I've noticed
something extremely strange: There doesn't seem to be any preemption. There
are currently two threads, one that pings a storage service to see if there
are messages available, and the other that runs the gtk windows. If I do not
explicitly yield either one, it runs forever. I'm assuming this is a setting
somewhere, but that's a very strange default behavior.

How do I get this to go about preempting these threads? Any advice would be
helpful. Thanks!

I apologize if anyone sees this twice, I sent a copy earlier but did not
receive it from the mailing list, indicating to me that it wasn't received
correctly.
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >