Re: How to generate pdf file from an html page??

2007-12-20 Thread MonkeeSage
On Dec 19, 10:17 am, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2007-12-19, Terry Jones [EMAIL PROTECTED] wrote:



  Grant == Grant Edwards [EMAIL PROTECTED] writes:
 Grant On 2007-12-19, abhishek [EMAIL PROTECTED] wrote:
   Hi everyone, I am trying to generate a PDF printable format file from
   an html page. Is there a way to do this using python. If yes then
   which library and functions are required and if no then reasons why it
   cant be done.

  Here's one way:

  --html2pdf.py-
  #!/usr/bin/python
  import os,sys

  inputFilename,outputFilename = sys.argv[1:3]

  os.system(w3m -dump %s | a2ps -B --borders=no | ps2pdf - %s % 
  (inputFilename,outputFilename))

  Note that this is highly insecure. outputFilename could be passed e.g., as

/tmp/file.pdf; rm -fr /home/abhishek

 Here's a half-assed solution:

 inputFilename = inputFilename.replace(',)
 outputFilename = outputFilename.replace(',)

 os.system(w3m -dump '%s' | a2ps -B --borders=no | ps2pdf - '%s' % 
 (inputFilename,outputFilename))

 As somebody else suggested, building the pipeline by hand
 using the subprocess module is the most bullet-proof method.

 --
 Grant Edwards   grante Yow! I brought my BOWLING
   at   BALL -- and some DRUGS!!
visi.com

This looks a little better for me ... | a2ps -B --borders=0 --
columns=1 -f 10.0 | ...

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


Re: free video lessons on 12 computer Science Courses

2007-12-17 Thread MonkeeSage
On Dec 17, 3:13 am, AK444 [EMAIL PROTECTED] wrote:
 Hi Guys,  Good news is that as many as 12 courses from top
 universities are providing free video lessons  
 http://freevideolectures.com/ComputerScience/
 on all the basic courses. All you need to have is Real Player
 installed on your PC.

 I think it is useful to you

Lots of fun A/V at the Berkeley webcast page also:

http://webcast.berkeley.edu/courses.php?semesterid=21

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


Re: Finite State Machine GUI editor in python?

2007-12-17 Thread MonkeeSage
On Dec 16, 1:55 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 I have spent some time googling and on wiki and came up with
 pyFSA in python. It may end up being useful, but it is not directly
 what I am looking for, as there is no GUI that I can see.

 I know about SMC, but it is not Python, and I can't find the gui.

 This looks good, but it seems to be in a Latin based language
 and I am linguistically challenged:

 http://www.ucse.edu.ar/fma/sepa/edt.htm

 I am looking for a similar front end, going from pretty pictures of
 state diagrams to some sort of state machine descriptor language
 or specification file, and I am not very fussy about the format of
 the output at this stage.

 Does anyone know of such an animal that is FOSS? - if written in
 Python it will be a bonus!

 It will also help if its in a language I can understand.  : - (

 - Hendrik

This looks interesting (and GPL'd :)

http://www46.homepage.villanova.edu/timothy.m.white/ [java]

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


Re: free video lessons on 12 computer Science Courses

2007-12-17 Thread MonkeeSage
On Dec 17, 6:12 am, MonkeeSage [EMAIL PROTECTED] wrote:
 On Dec 17, 3:13 am, AK444 [EMAIL PROTECTED] wrote:

  Hi Guys,  Good news is that as many as 12 courses from top
  universities are providing free video lessons  
  http://freevideolectures.com/ComputerScience/
  on all the basic courses. All you need to have is Real Player
  installed on your PC.

  I think it is useful to you

 Lots of fun A/V at the Berkeley webcast page also:

 http://webcast.berkeley.edu/courses.php?semesterid=21

 Regards,
 Jordan

And not forgetting Sussman-Abelson lectures...

http://www.archive.org/details/mit_ocw_sicp

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


Re: Is Python really a scripting language?

2007-12-16 Thread MonkeeSage
On Dec 14, 3:15 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 On Dec 14, 2:48 pm, Chris Mellon [EMAIL PROTECTED] wrote:



  On Dec 14, 2007 2:09 PM, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

   On Dec 11, 10:34 pm, Terry Reedy [EMAIL PROTECTED] wrote:
Ron Provost [EMAIL PROTECTED] wrote in message

   news:[EMAIL PROTECTED]
But here's my problem, most of my coworkers, when they see my apps and
learn that they are written in Python ask questions like, Why would you
write that in a scripting language?  Whenever I hear a comment like 
that I
can feel myself boiling inside.
===

I don't blame you.  Python is an full-fledged algorithm/programming
language that was designed to *also* be used a scripting language.

   When you buy a new car, which is more important, the styling
   or what's under the hood?

  snip

   That's for the whole sequence, not a single term!

   25.67 MINUTES compared to 17.65 HOURS!

   So, sure, some languages compile to .exe programs.

   In the trade, we call that polishing a turd.

  While I agree with the sentiment, surely this can't be a good example
  of F#s general performance?

 Of course. They example was deliberately chosen to make
 F#'s BigInt library look as bad as possible.

  I would expect .NET code to smoke stock
  (non-Psycoed) Python in this benchmark.

 Probably. It just so happens that the example chosen
 is typical of _my_ number theory research and I was
 toying with the idea of converting my Collatz Conjecture
 function library to F#.

 And that would take a lot of work since F# doesn't have
 anywhere near the functionality of gmpy. There isn't
 even a BigInt.mod function for cryin' out loud, let alone
 stuff like GCD or modular inverse, critical to my research.

 Sure, I could write my own Extended Euclidean Algorithm,
 but now that I now that F# is just a Volkswagen with a
 fiberglass shell that looks like a Ferrari, there isn't
 much point, eh?

 And don't even get me started about the stupid stuff,
 like having TWO different type of Big Rationals. One's
 more efficient than the other, they say. So why two?
 The less efficient one has functions not implemented
 in the other. And F# is strongly typed, so you can't
 use BigRational methods with BigNum types. And they
 have all sorts of conversion methods for to/from ints,
 strings, bigints, etc. Guess which conversions they
 don't have? BigRational - BigNum, of course.

 MAybe I'll check it out again in the future after it
 has gone through several revisions.

Since F# is a caml derivative, you may want to look at OCaml. Though,
I've never used OCaml for any kind of heavy number-crunching, so maybe
it has even worse library support; can't say. Ps. The two types are
probably for boxed and unboxed versions, q.v. this article, about half-
way down: http://msdn.microsoft.com/msdnmag/issues/1200/dotnet/

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


Re: Windows XP unicode and escape sequences

2007-12-16 Thread MonkeeSage
On Dec 16, 5:28 pm, [EMAIL PROTECTED] wrote:
 Thank you John and Tim.

 With your help I found that the XP console code page is set up for 'cp437' 
 and with a little bit of browsing I found that 869 is the code page for 
 Modern Greek.  After changing it to 869 that did the trick!  Thanks very much 
 for this advice.

 This brings up another question.  If I run some Python code that starts off 
 with 'os.system('cp869')' so it will change to the correct code page, then 
 when it starts printing the Greek characters it breaks.  But run the same 
 Python code again and it works fine.  Is there another way to do this so I 
 can change over to the 869 code page and continue on with the Greek letters 
 printing correctly?

 Thanks Tim for the info about the CONFIG.NT file as well as the curses-like 
 info.  I'll continue to research these.

 Thanks again!

 Jay

  CONFIG.NT only affects 16-bit programs running in the NTVDM (the Virtual
  DOS Machine).
  32-bit console apps (which Python is) simply cannot use ANSI escape
  sequences.  You have to use the Win32 APIs to do color.  There are
  curses-like libraries available for Python.  Or:
 http://www.effbot.org/zone/console-handbook.htm
  --
  Tim Roberts, timr at probo.com
  Providenza  Boekelheide, Inc.

Try using the unicode switch ( cmd.exe /u ), rather than trying to set
the codepage. See here:
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true

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


Re: searching a value of a dict (each value is a list)

2007-12-14 Thread MonkeeSage
On Dec 10, 1:28 pm, [EMAIL PROTECTED] wrote:
 Seongsu Lee:

 I have a dictionary with million keys. Each value in the dictionary has a 
 list with up to thousand integers.

 Let's say each integer can be represented with 32 bits (if there are
 less numbers then a 3-byte representation may suffice, but this makes
 things more complex), that is 2^2 bytes. Let's say there are 2^20 keys
 each one associated to 2^10 values. So to represent the values you
 need 2^32 bytes. It means 4 GB, so I don't think Python suffices to
 store them in RAM, because a Python int object requires quite more
 than 4 bytes (only represented inside an array.array it may need just
 4 bytes).

 So if you can use 128 MB RAM to store such data structure you need to
 store data on HD too. You probably can use a lower-level language. On
 disk you can keep the reverse index, represented as an array of
 records/structs, each of such structures keep two 32-bit numbers (so
 such array is 8 GB). Such index is sorted according to the first
 element of the struct. The first number is the value of the original
 dictionary and the second nuber is its key. Inside the RAM you can
 keep another sorted array that summarizes your whole data. When you
 need a number you can do a binary search on the array in RAM, such
 array gives you the position where you can read (with a seek) a little
 part of the file (512 bytes may suffice), to perform a little binary
 search (if the block is very little a linear scan suffices) on it too
 to find the number you need. Note that the summarizing data structure
 in RAM may be represented with just a Python dict too, so in the end
 you can use Python to solve this problem. You may need a lower-level
 language to create the 8 GB file on disk (or create it with Python,
 but it may take lot of time. You may sort it with the sort unix
 command).

 This isn't a complete solution, but I think it may work.

 Bye,
 bearophile

Nice. :)

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


Re: Is a real C-Python possible?

2007-12-11 Thread MonkeeSage
On Dec 11, 3:10 am, Duncan Booth [EMAIL PROTECTED] wrote:
 sturlamolden [EMAIL PROTECTED] wrote:
  On 9 Des, 23:34, Christian Heimes [EMAIL PROTECTED] wrote:

  http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-pyth
  ...

  The Ruby developers are allowed to be proud. They were able to
  optimize some aspects of the implementation to get one algorithm
  about 14 times faster. That's good work. But why was it so slow in
  the first place?

  The thing to notice here is that Congiano spent 31.5 seconds computing
  36 Fibonacci numbers in Python and 11.9 seconds doing the same in
  Ruby. Those numbers are ridiculous! The only thing they prove is that
  Congiano should not be programming computers. Anyone getting such
  results should take a serious look at their algoritm instead of
  blaming the language. I don't care if it takes 31.5 seconds to compute
  36 Fibonacci numbers in Python 2.5.1 with the dumbest possible
  algorithm.

 Quite so.

 Take something 
 likehttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498110
 and then modify the Python code from the Ruby smokes Python article by
 the addition of @memoize(3) to decorate the otherwise unchanged fib
 function: the Python runtime drops down to 0.002 seconds.

 That is just slightly better than Ruby's 11.9 seconds although I'm sure the
 Ruby code would also gain as much from a memoize decorator.

 from memoize import memoize

 @memoize(3)
 def fib(n):
if n == 0 or n == 1:
   return n
else:
   return fib(n-1) + fib(n-2)

 from time import clock
 start = clock()
 for i in range(36):
 print n=%d = %d % (i, fib(i))
 print clock()-start

 When I run this (with output directed to a file: I'm not trying to time
 windows console speed), the output is:

 n=0 = 0
 n=1 = 1
 n=2 = 1
 n=3 = 2
 n=4 = 3
 n=5 = 5
 n=6 = 8
 n=7 = 13
 n=8 = 21
 n=9 = 34
 n=10 = 55
 n=11 = 89
 n=12 = 144
 n=13 = 233
 n=14 = 377
 n=15 = 610
 n=16 = 987
 n=17 = 1597
 n=18 = 2584
 n=19 = 4181
 n=20 = 6765
 n=21 = 10946
 n=22 = 17711
 n=23 = 28657
 n=24 = 46368
 n=25 = 75025
 n=26 = 121393
 n=27 = 196418
 n=28 = 317811
 n=29 = 514229
 n=30 = 832040
 n=31 = 1346269
 n=32 = 2178309
 n=33 = 3524578
 n=34 = 5702887
 n=35 = 9227465
 0.00226425425578

Another point is, the reason the ruby code shows such a performance
increase is because of the way it wraps native (C) types for integers
in the the new byte compiler; i.e., it's a directed optimization,
which the example code exploits to its full extent. But with
dictionary access, for example, python still creams ruby (by a 2/1
factor in my tests). Speaking as someone who uses both python and
ruby, I can say that ruby 1.9 is approaching python's speed, which is
very cool, but is still not quite as fast as python in general (the
whole smokes python bit is just propaganda that utilizes a specific
feature vector, and is generally unhelpful).

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


Re: Distinguishing attributes and methods

2007-12-10 Thread MonkeeSage
It seems that I've got a short-circuit somewhere here. I understand
that everything is an object and the the storage/lookup system is
object-agnostic, and that it is only the descriptors (or tags as I
called them generically) that determine how an attribute is bound,
whether it is bound at all, whether it is even callable, and so forth.
So, when I say that all callable attributes (or to be more precise,
all callable attributes bound to objects other than toplevel) are
methods, what am I missing?

You said the difference [between a callable attribute and a method]
is the specific implementation of the attribute's class...but this
almost sounds like type-by-primitive (a method is a method when it
derives from a certain base class), or type-by-behavior (a method is a
method when it behaves in a certain way, e.g., responds in a certain
way to a query). Is this correct? Shouldn't it be type-by-capability/
interface--i.e., it implements the protocol of a callable, therefore,
formally, it is not meaningfully different from any other callable
(quacks like a duck and all)?

I guess what I'm asking is, in what way is a method (or function)
semantically different from a home-brewed callable I concoct and bind
to an object (or toplevel)? What is the distinction that I'm missing?

Ps. wrt your last comment, isn't a class object in essence a factory
method?

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


Re: searching a value of a dict (each value is a list)

2007-12-10 Thread MonkeeSage
On Dec 10, 3:50 am, Seongsu Lee [EMAIL PROTECTED] wrote:
 On 12월10일, 오후12시18분, Adonis Vargas [EMAIL PROTECTED]
 wrote:



  Seongsu Lee wrote:
   Hi,

   I have a dictionary with million keys. Each value in the
   dictionary has a list with up to thousand integers.
   Follow is a simple example with 5 keys.

   dict = {1: [1, 2, 3, 4, 5],
  2: [10, 11, 12],
  90: [100, 101, 102, 103, 104, 105],
  91: [20, 21, 22],
  99: [15, 16, 17, 18, 19]}

   I want to find out the key value which has a specific
   integer in the list of its value. For example, if I search
   104 in the list, 90 must be returned.

   How can I do this with Python? Ideas?

  You can try this:

  items = {1: [1, 2, 3, 4, 5],
2: [10, 11, 12],
90: [100, 101, 102, 103, 104, 105],
91: [20, 21, 22],
99: [15, 16, 17, 18, 19]}

  def findItem(item, dictionary):
   for key, value in dictionary.iteritems():
   if item in value:
   print key, value

  findItem(104, items)

  This will allow you to work with the existing dataset without needing to
  duplicate it. It will print all occurrances.

 Hi,

 Yes, it works. But I think it works in O(n * m), doesn't it?
 (n is # of keys in the dictionary and m is # of items in the list.)
 So, we need to create a reverse index. (a reverse dictionary) or
 need something better at least, I think.

  Also, you should never use reserved words like 'dict' this creates
  confusion and can cause Python to misbehave since you are rebinding the
  name.

 Yep. :)

  Hope this helps.

  Adonis Vargas- 따온 텍스트 숨기기 -

  - 따온 텍스트 보기 -

If I'm not mistaken, building a reverse dictionary like that will be
O(n*m) because dict/list access is O(n) (ammortized). Somebody correct
me if I'm wrong. In that case, it really depends on how you will use
the dict to see whether you get any benefit from building the reversed
dict. If you want to do several lookups, then the initial overhead
(speed/memory) of building the reversed dict might be worth it so that
you can just run lookups at O(n). But if you only need it once, it is
a waste of time and space to create a reverse dict when your access
time is the same for the lookup as for building the reversed dict.

If you do need more than one lookup, it would also be a good
optimization strategy to build the reverse dict in parallel, as you
execute the first search; that way you can combine the time spent on
building the reverse dict and the lookup, to get a total of O(n*m)
rather than O(n^2*m). The first search is free since you need the
reverse dict anyway.

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

Re: Distinguishing attributes and methods

2007-12-10 Thread MonkeeSage
On Dec 10, 7:19 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 MonkeeSage a écrit :

  It seems that I've got a short-circuit somewhere here. I understand
  that everything is an object and the the storage/lookup system is
  object-agnostic, and that it is only the descriptors (or tags as I
  called them generically)

 descriptor is a protocol - an interface if you prefer. It's a way for
 a class attribute to hook into the lookup mechanism, and it's
 implemented by the property type - to provide a basic support for
 computed attributes - and the function type - to provide the machinery
 that turns a function into a method.

  that determine how an attribute is bound,
  whether it is bound at all, whether it is even callable,

 An object is callable if it implement the __call__ method (for the
 commonly admitted definition of 'method' !-).

  and so forth.
  So, when I say that all callable attributes (or to be more precise,
  all callable attributes bound to objects other than toplevel)

 You mean other than a module ?

  are
  methods, what am I missing?

 All callable attributes that are either bound to an instance or don't
 implement the descriptor protocol the way the function type do.

  You said the difference [between a callable attribute and a method]
  is the specific implementation of the attribute's class...but this
  almost sounds like type-by-primitive

 It isn't.

  (a method is a method when it
  derives from a certain base class), or type-by-behavior (a method is a
  method when it behaves in a certain way, e.g., responds in a certain
  way to a query).

 Bingo.

  Is this correct? Shouldn't it be type-by-capability/
  interface--i.e., it implements the protocol of a callable, therefore,
  formally, it is not meaningfully different from any other callable
  (quacks like a duck and all)?

 The answer is in how the function type implements the descriptor
 protocol. For an attribute to become a method when looked up, this
 attribute has to implement the descriptor protocol so that it's __get__
 method returns either a BoundMethod (or any equivalent) when looked up
 on the instance and an UnboundMethod (or any equivalent) when looked up
 on the class (I'll save you the details about classmethods etc).

 Now since the method type is mostly trivial to implement, the fact that
 an attribute lookup doesn't return an instance of Method doesn't
 necessarily imply it's not one - so the truth is that an attribute is a
 method if it behaves like one !-)

  I guess what I'm asking is, in what way is a method (or function)

 Python's 'methods' are really thin wrappers around an object, it's class
 and a function. In the common use case, one of these wrappers is
 instanciated each time you lookup a function that's a class attributes.

  semantically different from a home-brewed callable I concoct and bind
  to an object (or toplevel)? What is the distinction that I'm missing?

 Implement your own callable that doesn't implement the descriptor
 protocol, bind it to a class, instanciate your class, lookup this
 attribute. You'll get the original attribute, not a method. Or bind a
 function to an *instance*, and look it up - here again, you wont get a
 method, but the original function object.

 Now you can of course label this a static method if you want !-)

 If you want a custom callable to be usable as a method, you have to
 implement the descriptor protocol like the function type do.

  Ps. wrt your last comment, isn't a class object in essence a factory
  method?

 Not quite - even if you can use it that way. In fact, the real factory
 method is the __new__ method of the class - that is, the proper constructor.

 A class object is an object that is responsible for:
 * creating instances of itself (and as such, it is indeed a factory -
 but a factory object, not a factory method)
 * providing class attributes and mro to these instances (lookup rules
 here: a name not found in the instance's __dict__ will be looked up in
 the class, then in classes in the mro - unless of course the class
 implements __getattr__ or __getattribute__, in which case all bets are
 off).

 caveat : all this describes the 'new-style' object model. The 'classic'
 ('old-style') object model works a bit differently.

  Regards,
  Jordan

Thank you kindly Bruno. You're answers have been very informative. I
thought I understand how python was operating, but I see that I have
some misconceptions. I honestly did read through the reference manual
when I started learning python a couple years ago, but I'm not the
most patient person by nature, and it seems that I was so happy with a
shiny new language, that I imported some foreign concepts into the
picture and glossed over many of the details of pythons object model.
I'm going to give the Data Model section a thorough going-over
again, and try to pay more attention this time(!) ;)

Just as a side-note, it's interesting that even through my
misunderstandings I've been able

Re: searching a value of a dict (each value is a list)

2007-12-10 Thread MonkeeSage
On Dec 10, 8:31 am, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-12-10, MonkeeSage [EMAIL PROTECTED] wrote:

  If I'm not mistaken, building a reverse dictionary like that will be
  O(n*m) because dict/list access is O(n) (ammortized). Somebody correct
  me if I'm wrong. In that case, it really depends on how you will use
  the dict to see whether you get any benefit from building the reversed
  dict. If you want to do several lookups, then the initial overhead
  (speed/memory) of building the reversed dict might be worth it so that
  you can just run lookups at O(n).

 It also depends on if the dictionary shall be mutated between
 reverse lookups.

  But if you only need it once, it is a waste of time and space
  to create a reverse dict when your access time is the same for
  the lookup as for building the reversed dict.

  If you do need more than one lookup, it would also be a good
  optimization strategy to build the reverse dict in parallel, as
  you execute the first search; that way you can combine the time
  spent on building the reverse dict and the lookup, to get a
  total of O(n*m) rather than O(n^2*m). The first search is
  free since you need the reverse dict anyway.

 It wouldn't be merely an optimization if reverse lookups and
 mutations were interleaved.

 --
 Neil Cerutti
 You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor

Well true, but you enter a whole other level of complexity in that
case...something like Theta(log(n*(m-n))). I might have calculated
that incorrectly, but that just goes to show how complex a lookup
is(!) in such a case.

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


Re: searching a value of a dict (each value is a list)

2007-12-10 Thread MonkeeSage
On Dec 10, 8:31 am, Neil Cerutti [EMAIL PROTECTED] wrote:
 On 2007-12-10, MonkeeSage [EMAIL PROTECTED] wrote:

  If I'm not mistaken, building a reverse dictionary like that will be
  O(n*m) because dict/list access is O(n) (ammortized). Somebody correct
  me if I'm wrong. In that case, it really depends on how you will use
  the dict to see whether you get any benefit from building the reversed
  dict. If you want to do several lookups, then the initial overhead
  (speed/memory) of building the reversed dict might be worth it so that
  you can just run lookups at O(n).

 It also depends on if the dictionary shall be mutated between
 reverse lookups.

  But if you only need it once, it is a waste of time and space
  to create a reverse dict when your access time is the same for
  the lookup as for building the reversed dict.

  If you do need more than one lookup, it would also be a good
  optimization strategy to build the reverse dict in parallel, as
  you execute the first search; that way you can combine the time
  spent on building the reverse dict and the lookup, to get a
  total of O(n*m) rather than O(n^2*m). The first search is
  free since you need the reverse dict anyway.

 It wouldn't be merely an optimization if reverse lookups and
 mutations were interleaved.

 --
 Neil Cerutti
 You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor

Well true, but you enter a whole other level of complexity in that
case...something like Theta(log(n*(m-n))). I might have calculated
that incorrectly, but that just goes to show how complex a lookup
is(!) in such a case.

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


Re: searching a value of a dict (each value is a list)

2007-12-10 Thread MonkeeSage
On Dec 10, 9:45 am, MonkeeSage [EMAIL PROTECTED] wrote:
 On Dec 10, 8:31 am, Neil Cerutti [EMAIL PROTECTED] wrote:



  On 2007-12-10, MonkeeSage [EMAIL PROTECTED] wrote:

   If I'm not mistaken, building a reverse dictionary like that will be
   O(n*m) because dict/list access is O(n) (ammortized). Somebody correct
   me if I'm wrong. In that case, it really depends on how you will use
   the dict to see whether you get any benefit from building the reversed
   dict. If you want to do several lookups, then the initial overhead
   (speed/memory) of building the reversed dict might be worth it so that
   you can just run lookups at O(n).

  It also depends on if the dictionary shall be mutated between
  reverse lookups.

   But if you only need it once, it is a waste of time and space
   to create a reverse dict when your access time is the same for
   the lookup as for building the reversed dict.

   If you do need more than one lookup, it would also be a good
   optimization strategy to build the reverse dict in parallel, as
   you execute the first search; that way you can combine the time
   spent on building the reverse dict and the lookup, to get a
   total of O(n*m) rather than O(n^2*m). The first search is
   free since you need the reverse dict anyway.

  It wouldn't be merely an optimization if reverse lookups and
  mutations were interleaved.

  --
  Neil Cerutti
  You only get a once-in-a-lifetime opportunity so many times. --Ike Taylor

 Well true, but you enter a whole other level of complexity in that
 case...something like Theta(log(n*(m-n))). I might have calculated
 that incorrectly, but that just goes to show how complex a lookup
 is(!) in such a case.

 Regards,
 Jordan

Sorry for the double-post...google is being beligerant right now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 8, 4:54 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 MonkeeSage a écrit :



  On Dec 8, 12:42 pm, Bruno Desthuilliers
  [EMAIL PROTECTED] wrote:

 MonkeeSage a écrit :

 On Dec 7, 11:08 pm, Steve Howell [EMAIL PROTECTED] wrote:

 (snip)

  4) Ruby forces you to explicitly make attributes for
 instance variables.  At first I found this clumsy, but
 I've gotten used to it, and I actually kind of like it
 in certain circumstances.

 4.) Yeah, it's hard when learning ruby, especially if coming from
 languages that distinguish between methods and attributes,

 which is not the case in Python

  It is, I just wasn't absolutely precise (uh-oh, here comes the
  semantics police! -- don't pass GO, don't collect $200, go strait to
  jail!). Python *does* distinguish between instance/class vars and
  instance/class methods. But in ruby no such distinction exists.
  Accessing a variable in ruby == calling object.var. I.e., in ruby,
  when you say blah.x that translates to blah.send(:x), whether :x
  is a variable or a method, since *everything* is a method. The
  call model of ruby is more like smalltalk.

 I'm sorry to have to insist: Python doesn't distinguish between methods
 and attributes. Calling a method in Python is really 1/ looking up an
 attribute then 2/ applying the call operator on what the lookup eval'd
 to. As a matter of fact, you can stop at the first step, and you'll have
 a reference to whatever the lookup mechanism yielded for the given
 attribute name on the given object. FWIW, Python's functions are plain
 objects, and when used as attributes are stored in the same place as any
 other attribute.

Except that pthon does differentiate, as python variables are not
callable, whereas everything in ruby is callable. blah.a in ruby means
blah.send(:a). Which is why you need an accessor to get at instance
variables, since as variables they exist in the scope scope of the
class, but they are not callable so they are not attributes of the
instance.

 to get used
 to thinking of a.a and a.a= as method calls and defining accessors
 for those methods  (or using one of the attr_* keywords) in the class
 body.

 Python has an equivalent support for computed attributes, using property
 or a custom descriptors. While it's a bit lower-level than Ruby, it's
 still quite easy to use and IMHO a bit more powerful.

 The equivalent python idiom is something like:

 class A:
   __a = foo
   def __init__(self):
 self.a = A.__a

 WTF ???

 Which roughly translates to this in ruby:

 class A
   attr_accessor :a
   def initialize
 @a = foo
   end
 end

 The Python translation of the above Ruby snippet is actually way more
 simple:

 class A(object):
def __init__(self):
  self.a = foo

  Not really.

 Yes, really. Sorry to have to insist, but...

  In ruby an ivar is accessible within the class *only*, but
  not from without (like a mangled python class var), unless you declare
  an accessor (or write the accessor methods yourself).

 Your Ruby snippets uses attr_accessor, which gives direct, uncontrolled
 read/write access to the attribute. So I maintain that the *exact*
 semantic equivalent in Python of your Ruby snippet is a plain attribute.

  So my example is
  closer, and is not a WTF, if you know how ruby works.

 I know enough about Ruby to understand this snippet, and enough about
 Python to tell your Python example is a WTF.

 FWIW, your Python snippet ends up doing the same thing as mine - that
 is, it defines a plain instance attribute named 'a' - but uses a
 reference to class attribute instead of a string literal as the initial
 value of the instance attribute. Since Python strings are immutable, the
 final result is the same wrt/ the instance attribute - it's just overly
 complicated, hence the WTF label.

 OTHO, your Python code also defines a class attribute which doesn't
 exist in the Ruby snippet. Mine doesn't imply any class attribute. So my
 Python translation is way closer to the Ruby original !-)

 If you what you had in mind was an example of a computed attribute,
 here's the correct code:

 class A(object):
@apply
def a():
  def fget(self):
return self._a
  def fset(self, val):
self._a = val
  return property(**locals())
def __init__(self):
  self.a = foo

 Now since we're just getting/setting the attribute, all these
 indirection levels are totally useless, so in such a case we just use a
 plain attribute. So my first exemple (plain attribute) is effectively
 the *exact* semantic equivalent of your Ruby snippet. CQFD.

No, it's not at all.

class A
  attr_accessor :a # == self.a,
   # accessible to instances of A
  def initialize
@a = foo # A.__a
   # only accessible from class scope of A
  end
end

Once again, there is no such thing as an attribute that is not a
method in ruby, and there is no such thing as setting an *attribute*
(= is a method also). You're trying to *re-implement* rubys

Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 1:58 pm, MonkeeSage [EMAIL PROTECTED] wrote:

  Sure. But as I understand, every attribute in python is a value,

sorry...*references* a value

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


Re: Distinguishing attributes and methods

2007-12-09 Thread MonkeeSage
On Dec 8, 4:11 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 MonkeeSage a écrit :



  On Dec 8, 12:56 pm, Bruno Desthuilliers
  [EMAIL PROTECTED] wrote:

 MonkeeSage a écrit :

 On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

 On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote:

 With properties, attributes and methods seem very similar.  I was
 wondering what techniques people use to give clues to end users as to
 which 'things' are methods and which are attributes.

 Methods are attributes.  So the decision is easy -- everything on an
 object is an attribute.  ;-)

 Ciao,
Marc 'BlackJack' Rintsch

 I think he means callable attributes (methods) and non-callable
 attributes (variables).

 callable attributes are not necessarily methods, and are still
 'variables' anyway.

  I think it muddies the water to say that a.a() and a.a are the same
  thing--obviously they are not.

 Indeed. a.a yields the object bound to name 'a' in object a, while a.a()
 yields the value returned by calling the object bound to name 'a' in
 object a.

  In the common case, the first is a
  method,

 Nope, it's the value returned by the call to a callable - remember that
 in Python, the parens are the call operator, so the expression a.a()
 evals to the value returned by the call to a.a - which is either the
 method object returned by the collaboration of the lookup mechanism and
 the descriptor protocol or any other possible callable object bound to
 that name or returned by the lookup mechanism for that name.

You're talking about the result of calling a.a(), I'm talking about
what the attribute a on the object a is. Which is a callable
attribute, which by definition is called a method in the standard
sense [1]. You can make a distinction between a method object and
any other possible callable object, but I wasn't using such a
distinction, I was using the standard definition. So my point holds.
When you see a.a(), because of pythons calling convention () you
know that a is a method of object a.

The point is that just because the attributes are looked up the same
way or whatever, doesn't make them the same *kind* of attribute. To
say that all attributes are the same in python muddies the water. They
are the same in a generic sense that they are attributes, but not in
their particular qualities. Like saying all humans are the same --
yes, in a general sense of being human. But to leave it at that is not
very helpful.

[1] http://en.wikipedia.org/wiki/Method_%28computer_science%29

  and the second is a variable.

 The second is whatever the lookup mechanism will yield for this name.

  Yes, you can do silly stuff,
  such that this rule will not hold, but in general it does. Or am I
  wrong?

 You're wrong. Python's methods are thin wrappers around an instance
 (or class) and a function. These wrappers are built *at lookup time*
 by the __get__ method of the function object itself when it's looked up
 as an attribute of a class, thanks to the lookup mechanism and the
 descriptor protocol.

 Now the fact that an attribute is callable doesn't make it a method.

 Also, anyone can implement it's own callable type that will act as a
 true function - that is, implement the descriptor protocol to return a
 wrapper around the instance or class and the callable - without
 necessarily yielding an instance of types.MethodType. This is all fairly
 trivial.

Again, I am using the common definition. I understand that you can
make an attribute callable in different ways than just the standard
machinery of def symbol(self): (those other techniques are what I
was referring to above by metaprogramming). But how it is made
callable doesn't matter (nor does how it is looked up). Once it is
callable, it fits the defintion of method I'm using. In future, I'll
try to be clear when I'm referring to something python specific or to
a general CS concept.

 And note that none of the two above cases are necessarily silly.
 Python exposes most of it's object model so you can hook into it and
 taylor it to your needs. This results in some constructs that may seem
 weird at first, but make sens once you understand them and learn to use
 them.

Silly in the sense that in this context, they only serve to show
that TIMTOWTDI, but don't actually change a callable attribute from
being a callable attribute (method in the general CS sense) to being
some magical something else. For the purpose of distinguishing an
object variable (non-callable attribute) and an object method
(callable attribute), they don't add anything.

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 3:10 pm, I V [EMAIL PROTECTED] wrote:
 On Sun, 09 Dec 2007 11:58:05 -0800, MonkeeSage wrote:
  class A
attr_accessor :a # == self.a,
 # accessible to instances of A
def initialize
  @a = foo # A.__a
 # only accessible from class scope of A
end
  end

  Once again, there is no such thing as an attribute that is not a method
  in ruby, and there is no such thing as setting an *attribute* (= is a
  method also). You're trying to *re-implement* rubys mechanism in python
  in your example, but in pythons mechanism, all attributes already have
  built-in getter/setter. So the correct analogy is a variable that is
  accessible from within the classes scope only (A.__a), and then exposed
  to instances through an attribute (self.a). Your example leaves out a
  variable accessible only from within the scope of the class, and adds a
  new attribute accessible from the instance (_a).

 Either I'm not understanding you, or you're not understanding what A.__a
 means in python. A.__a is a class attribute, not an instance attribute -
 it's equivalent to @@a in ruby, not @a.

I said previously that A.__a is a class variable. Since I was only
using it to show that @a is not exposed as an attribute, I just used
A.__a, but you're right, it would have been better to use self.__a.

 If I understand what you're
 saying, a better python example to make your point might be:

 class A(object):
 def __init__(self):
 self.__a = foo # equivalent to @a
 self.a = self.__a # exposes self.__a

Thanks.

 Except that this only allows you to access '__a' via the exposed
 attribute 'a', not bind it to a new object. If you do:

 inst = A()
 inst.a = bar

 you don't modify inst.__a, unlike the following ruby code, which does
 modify @a .

 inst = A.new
 inst.a = bar

I understand. That's why I said it was a rough translation of the ruby
code. I was only trying to say that it's strange when learning ruby,
to get your head around the idea that instance (and class) variables
are not attributes; that all attributes are callable. The example was
merely to demonstrate the distinction between instance method and
instance variable in ruby. The python isn't supposed to have the exact
same behavior, just a similar semantic.

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
Hi Bruno,

I think that we've been having a mainly semantic (pun intended)
dispute. I think you're right, that we've been using the same words
with different meanings.

I would like to say firstly that I've been using python for a few
years now (about three I think), and I think I have a basic grasp of
the object system and so forth (e.g., I understood your example with
the apply decorator and properties). I read the docs when I first
started learning python (along with Fredrik Lundh's page about python
objects and more recently call by object). But I also own up to my
ignorance. I'm not a guru by any means. So you'll have to forgive me
if my ignorance has gotten in the way. I'll definitely re-read the
docs tonight.

I would like to (try to) clarify a little about my use of wording. By
attribute I was referring to a member of an object (*other than*
toplevel). I was of course using method to refer to callable
attributes (and I would use function for callable attributes bound
to toplevel), and I was using variable to refer to non-callable
attributes. By tagging I meant that attributes without a
tag (e.g., __call__) are not included in the MRO for an object; they
must be tagged as something other than a variable.

As for ruby, I think the opcodes will help me clarify...

 require 'parse_tree'
= true
 ParseTree.translate(%q{
class A
  def foo
bar
  end
end
A.new.foo
})
= [:block, [:class, :A, nil, [:scope, [:defn, :foo, [:scope, [:block,
[:args], [:str, bar]], [:call, [:call,
[:const, :A], :new], :foo]]

Notice that #new and #foo are both CALL ops. All attribute access is
CALL (i.e., method). There really is no such thing as a non-callable
attribute in ruby. Within the scope of a class (block, c), there
can be non-callable members of course (LVAL), but foo can mean
either LVAL *or* FCALL, because there is no tagging, it's just
whatever is in context and/or parsed first as a given type of object
(well there are a few other rules, but that's the main idea), with
() is a hint to help the parser when the expression is ambiguous:

a = 1
def a; 2; end
a   # [:lval :a] == a = 1
a() # [:fcall :a] == def ...

Given this, I see the addition the instance variable also being an
attribute as a *huge* difference between the ruby code and your
initial example. An attribute can be named the same as an lval and
return or set the value of the lval (e.g., @a), but it's no different
from any other method.

class A
  def initialize; @a = blah; end
  attr_reader :a
  def cheese; @a; end # exactly equivalent
end

But at the same time, I can see how my python example can be seen as
*wildly* different (WTF?) as well. Maybe there is no easy way to
provide a true formally equivalent translation due to the
implementation differences of the languages (or if Saphir-Whorf is
right, maybe we just can't think of it! ;)

Anyhow, sorry for the confusion.

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 6:23 pm, MonkeeSage [EMAIL PROTECTED] wrote:
 Hi Bruno,

 I think that we've been having a mainly semantic (pun intended)
 dispute. I think you're right, that we've been using the same words
 with different meanings.

 I would like to say firstly that I've been using python for a few
 years now (about three I think), and I think I have a basic grasp of
 the object system and so forth (e.g., I understood your example with
 the apply decorator and properties). I read the docs when I first
 started learning python (along with Fredrik Lundh's page about python
 objects and more recently call by object). But I also own up to my
 ignorance. I'm not a guru by any means. So you'll have to forgive me
 if my ignorance has gotten in the way. I'll definitely re-read the
 docs tonight.

 I would like to (try to) clarify a little about my use of wording. By
 attribute I was referring to a member of an object (*other than*
 toplevel). I was of course using method to refer to callable
 attributes (and I would use function for callable attributes bound
 to toplevel), and I was using variable to refer to non-callable
 attributes. By tagging I meant that attributes without a
 tag (e.g., __call__) are not included in the MRO for an object; they
 must be tagged as something other than a variable.

 As for ruby, I think the opcodes will help me clarify...

  require 'parse_tree'
 = true
  ParseTree.translate(%q{

 class A
   def foo
 bar
   end
 end
 A.new.foo})

 = [:block, [:class, :A, nil, [:scope, [:defn, :foo, [:scope, [:block,
 [:args], [:str, bar]], [:call, [:call,
 [:const, :A], :new], :foo]]

 Notice that #new and #foo are both CALL ops. All attribute access is
 CALL (i.e., method). There really is no such thing as a non-callable
 attribute in ruby. Within the scope of a class (block, c), there
 can be non-callable members of course (LVAL), but foo can mean
 either LVAL *or* FCALL, because there is no tagging, it's just
 whatever is in context and/or parsed first as a given type of object
 (well there are a few other rules, but that's the main idea), with
 () is a hint to help the parser when the expression is ambiguous:

 a = 1
 def a; 2; end
 a   # [:lval :a] == a = 1
 a() # [:fcall :a] == def ...

 Given this, I see the addition the instance variable also being an
 attribute as a *huge* difference between the ruby code and your
 initial example. An attribute can be named the same as an lval and
 return or set the value of the lval (e.g., @a), but it's no different
 from any other method.

 class A
   def initialize; @a = blah; end
   attr_reader :a
   def cheese; @a; end # exactly equivalent
 end

 But at the same time, I can see how my python example can be seen as
 *wildly* different (WTF?) as well. Maybe there is no easy way to
 provide a true formally equivalent translation due to the
 implementation differences of the languages (or if Saphir-Whorf is
 right, maybe we just can't think of it! ;)

 Anyhow, sorry for the confusion.

 Regards,
 Jordan

Ps. To answer a question you asked, callable objects don't generally
implement a #call method--just Proc objects and method references
[class Method instances] do, which even though they have a #call
method, aren't usually considered callable since you can't call them
directly--the #call method could as easily be named #run or #evaluate
or whatever. Accessing a name in ruby basically does something like:
VCALL name (== if parens on name like a() skip to call step, otherwise
check for LVAL in scope and return value if found, otherwise FCALL/
CALL and return result). You can use the #define_method method to
create a new callable.

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


Re: How does python build its AST

2007-12-08 Thread MonkeeSage
On Dec 8, 3:32 am, Carl Banks [EMAIL PROTECTED] wrote:
 On Dec 7, 9:23 am, MonkeeSage [EMAIL PROTECTED] wrote:

  A quick question about how python parses a file into compiled
  bytecode. Does it parse the whole file into AST first and then compile
  the AST, or does it build and compile the AST on the fly as it reads
  expressions? (If the former case, why can't functions be called before
  their definitions?)

 Python creates certain objects at compile time but doesn't bind them
 to names in the modulespace until run time.

 Python could--and many other languages do--automatically bind these
 objects to names upon import.  Python doesn't do it because it sees a
 module as code to be executed rather than a list of global object
 definitions.

 Something like this would be awkward if Python bound the names at
 import time:

 if X:
 def a(): do_this()
 else:
 def a(): do_that()

 Which one gets bound to a?

 To do something similar in C would require preprocessor macros (ick).

 Carl Banks

Gotcha. Thanks again everyone for your answers.

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


Re: Distinguishing attributes and methods

2007-12-08 Thread MonkeeSage
On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote:
  With properties, attributes and methods seem very similar.  I was
  wondering what techniques people use to give clues to end users as to
  which 'things' are methods and which are attributes.

 Methods are attributes.  So the decision is easy -- everything on an
 object is an attribute.  ;-)

 Ciao,
 Marc 'BlackJack' Rintsch

I think he means callable attributes (methods) and non-callable
attributes (variables).

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


Re: Distinguishing attributes and methods

2007-12-08 Thread MonkeeSage
On Dec 8, 6:50 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
 On Sat, 08 Dec 2007 00:34:06 -0800, MonkeeSage wrote:
  I think he means callable attributes (methods) and non-callable
  attributes (variables).

 But not every callable attribute is a method.

 Ciao,
 Marc 'BlackJack' Rintsch

I swear, you dynamic programmers and your metaprogramming
tomfoolery! :P

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


Re: a Python person's experience with Ruby

2007-12-08 Thread MonkeeSage
On Dec 8, 12:42 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 MonkeeSage a écrit :

  On Dec 7, 11:08 pm, Steve Howell [EMAIL PROTECTED] wrote:

 (snip)
   4) Ruby forces you to explicitly make attributes for
  instance variables.  At first I found this clumsy, but
  I've gotten used to it, and I actually kind of like it
  in certain circumstances.
  4.) Yeah, it's hard when learning ruby, especially if coming from
  languages that distinguish between methods and attributes,

 which is not the case in Python

It is, I just wasn't absolutely precise (uh-oh, here comes the
semantics police! -- don't pass GO, don't collect $200, go strait to
jail!). Python *does* distinguish between instance/class vars and
instance/class methods. But in ruby no such distinction exists.
Accessing a variable in ruby == calling object.var. I.e., in ruby,
when you say blah.x that translates to blah.send(:x), whether :x
is a variable or a method, since *everything* is a method. The
call model of ruby is more like smalltalk.

  to get used
  to thinking of a.a and a.a= as method calls and defining accessors
  for those methods  (or using one of the attr_* keywords) in the class
  body.

 Python has an equivalent support for computed attributes, using property
 or a custom descriptors. While it's a bit lower-level than Ruby, it's
 still quite easy to use and IMHO a bit more powerful.

  The equivalent python idiom is something like:

  class A:
__a = foo
def __init__(self):
  self.a = A.__a

 WTF ???

  Which roughly translates to this in ruby:

  class A
attr_accessor :a
def initialize
  @a = foo
end
  end

 The Python translation of the above Ruby snippet is actually way more
 simple:

 class A(object):
def __init__(self):
  self.a = foo

  Python:

Not really. In ruby an ivar is accessible within the class *only*, but
not from without (like a mangled python class var), unless you declare
an accessor (or write the accessor methods yourself). So my example is
closer, and is not a WTF, if you know how ruby works.

  1.) I also found python's style of method referencing to be a lot more
  intuitive than using something like ruby's m = method('foo');
  m.call('bar') to get a reference to foo() and call it. It's alot
  cleaner to say m = foo; m('bar'), imo. But this goes back to the
  omitting parens thing, which makes it impossible to do it that way in
  ruby.

 Yeps. This is where the real and fundamental difference between Ruby and
 Python becomes evident. Both have support for transparent computed
 attributes, but the way it's implemented is totally different - in Ruby,
 by not having a call operator at all (I mean, the parens), in Python by
 having both an explicit call operator and an explicit protocol for
 computed attributes (the descriptor protocol). Not to say one is better
 than the other, but that while both languages have similar features
 (and, at first look, similar syntaxes), they really have totally
 different object models.

Yes and no. I'll leave it at that. If you want to know more, do your
homework. :P

  Though, ruby does allow some interesting things by having it
  that way, e.g., letting you substitute a Proc object (e.g., a block or
  lambda) for a method reference transparently.

 Care to give an example ? I don't have enough working experience with
 Ruby to be sure I understand what you mean here.

For example, any place expecting a foo (method reference), can be
exchanged with a { bar } block or a lambda { baz }.

  2.) I also find layout to be a nice feature. And since I've recently
  been using Haskell, it has only re-inforced that opinion. But when I
  first started using python, I got bitten by IndentationError quite
  often. And I kept wanting to type some closing symbol, heh. ;)

 The nice thing with Python is that it lets you use the closing symbol
 you want, as long as you prefix it with a '#' !-)

LOL. Well, yes, I used to do that, but I got over that irrational
urge. ;)

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


Re: Distinguishing attributes and methods

2007-12-08 Thread MonkeeSage
On Dec 8, 12:56 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 MonkeeSage a écrit :



  On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

 On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote:

 With properties, attributes and methods seem very similar.  I was
 wondering what techniques people use to give clues to end users as to
 which 'things' are methods and which are attributes.

 Methods are attributes.  So the decision is easy -- everything on an
 object is an attribute.  ;-)

 Ciao,
 Marc 'BlackJack' Rintsch

  I think he means callable attributes (methods) and non-callable
  attributes (variables).

 callable attributes are not necessarily methods, and are still
 'variables' anyway.

I think it muddies the water to say that a.a() and a.a are the same
thing--obviously they are not. In the common case, the first is a
method, and the second is a variable. Yes, you can do silly stuff,
such that this rule will not hold, but in general it does. Or am I
wrong?

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


Re: Distinguishing attributes and methods

2007-12-08 Thread MonkeeSage
On Dec 8, 2:51 pm, Glenn Hutchings [EMAIL PROTECTED] wrote:
 On Dec 8, 7:44 pm, MonkeeSage [EMAIL PROTECTED] wrote:

  I think it muddies the water to say that a.a() and a.a are the same
  thing--obviously they are not.

 A thing is not what it is;
 A thing is what it does.
 This is the Way of the Duck.

 -- Basho (in his 3 extra syllables phase)

Bah. Type-by-behavior never impressed me much. And I still think that
a.a is semantically different from a.a() in python.

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


How does python build its AST

2007-12-07 Thread MonkeeSage
A quick question about how python parses a file into compiled
bytecode. Does it parse the whole file into AST first and then compile
the AST, or does it build and compile the AST on the fly as it reads
expressions? (If the former case, why can't functions be called before
their definitions?)

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


Re: How does python build its AST

2007-12-07 Thread MonkeeSage
On Dec 7, 9:50 am, Kay Schluehr [EMAIL PROTECTED] wrote:
 On Dec 7, 3:23 pm, MonkeeSage [EMAIL PROTECTED] wrote:

  A quick question about how python parses a file into compiled
  bytecode. Does it parse the whole file into AST first and then compile
  the AST, or does it build and compile the AST on the fly as it reads
  expressions? (If the former case, why can't functions be called before
  their definitions?)

  Thanks,
  Jordan

 Python uses a highly optimized table based LL(1) parser to create a
 syntax tree. In Python 2.5 it transforms the concrete syntax tree
 ( CST ) into an AST before compilation. Before that it compiled the
 CST directly. I'm not sure what you are asking for ( in parentheses )?
 Parser actions or preprocessing the tree? The latter is definitely
 possible and you can build your own compilation machinery using the
 parser module and the compile function.

 Kay

Thanks for your reply. You answered my main question. The secondary
question is why is it a NameError to try to use a variable/function
prior to the declaration in a source file, since python has already
seen the declaration on the first pass building the CST/AST? At
compile time, shouldn't it already know about it? (Forgive my
ignorance.)

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


Re: __iadd__ useless in sub-classed int

2007-12-07 Thread MonkeeSage
On Dec 7, 12:45 am, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 En Fri, 07 Dec 2007 03:01:28 -0300, MonkeeSage [EMAIL PROTECTED]
 escribió:

  I've wondered about this myself. Seems to me, to prevent clobbering
  subclasses, __iadd__ (and all of the integer and float and whatever)
  methods that return new instances, should work like this (obviously I
  mean in the C backend, this is just to show the behavior):

  def __iadd__(self, other):
return self.__class__(self + other)

 This would slow down *all* of Python, and is only useful for those who
 actually inherit from some builtin class (not so common)

 --
 Gabriel Genellina

I understand why it doesn't. It just *seems* like it should work that
way when you first run into it (and has bitten me a couple times
before). But then, I'm not Dutch. :)

Regard,
Jordan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does python build its AST

2007-12-07 Thread MonkeeSage
On Dec 8, 12:20 am, Terry Reedy [EMAIL PROTECTED] wrote:
 MonkeeSage [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]
 | 1.) What is the benefit of doing a two phase compilation (parsing/
 | compiling), rather than a single, joint parse + compile phase (as in
 | interactive mode)?

 As far as I know (without looking at the code), there is no difference
 between interactive and batch mode except that the unit processed is a
 statement versus file.

I see.

 | 2.) Wouldn't it be possible on the parsing phase to tag names as
 | valid, even if they occur prior to the assignment of the name, if on a
 | later branch that assignment is found (and have the compiler be aware
 | of such tags)?

 What would be the point?  The semantics of Python code is essentially
 independent of whether it is executed in interactive or batch mode.  (The
 exceptions are not relevant to your question.)  So there is no point I can
 see to doing something in file mode that could not be done in statement
 mode.

It would pretty much be pointless. Referencing a name before it's
assigned seems confusing and strange to me. I suppose one sane use
would be in implementing something like Haskell's where clause, but
I don't think that would work well (or even be very useful) in python.
Anyhow, this was more of an academic curiosity on how CPython does
things, and I appreciate your answers.

 tjr

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


Re: How does python build its AST

2007-12-07 Thread MonkeeSage
On Dec 7, 4:29 pm, Terry Reedy [EMAIL PROTECTED] wrote:
 MonkeeSage [EMAIL PROTECTED] wrote in message

 news:[EMAIL PROTECTED]
 |A quick question about how python parses a file into compiled
 | bytecode. Does it parse the whole file into AST first and then compile
 | the AST, or does it build and compile the AST on the fly as it reads
 | expressions? (If the former case, why can't functions be called before
 | their definitions?)

 The direct answer is that names cannot be entered into namespaces and bound
 to objects to be looked up until the corresponding object is created by
 executing the corresponding code.  Compiling Python code creates the
 internal code needed to create Python objects, but only exceptionally
 creates Python objects in the process.  In particular, compiling a function
 may create code objects (since the code is a constant) referenced by the
 function creation code, but not function objects themselves.

 A less direct answer is the Python is designed to by usable interactively.
 In CPython interactive mode, you enter and the interpreter compiles and
 executes one top(module)-level statement at a time.  Calling a function you
 have not yet entered would be magical.

 Terry Jan Reedy

Thanks for your replies Kay, Michael and Terry. To summarize my
understanding of your answers:

- Python (meaning CPython here) first does a parsing pass over the
entire file, with 2.5+ building a syntax tree and prior versions
building a parse tree.

- It then compiles the tree into bytecode, by walking down the nodes
recursively from the top down.

- When in interactive mode (e.g., python prompt), it builds the tree
and compiles it on the fly, as individual expressions are parsed.

Is this correct? If so, may I pick your brain on two more points?

1.) What is the benefit of doing a two phase compilation (parsing/
compiling), rather than a single, joint parse + compile phase (as in
interactive mode)?

2.) Wouldn't it be possible on the parsing phase to tag names as
valid, even if they occur prior to the assignment of the name, if on a
later branch that assignment is found (and have the compiler be aware
of such tags)?

The reason I'm wondering about these things is that on a different
group, it came up that perl allows referencing before assignment,
which seems to require a two-phase compilation, which made me wonder
how python does things. And since (if I haven't misunderstood), python
does use two-phase compilation, I just wondered if it would be
possible to do what perl does. I'm not advocating it as a feature for
python (it seems bass-ackwards to me to reference a name before it's
assigned to in the script), this is just curiosity.

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


Re: a Python person's experience with Ruby

2007-12-07 Thread MonkeeSage
On Dec 7, 11:08 pm, Steve Howell [EMAIL PROTECTED] wrote:
 Python is my favorite programming language.  I've used
 it as my primary language for about six years now,
 including four years of using it full-time in my day
 job.  Three months ago I decided to take a position
 with a team that does a lot of things very well, but
 they don't use Python.  We use Ruby instead.  I'd like
 to share my observations about Ruby, because I think
 they say important things about Python, which has been
 my frame of reference.

 First of all, I actually enjoy programming in Ruby.
 Although I'm still fairly early on the learning curve,
 I feel like I've achieved basic fluency, and it
 generally stays out of the way.

 (A quick disclaimer is that some of the observations I
 make about Ruby may simply reflect my ignorance about
 the language.  I'm still learning it.)

 The thing that I like least about Ruby is its
 require mechanism.  Basically, when you do require
 in Ruby, it sort of pollutes your namespace.  I much
 prefer Python's explicitness.

 Some surprising things that I like about Ruby:

   1) It has the Perlish natural language syntax of
 raise 'foo' if condition.  I never missed having
 that syntax in Python, but now that I have it in Ruby,
 I use it quite often.

   2) On a general note, Ruby is enough like Python
 that it doesn't bend my brain.

   3) I actually like being able to omit parentheses in
 method definitions and method calls.  In Ruby you can
 express add(3,5,7) as both add(3,5,7) and add 3,
 5, 7.  The latter syntax is obviously more error
 prone, but I don't think I've ever actually gotten bit
 by it, and the code appears more clean to me.

   4) Ruby forces you to explicitly make attributes for
 instance variables.  At first I found this clumsy, but
 I've gotten used to it, and I actually kind of like it
 in certain circumstances.

 What I miss about Python:

   1) I like the fact that Python's syntax for passing
 around methods is very natural. Ruby's syntax is much
 more clumsy.

   2) I miss indentation.  I get bitten by kEnd in Ruby
 all the time.

   3) I miss Python's maturity.  Just to give a small
 example, Python's interpreter gives more readable
 syntax error messages.

 Those are the things that jump out for me.  I'm
 curious to hear what other people have learned about
 Python after maybe going away from it for a while.

   
 
 Be a better friend, newshound, and
 know-it-all with Yahoo! Mobile.  Try it now.  
 http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ

Hello,

Standard disclaimer: This response is in the spirit of sharing
knowledge and experience, as I take your post to be, not in the spirit
of advocacy of any language. All opinions I express are simply that:
my opinion.

I use both python and ruby quite often. But I came from the other
direction, starting with ruby then learning python. Overall, I think
they are both great languages, and I believe the choice in whether to
use one or the other (or both!) is determined mainly by expedience and
preference. I'll try to give my thoughts on your points, which I had
as I was learning python a few years ago, along with my current
opinions:

Ruby:

0.) I found python's concept of namespaces as defined by imported
modules (i.e., files) to be strange at first. I used from foo import
* a lot starting out. The main thing that I had to get my mind around
was that in ruby a namespace applies to an object (even main, i.e.,
toplevel, is an instance of class Object), and you can re-open
objects to extend their namespace (or mix in modules, which in ruby
are like a container of unbound methods that you can include in
another object and thereby bind those methods to that object). So
rather than import a module with the namespace string, as in
python, in ruby you'd require a file that re-opens class String and
extends it. They are two different approaches (and two different ideas
of namespace pollution), but once you get your mind around both, they
are very easy to use. I almost never use from foo import * now in
python.

1.) I missed the infix version of conditionals that ruby provides at
first, and I would often write things like if foo: bar in python if
the line was short. Now it just feels more natural to write it on two
lines in python most of the time, though in ruby I still use the other
notation if the line is short.

2.) I found the same was true. I could basically translate 90% of the
ruby idioms directly into python (minor syntax issues aside), and vise
versa.

3.) I never have liked omitting parens in ruby method calls (with the
exception of methods taking no arguments, but I didn't even do that
for a long time), though many/most rubyists do use that style. One
problem with it is that it leads to ambiguities, and the parser
complains in those cases (e.g., puts add 1, 2, 3). However, with
predicate methods it does make it read more like a 

Re: Class destructor -- strange behaviour

2007-12-06 Thread MonkeeSage
On Dec 6, 3:51 pm, Spes [EMAIL PROTECTED] wrote:
 Hi,

 I have this simple code:
 | #!/usr/bin/python
 | import codecs
 | import re
 | from copy import deepcopy
 |
 | class MyClass(object):
 |   def __del__(self):
 | deepcopy(1)
 |
 | x=MyClass()

 but I get an error:
 | Exception exceptions.TypeError: 'NoneType' object is not callable
 in bound method MyClass.__del__ of __main__.MyClass object at
 0x6fcf0 ignored

 The problem disappears if I do anything of this:
 1. change
  - from copy import deepcopy
  + import copy
 and call directly copy.deepcopy(1)

 or
 2. don't store object to variable `x'

 or
 3. don't import module `re'

 The first solution is OK, but I would like to know why it behaves so
 strange. We have tested on:

 - Mac OS X Tiger for PPC
 Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
 [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

 - Linux 64bit and 32bit
 Python 2.4.4 (#1, Oct 30 2007, 14:31:50)
 [GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2
 Python 2.5 (r25:51908, Jan 12 2007, 13:57:15)
 [GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2

 Thanks for the explanation,
 Vlasta

I can't explain why, but it also works if you call del x manually
before the script exits.

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


Re: Capturing global input?

2007-12-06 Thread MonkeeSage
On Dec 6, 9:16 pm, MonkeeSage [EMAIL PROTECTED] wrote:
 On Dec 6, 3:51 pm, nomihn0 [EMAIL PROTECTED] wrote:

  I'd like to accept mouse gestures and keyboard shortcuts as input to a
  program. The nature of this program requires that these commands be
  issued regardless of the currently active window. Here's the rub: I
  need a platform-independent solution.

  Java supports with its MouseInfo class, but I'd like a Python
  equivalent without turning to Jython.  Is this possible?

  Thanks in advance.

 There is no cross-platform way to do that. You have to use whatever
 interface the OS provides for that (e.g., Xlib events for X11). You
 could probably write a platform independent way by testing the OS and
 using the appropriate apis for that OS (assuming that there are python
 modules like python-xlib for other OS). I wonder why you'd want to
 though, if Java already provides a solution? If you don't want to muck
 with Java syntax, what about Jython?

 Regards,
 Jordan

Ps. I saw you said you didn't want Jython, but I can't see why.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Capturing global input?

2007-12-06 Thread MonkeeSage
On Dec 6, 3:51 pm, nomihn0 [EMAIL PROTECTED] wrote:
 I'd like to accept mouse gestures and keyboard shortcuts as input to a
 program. The nature of this program requires that these commands be
 issued regardless of the currently active window. Here's the rub: I
 need a platform-independent solution.

 Java supports with its MouseInfo class, but I'd like a Python
 equivalent without turning to Jython.  Is this possible?

 Thanks in advance.

There is no cross-platform way to do that. You have to use whatever
interface the OS provides for that (e.g., Xlib events for X11). You
could probably write a platform independent way by testing the OS and
using the appropriate apis for that OS (assuming that there are python
modules like python-xlib for other OS). I wonder why you'd want to
though, if Java already provides a solution? If you don't want to muck
with Java syntax, what about Jython?

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


Re: __iadd__ useless in sub-classed int

2007-12-06 Thread MonkeeSage
On Dec 6, 3:02 pm, samwyse [EMAIL PROTECTED] wrote:
 On Dec 6, 1:12 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:



  samwyse schrieb:

   For whatever reason, I need an inproved integer.  Sounds easy, let's
   just subclass int:

   class test(int):
  pass

   Now let's test it:

   zed=test(0)
   zed.__class__
   class '__main__.test'
   zed
   0

   So far, so good.  Now let's try incrementing:

   zed+=1
   zed
   1
   zed.__class__
   type 'int'

   WTF??!
   Is this a bug or is it the inevitable result of optimizing for the
   case where all integers are indistinguishable?

  There has been a lengthe thread over the semantics of __iadd__ a few
  weeks ago. It _can_ modify the object in question in-place (something
  not possible for ints anyway), but it will ALWAYS return a reference
  which will be set to the left-hand-side.

 Thanks!  I'd missed that thread, googling found it but it didn't look
 noteworthy at first glance.  I've not yet read the entire thread, but
 I did see a reference to PEP 203.

 )So, given the expression:
 )
 )  x += y
 )
 )The object `x' is loaded, then `y' is added to it, and the
 )resulting object is stored back in the original place.

 That agrees with what I'm seeing, all right.  The problem is, the
 resulting object has a different type, which seems to violate the
 spirit of a later paragraph:

 )Writing the above expression as
 )
 )x operator= y
 )
 )is both more readable and less error prone, because it is
 )instantly obvious to the reader that it is x that is being
 )changed, and not x that is being replaced by something almost,
 )but not quite, entirely unlike x.

 And that's my complaint.  The value in zed is being replaced by
 something almost, but not quite, identical to the original value.
 Python's internal implementation of __iadd__ for int isn't returning
 self, it's returning a new value belonging to the super-class.  My
 whole point is overloading int was that I'd hoped to avoid having to
 write a bunch of methods to perform in-place modifications.  Looks
 like I stuck, however.

I've wondered about this myself. Seems to me, to prevent clobbering
subclasses, __iadd__ (and all of the integer and float and whatever)
methods that return new instances, should work like this (obviously I
mean in the C backend, this is just to show the behavior):

def __iadd__(self, other):
  return self.__class__(self + other)

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


Re: converting to and from octal escaped UTF--8

2007-12-04 Thread MonkeeSage
On Dec 3, 8:10 am, Michael Goerz [EMAIL PROTECTED] wrote:
 MonkeeSage wrote:
  On Dec 3, 1:31 am, MonkeeSage [EMAIL PROTECTED] wrote:
  On Dec 2, 11:46 pm, Michael Spencer [EMAIL PROTECTED] wrote:

  Michael Goerz wrote:
  Hi,
  I am writing unicode stings into a special text file that requires to
  have non-ascii characters as as octal-escaped UTF-8 codes.
  For example, the letter Í (latin capital I with acute, code point 205)
  would come out as \303\215.
  I will also have to read back from the file later on and convert the
  escaped characters back into a unicode string.
  Does anyone have any suggestions on how to go from Í to \303\215 and
  vice versa?
  Perhaps something along the lines of:
 def encode(source):
... return .join(\%o % ord(c) for c in source.encode('utf8'))
...
 def decode(encoded):
... bytes = .join(chr(int(c, 8)) for c in encoded.split('\\')[1:])
... return bytes.decode('utf8')
...
 encode(uÍ)
'\\303\\215'
 print decode(_)
Í
  HTH
  Michael
  Nice one. :) If I might suggest a slight variation to handle cases
  where the encoded string contains plain text as well as octal
  escapes...

  def decode(encoded):
for octc in (c for c in re.findall(r'\\(\d{3})', encoded)):
  encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
return encoded.decode('utf8')

  This way it can handle both \\141\\144\\146\\303\\215\\141\\144\\146
  as well as adf\\303\\215adf.

  Regards,
  Jordan

  err...

  def decode(encoded):
for octc in re.findall(r'\\(\d{3})', encoded):
  encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
return encoded.decode('utf8')

 Great suggestions from both of you! I came up with my final solution
 based on them. It encodes only non-ascii and non-printables, and stays
 in unicode strings for both input and output. Also, low ascii values now
 encode into a 3-digit octal sequence also, so that decode can catch them
 properly.

 Thanks a lot,
 Michael

 

 import re

 def encode(source):
 encoded = 
 for character in source:
 if (ord(character)  32) or (ord(character)  128):
 for byte in character.encode('utf8'):
 encoded += (\%03o % ord(byte))
 else:
 encoded += character
 return encoded.decode('utf-8')

 def decode(encoded):
 decoded = encoded.encode('utf-8')
 for octc in re.findall(r'\\(\d{3})', decoded):
 decoded = decoded.replace(r'\%s' % octc, chr(int(octc, 8)))
 return decoded.decode('utf8')

 orig = ublaÍblub + chr(10)
 enc  = encode(orig)
 dec  = decode(enc)
 print orig
 print enc
 print dec

An optimization...in decode() store matches as keys in a dict, so you
only do the string replacement once for each unique character...

def decode(encoded):
  decoded = encoded.encode('utf-8')
  matches = {}
  for octc in re.findall(r'\\(\d{3})', decoded):
matches[octc] = None
  for octc in matches:
decoded = decoded.replace(r'\%s' % octc, chr(int(octc, 8)))
  return decoded.decode('utf8')

Untested...

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


Re: minimalist web server

2007-12-03 Thread MonkeeSage
On Dec 2, 10:13 pm, Daniel Fetchinson [EMAIL PROTECTED]
wrote:
   The reason I need this is that my current best strategy to avoid ads in
   web pages is putting all ad server names into /etc/hosts and stick my
   local ip number next to them (127.0.0.1) so every ad request goes to my
   machine. I run apache which has an empty page for 404 errors so I'll

  In this case, do you need a webserver at all? If your browser tries to
  access a web server on 127.0.0.1 and there isn't one, won't the result,
  in most cases, be more or less the same as if the server returned a 404?

 Not quite, because if the browser doesn't get a response from the
 server it will keep trying for a while and will only give up after
 that. And then will display a server not found, blablablabla message
 depending on the browser, which will appear in place of every ad.
 That's ugly and it's better to have an empty page.

 Concerning the python solutions posted by several guys, they are too
 heavyweight compared to a ~ 1-3 hundred lines of C code that one can
 obtain from cheetah's source code.

Then use those lines of source, heh. No need to try to force python to
fit every problem. If you have a solution that works better in some
other language, then use it; we won't be angry. :)

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


Re: Python is not a good name, should rename to Athon

2007-12-03 Thread MonkeeSage
On Dec 2, 4:47 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Sat, 01 Dec 2007 23:55:32 -0800, Russ P. wrote:
  I neither know nor care much about Newton's personality and social
  graces, but I can assure you that he was more than a technician (no
  offense to technicians).

  If you just read the Wikipedia preamble about him you will realize that
  he is arguably the greatest scientist who ever lived.

 Arguably is right.

 Please, stop with the fanboy squeeing over Newton. Enough is enough.
 Newton has already received far more than his share of honours.

 He might have been a great intellectual but he was no scientist. It's
 only by ignoring the vast bulk of his work -- work which Newton himself
 considered *far* more important and interesting than his work on physics
 and mathematics -- that we can even *pretend* he was a scientist.

 Newton was arrogant, deceitful, secretive, and hostile to other peoples
 ideas. Arrogance sometimes goes hand in hand with intellectual
 brilliance, and there's no doubt that Newton was brilliant, but the last
 three are especially toxic for good science. His feuds against two of his
 intellectual equals, Leibniz and Hooke, held mathematics and the sciences
 back significantly. They weren't the only two: he feuded with Astronomer
 Royal John Flamsteed, John Locke, and apparently more tradesmen than
 anyone has counted. He held grudges, and did his best to ruin those who
 crossed him.

 Historians of science draw a fairly sharp line in the history of what
 used to be called natural philosophy (what we now call science). That
 line is clearly drawn *after* Newton: as John Maynard Smith has said,
 Newton was the last and greatest of the magicians, not the first of the
 scientists. He was first and foremost a theologian and politician, an
 alchemist, a religious heretic obsessed with End Times, and (when he
 wasn't being secretive and isolating himself from others) a shameless
 self-promoter unwilling to share the spotlight.

 The myth of Newton the scientist is pernicious. Even those who recognise
 his long periods of unproductive work, his wasted years writing about the
 end of the world, his feuds, his secrecy and his unprofessional grudges
 against other natural philosophers, still describe him as a great
 scientist -- despite the fact that Newton's way of working is anathema to
 science. The myth of science being about the lone genius dies hard,
 especially in popular accounts of science. Science is a collaborative
 venture, like Open Source, and it relies on openness and cooperation, two
 traits almost entirely missing in Newton.

 There is no doubt that Newton was a great intellect. His influence on
 mechanics (including astronomy) was grand and productive; that on optics
 was mixed, but his alchemical writings have had no influence on modern
 chemistry. Newton's calculus has been virtually put aside in favour of
 Leibniz's terminology and notation. The great bulk of his work, his
 theological writings, had little influence at the time and no lasting
 influence at all.

Being fair, the bulk of Liebniz' writings have also been rejected by
those in related fields. Most modern metaphysicians hold a view closer
to Boston Personalism or at least post-Kantian Personalism (a la
Buber), than monadic unity and pre-established harmony, a la Liebniz.
It is an instance of the genetic fallacy to reject the achievements of
a person in one field, simply because of their failures in another.

 Newton was lucky to live at a time of great intellectual activity. Had he
 lived thirty years earlier, his secrecy would almost certainly have meant
 that his discoveries, such as they were, would have died with him. Had he
 lived thirty years later, others like Leibniz, Hooke, the Bernoullis, or
 others, would have made his discoveries ahead of him -- perhaps a few
 years or a decade later, but they would have done so, as Leibniz
 independently came up with calculus.

 There's no doubt that Newton was a genius and an important figure in the
 history of science, but to describe him as a scientist is to distort both
 the way Newton worked and the way science works. By all means give him
 credit for what he did and what he was, but don't pretend he was
 something that he was not.

 --
 Steven

That said, I think this whole rename python thing is silly.

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


Re: Python is not a good name, should rename to Athon

2007-12-03 Thread MonkeeSage
On Dec 3, 7:23 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Mon, 03 Dec 2007 02:12:17 -0800, MonkeeSage wrote:
  Being fair, the bulk of Liebniz' writings have also been rejected by
  those in related fields. Most modern metaphysicians hold a view closer
  to Boston Personalism or at least post-Kantian Personalism (a la Buber),
  than monadic unity and pre-established harmony, a la Liebniz. It is an
  instance of the genetic fallacy to reject the achievements of a person
  in one field, simply because of their failures in another.

 I'm not suggesting that Leibniz was any more of a scientist than Newton
 was, nor am I suggesting that Newton's achievements should be *rejected*
 (er, except for those pesky Quantum Mechanics and Relativity things...).
 I'm just saying that we should understand Newton for what he actually
 was, and not based on the 18th Century revisionism.

 --
 Steven

Fair enough. Understanding a person in their own context, especially
given the modern tendency to appropriate anything remotely similar to
the modern view as their own, is a rare quality (at least among
philosophers). I'm not a 'Newtonian fanboy' as it were, I just dislike
the uniformitarian push for a one right view of physics/metaphysics,
as if there were no room for innovation!

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


Re: Python is not a good name, should rename to Athon

2007-12-03 Thread MonkeeSage
On Dec 3, 5:39 pm, Russ P. [EMAIL PROTECTED] wrote:
 On Dec 3, 2:40 pm, Terry Reedy [EMAIL PROTECTED] wrote:

  Until the OP posted his lastest 'why', I assumed this proposal was an April
  Fools' post that he just could not wait to post.  In fact, given that the
  effective cost would be in  the $millions, I an still not sure he is sanely
  serious.

 I doubt you really thought that. I think you just want to make the OP
 feel like a fool. Do you feel better now? Where are the sensitivity
 police when they are needed?

 I find it interesting that someone can claim that Newton was not a
 scientist and be taken seriously on this site, but someone who
 suggests changing the name of a programming language is ridiculed.
 That's ridiculous.

Whether Newton was a scientist is a matter of opinion (mainly
regarding one's philosophy of science, and more specifically, the
demarcation problem); whether to change the name of python is a matter
of pragmatics. It's much easier to show that something is
pragmatically wrong (e.g., costs extra money with no overall gain),
than to show that someone's opinion about a complex matter is wrong.

On my view of science, Newton was a scientist (as is anyone using
the tools of discursive reasoning and empirical observation; even if
they don't strictly follow the scientific method). That's all great.
But my opinions have nothing to do with the fact that it makes no
pragmatic sense to change the name of python. It is a foolish (or
unwise if you want a more sensitive euphemism) suggestion.

The suggestion, in syllogism (w/ conjunctions of the first premise
broken into separate premises 1-N):

1 Python is not taken seriously because of its joke name
2 great people of the past deserve honor
3 it would get better publicity with a different name
N ...
N' we want to be taken seriously, c
Ergo, the name python should be changed to name X

It is easy to prove that premises 1-N are either true or false (or
pragmatically irrelevant, which can be considered as false to preserve
bivalence). So far, no compelling reasons have been given to think
them true, while several counter-examples and contradicting facts have
been given for thinking them false. Thus, a name change is
pragmatically stupid. QED.

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


Re: Generating API documentation as a textfile

2007-12-03 Thread MonkeeSage
On Dec 3, 8:58 am, Samuel [EMAIL PROTECTED] wrote:
 On Mon, 03 Dec 2007 06:45:45 -0800, Giampaolo Rodola' wrote:
  dir.__doc__

 This contains only the docstring one object (module, class,
 function, ...). I was thinking more of the complete API documentation
 that can be found in a file, and formatted in a readable way.

 -Samuel

Sounds like you want pydoc.

http://docs.python.org/lib/module-pydoc.html

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


Re: converting to and from octal escaped UTF--8

2007-12-02 Thread MonkeeSage
On Dec 2, 8:38 pm, Michael Goerz [EMAIL PROTECTED] wrote:
 Michael Goerz wrote:
  Hi,

  I am writing unicode stings into a special text file that requires to
  have non-ascii characters as as octal-escaped UTF-8 codes.

  For example, the letter Í (latin capital I with acute, code point 205)
  would come out as \303\215.

  I will also have to read back from the file later on and convert the
  escaped characters back into a unicode string.

  Does anyone have any suggestions on how to go from Í to \303\215 and
  vice versa?

  I know I can get the code point by doing
  Í.decode('utf-8').encode('unicode_escape')
  but there doesn't seem to be any similar method for getting the octal
  escaped version.

  Thanks,
  Michael

 I've come up with the following solution. It's not very pretty, but it
 works (no bugs, I hope). Can anyone think of a better way to do it?

 Michael
 _

 import binascii

 def escape(s):
 hexstring = binascii.b2a_hex(s)
 result = 
 while len(hexstring)  0:
 (hexbyte, hexstring) = (hexstring[:2], hexstring[2:])
 octbyte = oct(int(hexbyte, 16)).zfill(3)
 result += \\ + octbyte[-3:]
 return result

 def unescape(s):
 result = 
 while len(s)  0:
 if s[0] == \\:
 (octbyte, s) = (s[1:4], s[4:])
 try:
 result += chr(int(octbyte, 8))
 except ValueError:
 result += \\
 s = octbyte + s
 else:
 result += s[0]
 s = s[1:]
 return result

 print escape(\303\215)
 print unescape('adf\\303\\215adf')

Looks like escape() can be a bit simpler...

def escape(s):
  result = []
  for char in s:
result.append(\%o % ord(char))
  return ''.join(result)

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


Re: converting to and from octal escaped UTF--8

2007-12-02 Thread MonkeeSage
On Dec 2, 11:46 pm, Michael Spencer [EMAIL PROTECTED] wrote:
 Michael Goerz wrote:
  Hi,

  I am writing unicode stings into a special text file that requires to
  have non-ascii characters as as octal-escaped UTF-8 codes.

  For example, the letter Í (latin capital I with acute, code point 205)
  would come out as \303\215.

  I will also have to read back from the file later on and convert the
  escaped characters back into a unicode string.

  Does anyone have any suggestions on how to go from Í to \303\215 and
  vice versa?

 Perhaps something along the lines of:

def encode(source):
   ... return .join(\%o % ord(c) for c in source.encode('utf8'))
   ...
def decode(encoded):
   ... bytes = .join(chr(int(c, 8)) for c in encoded.split('\\')[1:])
   ... return bytes.decode('utf8')
   ...
encode(uÍ)
   '\\303\\215'
print decode(_)
   Í
   

 HTH
 Michael

Nice one. :) If I might suggest a slight variation to handle cases
where the encoded string contains plain text as well as octal
escapes...

def decode(encoded):
  for octc in (c for c in re.findall(r'\\(\d{3})', encoded)):
encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
  return encoded.decode('utf8')

This way it can handle both \\141\\144\\146\\303\\215\\141\\144\\146
as well as adf\\303\\215adf.

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


Re: converting to and from octal escaped UTF--8

2007-12-02 Thread MonkeeSage
On Dec 3, 1:31 am, MonkeeSage [EMAIL PROTECTED] wrote:
 On Dec 2, 11:46 pm, Michael Spencer [EMAIL PROTECTED] wrote:



  Michael Goerz wrote:
   Hi,

   I am writing unicode stings into a special text file that requires to
   have non-ascii characters as as octal-escaped UTF-8 codes.

   For example, the letter Í (latin capital I with acute, code point 205)
   would come out as \303\215.

   I will also have to read back from the file later on and convert the
   escaped characters back into a unicode string.

   Does anyone have any suggestions on how to go from Í to \303\215 and
   vice versa?

  Perhaps something along the lines of:

 def encode(source):
... return .join(\%o % ord(c) for c in source.encode('utf8'))
...
 def decode(encoded):
... bytes = .join(chr(int(c, 8)) for c in encoded.split('\\')[1:])
... return bytes.decode('utf8')
...
 encode(uÍ)
'\\303\\215'
 print decode(_)
Í

  HTH
  Michael

 Nice one. :) If I might suggest a slight variation to handle cases
 where the encoded string contains plain text as well as octal
 escapes...

 def decode(encoded):
   for octc in (c for c in re.findall(r'\\(\d{3})', encoded)):
 encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
   return encoded.decode('utf8')

 This way it can handle both \\141\\144\\146\\303\\215\\141\\144\\146
 as well as adf\\303\\215adf.

 Regards,
 Jordan

err...

def decode(encoded):
  for octc in re.findall(r'\\(\d{3})', encoded):
encoded = encoded.replace(r'\%s' % octc, chr(int(octc, 8)))
  return encoded.decode('utf8')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is not a good name, should rename to Athon

2007-12-01 Thread MonkeeSage
On Dec 1, 4:11 am, Bjoern Schliessmann usenet-
[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  New name Pytn may be better, do you think so ?

 No. How would you pronounce it? Pai-tn?

 Why don't you create a fork where the only difference is the name?

 Regards,

 Björn

 --
 BOFH excuse #194:

 We only support a 1200 bps connection.

My vote is for Pyrotron [1] 10,000, heh. ;)

[1] http://en.wikipedia.org/wiki/Disintegrator_ray

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


Re: Show this file in explorer

2007-12-01 Thread MonkeeSage
On Dec 1, 2:58 pm, farsheed [EMAIL PROTECTED] wrote:
 But now I have a more technical question. when I run this command, I
 saw that the windows explorer did not refresh,example: I have two
 files in a folder and i use that command to select them from command
 line, the first one will be  selected, but after running the command
 for second file, the second remains unselected. So I need to close the
 explorer and run the command again for the second file. this is
 different from the way iTunes do it.
 Any Idea?
 TIA.
 Farsheed.

I think you want some sort of OLE automation. Perhaps this will
help...

http://farm.tucows.com/blog/_archives/2004/11/23/189572.html

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


Re: reading raw variables from file

2007-11-30 Thread MonkeeSage
On Nov 30, 10:05 am, Martin Blume [EMAIL PROTECTED] wrote:
 Bruno Desthuilliers  schrieb



   I have a file that might contain literal python
   variable statements at every line. For example
   the file info.dat looks like this:
   users = [Bob, Jane]
   status = {1:ok,2:users[0]}
   the problem is I want to read this file and load
   whatever variables written in it as normal python
   variable statements so that when i read the file,
   my users var will be [Bob,Jane] and my status
   var will be {1:ok,2:users[0]} .
   Is there an easy way of doing this instead of
   parsing the files and checking said types?

   You might want to look at the eval, exec and execfile;

  Or just import...

   but bear in in mind Paddy's warning about security.

  +10

 If I have understood python naming scoping correctly,
 doing
my_var=hello
import stuff
print my_var
 is not the same as
my_var=hello
exec open(stuff.py).read()
print my_var
 with stuff.py containing
my_var=bye

It's not the same...

from stuff import *

...is.

 I use this exec open(stuff.py).read() mechanism to set
 values in my scripts: the script sets a useful default,
 a command-line argument in the form a valid python program
 may override it. Why bother with inventing or using another
 mechanism when this is perfectly simple, easy and self-explaining?

 The one and only thing against it is that a malicious user
 can sneak in an os.system(cd /  rm -rf *).

 IMHO. YMMV.
 Martin

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


Re: How to Teach Python Variables

2007-11-28 Thread MonkeeSage
On Nov 28, 8:35 am, Aaron Watters [EMAIL PROTECTED] wrote:
 On Nov 27, 5:31 pm, MonkeeSage [EMAIL PROTECTED] wrote:

  Of course. But then it really depends on the teaching methodology,
  doesn't it? There is no reason (well, barring the restraints of the
  curriculum vitea), that one should learn topics so complex as to
  require off-putting the *real* meaning until later, when one could
  just as easily learn the basic concepts first. I guess it's a matter
  of preference; whether you build from the top down (ala Berkley) or
  the other way 'round.

 As you hint, this is the tip of the iceberg
 of some very complex philosophical issues.
 For practical instruction I think there is
 overwhelming evidence you can't begin at the beginning.
 In mathematics you really can't teach starting
 with the axioms of set theory and build up from
 there -- you'd never get to long division before
 the students will have given up long ago.
 Similarly, in computer science you can't just
 go off to the beach to get some sand to start
 building a computer.  (Although when I was
 at Bell Labs the joke was that that was the
 Bell Labs attitude.)

 In practice you always have to start in the
 middle and tell the students not to worry
 about stuff that would add an overwhelming
 amount of detail.  For example, most beginning
 students will have a vague idea what
 the filesystem is, even though they will
 have to deal with it a lot -- and you don't
 want to get mired down for the first few weeks
 trying to talk about the filesystem.  Instead
 you say follow these steps and all will
 become clear later.  It's not a matter of
 preference -- it's a matter of necessity.

   -- Aaron Watters
 ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=lazy+future+ge...

I agree. I think that perhaps I overstated my point. Given that a
subject remains within the realm of intuition, I see no reason to hide
information; but after a certain (admittedly subjective) boundery,
things stop making intuitive sense (e.g., what do you mean that my
computer is made of sand? or what do you mean that what goes on in
my computer is no different than plugging in a toaster?). I just
don't see the merit in some approaches, where one starts a CS course
with C#/C++/Java and 75% of the language you have to ignore for now.
I think that type of approach leads to bad practices to say the least.
But indeed, there is a happy medium! You don't want to start with
assembler...but at the same time (my contention) you don't want to
start with private static void either. You want to start in the
happy medium, where analogies (*good* analogies) can be of no end of
helpfulness.

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


Re: the annoying, verbose self

2007-11-27 Thread MonkeeSage
On Nov 27, 3:20 am, Roy Smith [EMAIL PROTECTED] wrote:

 If you want to have a little fun:

 class peverse:
 def __call__(self):
 raise AttributeError (peverse instance has no __call__ method)

 x = peverse()
 x()

That is peverse, but still...

from types import FunctionType
type(x) == FunctionType # False

And you can't (easily?) subclass FunctionType:

Error when calling the metaclass bases
  type 'function' is not an acceptable base type

;)

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


Re: Find Replace hyperlinks in a string

2007-11-27 Thread MonkeeSage
On Nov 27, 1:37 am, Nico Grubert [EMAIL PROTECTED] wrote:
 Hi there,

 I have a string containing some hyperlinks. I'd like to replace every
 hyperlink with a HTML style link.

 Example:
 
 Replace
'http://www.foo.com/any_url'
 with
'a href=http://www.foo.com/any_url;http://www.foo.com/any_url/a'

 What's the best way to do this if I have a few hundret strings to check?

 Thanks in advance,
 Nico

Well, this isn't the most robust and someone will probably say not to
use regular expressions, but the QD way is:

import re
fixed = re.sub(r'(http:[^\s\n\r]+)', r'a href=\1\1/a',
your_string)

NB. If the URLs are malformed (like have spaces in them, or are broken
over several lines) this won't work right.

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


Re: spawning a process with subprocess

2007-11-27 Thread MonkeeSage
On Nov 27, 4:30 am, Nick Craig-Wood [EMAIL PROTECTED] wrote:
 MonkeeSage [EMAIL PROTECTED] wrote:
   Couple of things. You should use poll() on the Popen instance, and
   should check it explicitly against None (since a 0 return code,
   meaning exit successfully, will be treated as a false condition the
   same as None). Also, in your second example, you block the program
   when you call readlines on the pipe, since readlines blocks until it
   reaches eof (i.e., until pipe closes stdout, i.e., process is
   complete). Oh, and you don't have to split the input to the args
   option yourself, you can just pass a string.

 Though passing an array is good practice if you want to avoid passing
 user data through the shell.

Well, he was setting shell=True, but I guess being explicit (about
that) is better than implicit. ;)

  So, putting it all together, you want something like:

   import subprocess, time

   cmd = cat somefile
   proc = subprocess.Popen(args=cmd, shell=True,
 stdout=subprocess.PIPE, stdin=subprocess.PIPE,
 stderr=subprocess.STDOUT, close_fds=True)

   while 1:
 time.sleep(1)
 if proc.poll() != None:
   break
 else:
   print waiting on child...

   print returncode =, proc.returncode

 This works fine unless the command generates a lot of output (more
 than 64k on linux) when the output pipe will fill up and the process
 will block until it is emptied.

 If you run the below with `seq 1` then it works fine but as
 written the subprocess will block forever writing its output pipe
 (under linux 2.6.23).

 #
 import subprocess, time

 cmd = 
 for i in `seq 2`; do
   echo $i
 done
 exit 42
 

 proc = subprocess.Popen(args=cmd, shell=True,
   stdout=subprocess.PIPE, stdin=subprocess.PIPE,
   stderr=subprocess.STDOUT, close_fds=True)

 while 1:
   time.sleep(1)
   if proc.poll() != None:
 break
   else:
 print waiting on child...

 print returncode =, proc.returncode
 lines = 0
 total = 0
 for line in proc.stdout:
 lines += 1
 total += len(line)
 print Received %d lines of %d bytes total % (lines, total)
 #

 So you do need to read stuff from your subprocess, but there isn't a
 way in the standard library to do that without potentially blocking.

 There are a few solutions

 1) use the python expect module (not windows)

  http://pexpect.sourceforge.net/

 2) set your file descriptors non blocking.  The following recipe shows
 a cross platform module to do it.

  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554

 Or just do it with the fcntl module

 3) Use a thread to read stuff from your subprocess and allow it to
 block on proc.stdout.read()

 Here is an example of 2)

 #
 import subprocess, time, os
 from fcntl import fcntl, F_GETFL, F_SETFL
 from errno import EAGAIN

 cmd = 
 for i in `seq 10`; do
   echo $i
 done
 exit 42
 

 proc = subprocess.Popen(args=cmd, shell=True,
   stdout=subprocess.PIPE, stdin=subprocess.PIPE,
   stderr=subprocess.STDOUT, close_fds=True)

 # Set non blocking (unix only)
 fcntl(proc.stdout, F_SETFL, fcntl(proc.stdout, F_GETFL) | os.O_NONBLOCK)

 def read_all(fd):
 out = 
 while 1:
 try:
 bytes = fd.read(4096)
 except IOError, e:
 if e[0] != EAGAIN:
 raise
 break
 if not bytes:
 break
 out += bytes
 return out

 rx = 
 while 1:
   time.sleep(1)
   if proc.poll() != None:
 break
   else:
 print waiting on child...
 rx += read_all(proc.stdout)

 rx += read_all(proc.stdout)
 print returncode =, proc.returncode
 lines = 0
 total = 0
 for line in rx.split(\n):
 lines += 1
 total += len(line)
 print Received %d lines of %d bytes total % (lines, total)
 #

 Which runs like this on my machine

 $ python subprocess-shell-nb.py
 waiting on child...
 waiting on child...
 waiting on child...
 waiting on child...
 waiting on child...
 waiting on child...
 waiting on child...
 waiting on child...
 returncode = 42
 Received 11 lines of 488895 bytes total

 --
 Nick Craig-Wood [EMAIL PROTECTED] --http://www.craig-wood.com/nick

Nice. Thanks for the recipe link too.

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


Re: the annoying, verbose self

2007-11-27 Thread MonkeeSage
On Nov 27, 4:22 am, Bruno Desthuilliers

 You don't have to subclass function to define a callable type that
 implements the descriptor protocol so it behaves just like a function in
 the context of an attribute lookup.

I'm aware, and I understand that python's types (as with other duck-
typed languages) are basically just an object's capabilities; I was
just pointing out that, if needed (though I can't think of why
offhand...mabye some kind of sandbox?), you can detect built-in
functions. Hmm...but then again, it seems that shadowing a built-in
function still reports as it's type as FunctionType...

In [1]: from types import FunctionType

In [2]: def len(x):
   ...: # mischief
   ...: pass
   ...:

In [3]: type(len) == FunctionType
Out[3]: True

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


Re: A bug in Python's regular expression engine?

2007-11-27 Thread MonkeeSage
On Nov 27, 10:52 am, MonkeeSage [EMAIL PROTECTED] wrote:
 On Nov 27, 10:19 am, Just Another Victim of the Ambient Morality

 [EMAIL PROTECTED] wrote:
  That is funny.  Thank you for your help...
  Just for clarification, what does the r in your code do?

 It means a raw string (as you know ruby, think of it like %w{}):

 This page explains about string literal prefixes (see especially the
 end-notes):

 http://docs.python.org/ref/strings.html

 HTH,
 Jordan

Arg! %w{} should have said %q{}
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to Teach Python Variables

2007-11-27 Thread MonkeeSage
On Nov 27, 11:50 am, Donn Cave [EMAIL PROTECTED] wrote:

 In contrast, I suspect that someone who learns Python concepts
 in terms of explanations like `boxes' or `pointers' or whatnot
 is at some disadvantage while that lasts, like translating a
 foreign language to your own instead of attaching meaning
 directly.

I agree with your point, but I think the distinction is this:
pedagogical analogies should be truly *analogous* -- they should not
be analogies that are only vaguely similar and require you to
constantly say ...but ignore this difference and that
difference...oh, and that one...you'll learn that later. I personally
think the ignore this for now approach is detrimental. An example of
a real analogy, which is very useful (imho), is in regards to C
pointers. The analogy is to a real pointing device (nowadays, probably
a laser pointer). The pointer (pointing device) is one thing, and it
takes up its own dimensions of space; but it can point to something
else, and that something takes up its own dimensions as well. They are
not interchangeable;  they have their own identities. But by following
the pointer to the something else, and interpreting that something
according to its own nature (text, a picture, c), you can find the
value of the pointer. The pointer merely references that value.
And you can exchange the value that is referred to with any other
value of the same nature. You can, for example, point to a line of
code on an overhead projector. Then you can change the slide. Now the
value of the reference has changed, but the reference is the same. And
you can go one step further and point at an arrow symbol, which in
turn points to some other value in the context; the value turns out to
be another pointer which can be followed to it's own meaning. Granted,
it's an analogy, but I think it's a *good* analogy rather than a bad
one; it helps map the meaning to familiar objects, rather than the
trappings of the familiar preventing from grasping the concept.

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


Re: How to Teach Python Variables

2007-11-27 Thread MonkeeSage
On Nov 27, 2:49 pm, Aaron Watters [EMAIL PROTECTED] wrote:

 In practice there is too much to understand all at
 once and in the beginning you have to say don't worry about that
 right now, consider it magic...  Of course they should
 eventually understand it.

Of course. But then it really depends on the teaching methodology,
doesn't it? There is no reason (well, barring the restraints of the
curriculum vitea), that one should learn topics so complex as to
require off-putting the *real* meaning until later, when one could
just as easily learn the basic concepts first. I guess it's a matter
of preference; whether you build from the top down (ala Berkley) or
the other way 'round.

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


Re: spawning a process with subprocess

2007-11-26 Thread MonkeeSage
Hi Brian,

Couple of things. You should use poll() on the Popen instance, and
should check it explicitly against None (since a 0 return code,
meaning exit successfully, will be treated as a false condition the
same as None). Also, in your second example, you block the program
when you call readlines on the pipe, since readlines blocks until it
reaches eof (i.e., until pipe closes stdout, i.e., process is
complete). Oh, and you don't have to split the input to the args
option yourself, you can just pass a string. So, putting it all
together, you want something like:

import subprocess, time

cmd = cat somefile
proc = subprocess.Popen(args=cmd, shell=True,
  stdout=subprocess.PIPE, stdin=subprocess.PIPE,
  stderr=subprocess.STDOUT, close_fds=True)

while 1:
  time.sleep(1)
  if proc.poll() != None:
break
  else:
print waiting on child...

print returncode =, proc.returncode

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


Re: import pysqlite2 or import sqlite3?

2007-11-25 Thread MonkeeSage
I use the following for a progam I wrote using sqlite, to ensure
maximum compatibility (since the API is the same, importing them both
as 'sqlite' should be fine):

try:
  from sqlite3 import dbapi2 as sqlite # python 2.5
except:
  try:
from pysqlite2 import dbapi2 as sqlite
  except:
print 'This program requires pysqlite2\n',\
  'http://initd.org/tracker/pysqlite/'
sys.exit(1)

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


Re: How can I create customized classes that have similar properties as 'str'?

2007-11-25 Thread MonkeeSage
On Nov 24, 6:42 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:

 This has nothing, absolutely NOTHING, to do with memoization. Memoization
 trades off memory for time, allowing slow functions to return results
 faster at the cost of using more memory. The OP wants to save memory, not
 use more of it.

Not to beat a dead horse, but memoization can significantly minimize
memory usage, given a large data set with redundant elements (as the
OP seems to suggest [e.g., calculating the deltas of trigrams in a
natural language]). For example, if the data set has 1/3 redundant
elements, then the un-memoized version requires 1/3 more memory,
because it needs to store 1/3 more unique copies of the element,
whereas the memoized version has only to store unique elements once.
Every instance of an element which is already in the cache requires
only the cache lookup (speed), rather than the creation of a new
object (memory). So the trade-off is actually speed for memory rather
than the other way around. Of course, it all depends on the nature of
the data; but for large, redundant data sets, memoization is
definitely a win when it comes to memory optimization.

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


Re: the annoying, verbose self

2007-11-25 Thread MonkeeSage
I like the explicit self, personally. It helps distinguish class
methods from functions. When I see a self I think A-ha, a class
method. Of course, I could tell that from just the indentation and
following that back to the class declaration, but as a quick reference
I find it helpful. Besides, none of the proposals have sufficinetly
dealt with lexical scope without introducing a lot of costly checks
which would also hide the complexity of the process (and thereby, most
likely, lead to abuse and bad practices).

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


Re: the annoying, verbose self

2007-11-25 Thread MonkeeSage
The issue of lexical scope still looms large on the horizon. How does
one distinguish between attributes (as scoped by the with clause),
local/global variables, and function/method calls? There doesn't seem
to be an easy way. You'd need multiple passes over the data to
determine various scopes -- and for what, to save typing a few
characters? And even if implemented, it would mean hiding the
complexity of the resolution, which is not a good thing.

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


Re: import pysqlite2 or import sqlite3?

2007-11-25 Thread MonkeeSage
On Nov 25, 3:30 pm, Nick Craig-Wood [EMAIL PROTECTED] wrote:
 MonkeeSage [EMAIL PROTECTED] wrote:
   I use the following for a progam I wrote using sqlite, to ensure
   maximum compatibility (since the API is the same, importing them both
   as 'sqlite' should be fine):

   try:
 from sqlite3 import dbapi2 as sqlite # python 2.5

 I've been using

  import sqlite3 as sqlite

 here

 sqlite3 and sqlite3.dbapi2 seem to be the same thing

 Python 2.5.1 (r251:54863, Aug 17 2007, 00:51:07)
 [GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2
 Type help, copyright, credits or license for more information.
  from sqlite3 import dbapi2
  import sqlite3
  set(dir(sqlite3)) ^ set(dir(dbapi2))
 set(['__path__', 'dbapi2'])
 

 --
 Nick Craig-Wood [EMAIL PROTECTED] --http://www.craig-wood.com/nick

Didn't know that! Seeing that only two attributes differed between
them in your demonstration, I looked at the __init__.py for the
package, and all it does is from dbapi2 import *. Learn something
new every day. :)

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


Re: Disk Space Script

2007-11-24 Thread MonkeeSage
On Nov 24, 11:46 am, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:

 I would like to write a script in Python to email me when disk space
 gets below a certain value.

OK, I'll give you the easy way using your example and popen, and then
a more complex example that doesn't rely on df/grep/awk and uses only
system calls:


Easy way:

import os

# open a pipe to df ..., read from its stdout,
# strip the trailing \n, split it into a list on
# every \n, and put the results in 'data'
pipe = os.popen(df -x cifs -x iso9660 |  +
grep --color=never -E '^/dev' |  +
awk '{print $1, $4}')
data = pipe.read().strip().split('\n')
pipe.close()

# 'data' now looks like:
# ['/dev/hda1 1405056', '/dev/hda3 152000']

quota = 2097152 # 2GB

# iterate the list, splitting each element
# on ' ', and assigning the first and second
# elements to 'device' and 'free'
for node in data:
  device, free = node.split(' ')
  if int(free)  quota:
# your mail stuff here
print Device `%s' has less than %.2f GB free space % \
  (device, quota/1024.0/1024)


More complex way (well, less complex actually, just requires more
knowledge of python/fs):

quota = 2097152 # 2 GB

# map of mount point / device name
device_map = {'/'   : '/dev/hda1',
  '/mnt/shared' : '/dev/hda3'}

for mount, device in device_map.items():

  # statvfs returns tuple of device status,
  # see also man statvfs which this call wraps
  vstat = os.statvfs(mount)

  # (block size * free blocks) / 1024 = free bytes
  # NB: for large drives, there is a margin of error
  # in this naive computation, because it doesn't account
  # for things like inode packing by the fs. But for a
  # large quota like 2 GB, a +/- hundrend megs margin of
  # error should not cause any problem.
  free = (vstat[0] * vstat[4]) / 1024

  if free  quota:
# your mail stuff here
print Device `%s' has less than %.2f GB free space % \
  (device, quota/1024.0/1024)


References:

statvfs:
http://www.python.org/doc/lib/os-file-dir.html
http://www.python.org/doc/lib/module-statvfs.html

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


Re: eof

2007-11-23 Thread MonkeeSage
On Nov 22, 11:04 am, Neil Cerutti [EMAIL PROTECTED] wrote:

 I think it's too low level, and so doesn't do what naive users
 expect. It's really only useful, even in C, as part of the
 forensic study of a stream in an error state, [...]

Indeed. I just wrote a little implementation of an IPS patcher for the
ips patches used on many old game roms (snes, genesis) for doing fan
translations from Japanese to other languages. The basic format of a
patch is the ascii header PATCH, followed by 3 bytes telling offest
into datafile to apply patch chunk, 2 bytes telling chunk size, n
bytes of chunk, repeated, with final ascii EOF footer. As I was
using Haskell, the function was recursive, and it was useful to check
that EOF were the final bytes read and that no more bytes had been
read between the last data chunk and eof. In other words, on the
corner case that all the data in the patch was structurally valid,
except up to two bytes after the last chunk and before the EOF,
checking that the absolute position in the file was eof gave me the
ability to differentiate the error states of the patch lacking the
closing ascii EOF, or including extra data between the last chunk
and the EOF. Without checking eof (or doing something more complex),
I would have only been able to detect the error as a missing footer.

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


Re: foldr function in Python

2007-11-23 Thread MonkeeSage
On Nov 23, 8:56 pm, MonkeeSage [EMAIL PROTECTED] wrote:

 This doesn't matter for non-associative functions
 like +, but it does for associative functions like -.

Err...that's backwards...should have been:

This doesn't matter for associative functions
like +, but it does for non-associative functions like -.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: foldr function in Python

2007-11-23 Thread MonkeeSage
On Nov 23, 7:05 pm, greg [EMAIL PROTECTED] wrote:

 My feeling is that Python shouldn't provide a bunch of
 different versions of the same function that differ only in
 the degree of currying. If you want a particular curried
 combination, it's easy enough to create it as needed using
 lambda, nested functions or partial().

I agree about noy having different functions with different levels of
currying.

What's interesting is that no-one has yet implemented a real foldr on
this thread -- all of the examples have been of foldl. The foldr is
right-associative. This doesn't matter for non-associative functions
like +, but it does for associative functions like -.

def foldl(f, l, i): # same as reduce()
  if len(l) == 0:
return i
  else:
return foldl(f, l[1:], f(i, l[0]))

def foldr(f, l, i):
  l.reverse()
  def _foldr(f, l, i):
if len(l) == 0:
  return i
else:
  return _foldr(f, l[1:], f(l[0], i))
  return _foldr(f, l, i)

foldl(int.__sub__, [1,2,3,4], 0)
# -10

foldr(int.__sub__, [1,2,3,4], 0)
# -2

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


Re: Clean way to get one's network IP address?

2007-11-23 Thread MonkeeSage
On Nov 21, 9:15 am, Gilles Ganault [EMAIL PROTECTED] wrote:
 Hello

 I need to get the local computer's IP address, ie. what's displayed
 when running ifconfig in Linux:

 # ifconfig
 eth0  Link encap:Ethernet  HWaddr 00:15:58:A1:D5:6F
   inet addr:192.168.0.79  Bcast:192.168.0.255
 Mask:255.255.255.0

 I know about socket.gethostbyname, but this relies on what's in
 /etc/hosts, and I'd rather have a more independent solution.

 What would be a good way to do this?

 Thank you.

For linux (and possibly other POSIX-like OS', though reported not to
work on FreeBSD), see the pure python 'ifconfig' script I posted here:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/52ad421ed64ec3fc/13e2a0609920c27b?lnk=gstq=monkeesage+hwaddr#a4419fd2c52078e2

It uses low-level ioctl to query the same values as are displayed in
ifconfig. It's obviously not very portable, but I didn't know what
exactly you meant by independent.

Regards,
Jordan

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


Re: eof

2007-11-23 Thread MonkeeSage
On Nov 23, 10:43 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  This is not the same as ISO C. f.tell could be equal to
 File.size(f.path) and eof could be false. An extra read() is required.

My bad. As you might have surmised, I'm not a genius when it comes to
C. I thought that the eof flag was set when the pointer into the
stream was the same as the length of the stream, but I guess it makes
since that as an error flag, it would only be set after an attempted
read past the end of the stream (in which case, I guess you'd get a
NULL from the read, equivalent to python's empty string?).

Ps. braver, if you really want a ruby-like eof method on file objects
in python, how about overriding the open() alias with a file subclass
including eof?

import os

class open(file):
  def __init__(self, name):
self.size = os.stat(name).st_size
file.__init__(self, name)
  def eof(self):
return self.tell() == self.size

f = open('tmp.py')
print f.eof() # False
f.read()
print f.eof() # True

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


Re: eof

2007-11-23 Thread MonkeeSage
On Nov 23, 10:00 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  Ruby doesn't have the good ol' eof. Good old eof tests a single flag
 and requires a pre read(). Ruby's eof blocks and does buffering (and
 this is a very strong technical statement).

Actually, to be a bit more technical, IO#eof acts like standard C eof
for File objects, it only blocks / requires a previous read() on
character devices and pipes and such. For files, it's the same as
checking the absolute position of the file stream: f.tell ==
File.size(f.path).

Of course, the same can be done in python quite easily (and probably
better implemented):

f.tell() == os.stat(f.name).st_size

I don't honestly see what the big deal is about including or excluding
an eof function / method in python. If you need it, it is easy to
implement, and like yourself and others have shown, you usually don't
need it.

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


Re: eof

2007-11-23 Thread MonkeeSage
On Nov 23, 6:56 pm, greg [EMAIL PROTECTED] wrote:

 By not providing an eof() function, C -- and Python -- make
 it clear that testing for eof is not a passive operation.
 It's always obvious what's going on, and it's much harder to
 make mistakes like the above.

err...C has feof() in stdio (see man 3 ferror).

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


Re: A proposal for attribute lookup failures

2007-11-18 Thread MonkeeSage
On Nov 18, 5:27 am, James Stroud [EMAIL PROTECTED] wrote:

 It would be unoriginal of me to suggest that this violates the explicit
 is better than implicit maxim. But it does.

That's what I meant about hiding the complexity of an attribute
failure. Though, sometimes implicit is acceptable (e.g., promotion of
int to float by __add__ when RHS is a float). Perhaps not here though.


 Also, you have picked the perfect use case for a counter argument:

 py class NoLen(object):
 ...   pass
 ...
 py len(NoLen)
 
 Traceback (most recent call last):
File ipython console, line 1, in module
 type 'exceptions.TypeError': object of type 'type' has no len()

 So this proposal would send the interpreter through two cycles of trying
 to find the proper attribute before it failed.

Ah. Good point. Hadn't thought of that.



On Nov 18, 6:42 am, Arnaud Delobelle [EMAIL PROTECTED] wrote:

 It changes how the following code executes:

 --
 def foo(x): return x.foo()
 foo(1)
 --

 * currently this raises AttributeError
 * under your proposal this code would fill the stack and raise a
 RuntimeError I guess.

I think it would be easy enough to detect and avoid cyclic references
like that (it's done in other instances in the language). An exception
could be thrown in such a case. But maybe it would be more difficult
than I imagine, leading to even further complexity (bad).

I think that, given that it hides a complex operation (which could
easily lead to abuse by the unwashed masses), and that in many cases
multiple lookups in the symbol table would be necessary before
termination (as in James' example above), as well as having to deal
with cases such as you mention, perhaps it's not such a good idea.

Off the cuff, it seemed like a nice feature (and still does, if it
could be implemented without the drawbacks). But such is life. :)

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


Re: A proposal for attribute lookup failures

2007-11-18 Thread MonkeeSage
Ps. Just for kicks, here is a simple ruby 1.8 mock-up of the proposal
(sorry for using ruby, but I don't know enough C to start hacking the
CPython backend; I think that a higher-level example is conceptually
clearer anyhow). Reference cycles are not detected in the example.

#!/usr/bin/ruby

class Object
  def method_missing(fun, *args)
begin
  TOPLEVEL_BINDING.method(fun).call(self, *args)
rescue
  raise(NoMethodError,
%{undefined method `#{fun.to_s}' for #{self}:String},
[])
end
  end
end

def myfun(s1, s2)
  s1 + s2
end

puts foo.myfun(bar)
# - foobar

puts 1.myfun(2)
# - 3

puts foo.nofun(baz)
# - ./attr_fail.rb:10: undefined method `nofun' for foo:String
(NoMethodError)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A proposal for attribute lookup failures

2007-11-18 Thread MonkeeSage
On Nov 18, 5:59 pm, Kay Schluehr [EMAIL PROTECTED] wrote:

 No need to excuse. I think Ruby provides a nice context for discussing
 the semantics of top level open classes. But I think those are
 entirely different than your contextual bindings. Note I find your
 proposal somewhat confusing since I expect that an attribute is
 owned by an object and is not an arbitrary contextual property.

I obviously like ruby as well as python, I just didn't want to turn
the discussion into a I can do this in ruby, can you do that in
python thread, so my apology was more along those lines that an
apology for using ruby at all. :)

As far as ownership of an object, that's what object abstraction is
all about is it not? Multiple instances can own a method via
polymorphic substitution, without a strict interface definition. My
proposal simply adds a new scope within which to look for ownership.
Of course, there are problems with that, as noted above.

 Regarding open classes in Python, what about extension classes?

 class +object:
def len(self):
return self.__len__()

 This either adds the len method to the namespace of object or it
 creates a new namespace which is associated with the namespace of
 object s.t. each object can lookup attributes in this namespace when
 default lookup fails. I'm not entirely sure about scope. I think the
 lifetime of an extension class shall be determined by the lifetime of
 the extended class and not by the scope in which the extension class
 is defined. What do you think?

Sounds like a interesting approach! Worth looking into, imo.

 PS. you can use EasyExtend when you want to provide a language
 extension without hacking the CPython runtime. EE was made for such
 kinds of experiments.

Hadn't seen that before, thanks for the reference. :)

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


Re: Simple eval

2007-11-18 Thread MonkeeSage
As I see it, just as a matter of common sense, there will be no way to
match the performance of the backend eval() with any interpreted code.
At best, performance-wise, a preprocessor for the built-in eval()
would be in order, filtering out the unsafe cases and passing the
rest through. But what do I know, I could be dead wrong. :)

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


Re: regular expression

2007-11-18 Thread MonkeeSage
On Nov 18, 3:54 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:

 What the heck is that format? XML's retarded cousin living in the attic?

ROFL...for some reason that makes me think of wierd Ed Edison from
maniac mansion, heh ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too complex ?!?!?!

2007-11-18 Thread MonkeeSage
On Nov 17, 7:46 am, Brian [EMAIL PROTECTED] wrote:
 Had a unsettling conversation with a CS instructor that
 teaches at local high schools and the community
 college. This person is a long-term Linux/C/Python
 programmer, but he claims that the install, config, and
 library models for C# have proved to be less
 problematic than Python. So both his courses (intro,
 data structs, algorithms) are taught in C#.

 I am a low-end (3-year) journeyman Pythonista, and I
 was attracted to the language because of its
 simplicity. And I have come to enjoy the richness of
 available libraries.

 Many of the good people of this NG may be 'too close'
 to answer, but has Python, as a general devel platform,
 lost its simplicity ? Is library install too complex
 and unreliable ? Will my dog go to heaven ?

I started out with some javascript and ruby background, and I
mastered (i.e., could do everything I wanted to do in) python in a
few months (including playing with the GTK bindings). I only have a
GED, so I'm not the smartest programmer in the world or anything. But
even so, the learning curve for python, for me, was very gradual.
Nothing to too complex to swallow a spoonful at a time. After several
years of using python (a very short time in the long-run, mind you), I
think that the basic concepts are as simple as ever, and it remains a
prime candidate for a CS 101 course.

On the other hand, C# and .NET seems like a lot of baggage to bring to
the table. First off, you have to introduce the CLR and how it relates
to C#, then you have to deal with all the public, private, etc,
syntaxis for constructors/destructors. I don't see how anyone could
claim that C# is simpler to teach than python. I mean, (non-PC
statement follows), it's easier to teach retarded, blind children to
recite the lord's prayer backwards, in sign language, than it is to
get a working .net environment set up for actual use w/o installing
the latest visual studio. And not everyone had five-million dollars
(or a corporate license) to get the latest and greatest VS.

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


Re: newbie Q: sequence membership

2007-11-18 Thread MonkeeSage
On Nov 19, 12:32 am, saccade [EMAIL PROTECTED] wrote:

 I am not a programmer so I feel odd commenting about language design
 decisions. When my Prof. introduced python the first question that
 popped into mind was that since x=9; y=9; print x is y and x == y
 prints True is there a way to change the value of 9? He said that
 was silly but after class showed me that statements True = [] work
 but suggested it was harmless and not quite a bug.

 So if I am permitted to think of integers as immutable objects with
 predefined labels (i.e. the integers used in the text of the program
 code) that cannot de or re referenced then what a similar treatment of
 characters will look like seams to be an arbitary (a design) decition.

 In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer
 to the same object. If one follows the convention used with integers
 (9 and 9 refer to the same object) then 'ab' and 'ab' would be the
 same. An equally reasonable assumption would be that 'ab' and 'ab' are
 two different sequences and so not equal (I do not see the problem
 here).

The problem is with side-effets. With pure code, your reasoning
would be sound; but given that side-effects may alter the execution
path, [EMAIL PROTECTED] and [EMAIL PROTECTED] may _not_ refer to the same 
object. This
observation, is, of course, highly superfluous. ;)

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


A proposal for attribute lookup failures

2007-11-17 Thread MonkeeSage
Proposal:

  When an attribute lookup fails for an object, check the top-level
(and local scope?) for a corresponding function or attribute and apply
it as the called attribute if found, drop through to the exception
otherwise. This is just syntactic sugar.


Example:

  a = [1,2,3]

  a.len()
  # - fails,
  # - finds len() in the top-level symbol table,
  # - applies len(a)
  # - 3

  a.foobar()
  # - fails,
  # - no foobar() in scope,
  # - raise NameError


Benefits:

  - Uniform OO style. Top-levels can be hidden as attributes of data.
Most of the top-level functions / constructors can be considered as
attributes of the data; e.g., an int() representation of a string can
be considered as _part_ of the semantics of the string (i.e., one
_meaning_ of the string is an int representation); but doing it this
way saves from storing the int (etc) data as part of the actual
object. The trade-off is speed for space.

  - Ability to add attributes to built-in types (which is requested
all the time!!) without having to sub-class a built-in type and
initialize all instances as the sub-class. E.g., one can simply define
flub() in the top-level (local?) namespace, and then use blah.flub()
as if the built-in str class provided flub().

  - Backwards compatible; one can use the top-level functions when
desired. No change to existing code required.

  - Seemingly trivial to implement (though I don't know much C). On
attribute lookup failure, simply iterate the symbol table looking for
a match, otherwise raise the exception (like current implementation).


Drawbacks:

  - Could hide the fact that an extra (On?) lookup on the symbol table
is necessary for attribute lookup failure. (Maybe there could be a
switch/pragma to enable (or disable) the functionality?)

  - As above, attribute lookup failure requires an extra lookup on the
symbol table, when normally it would fall through directly to
exception.

  - ???


Disclaimer:

  I realize that very often what seems good to me, ends up being half-
assed, backwards and generally bad. So I'd appreciate input on this
proposition. Don't take it that I think the idea is wonderful and am
trying to push it. I am just throwing it out there to see what may
become of it.

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


Re: Single string print statements on multiple lines.

2007-03-12 Thread MonkeeSage
HeEm wrote:
 In my 100 level CS course, I was asked to create multiple lines of
 output within a single string.  Of course I know how to:

If this is for a CS course, you shouldn't really be cheating and
asking for an answer here, should you? I mean, the whole point of
taking (and paying for!) a CS course is to learn CS, right? But like
Diez said, the standard C escapes work in python: \t = TAB, \r =
CARRIAGERETURN, \n = NEWLINE/LINEFEED, c.

Regards,
Jordan

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


Re: number generator

2007-03-11 Thread MonkeeSage
On Mar 11, 2:16 am, greg [EMAIL PROTECTED] wrote:
 MonkeeSage wrote:
  this ... requires that M be evenly divisible by N,

 No, it doesn't -- I never said the numbers had
 to be *equal*.

Sorry for not being clear. I was refering to my specific
implementation of the algorithm, not the generic design pattern.

Regards,
Jordan

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


Re: Help controlling CDROM from python

2007-03-10 Thread MonkeeSage
On Mar 10, 8:27 am, Ognjen Bezanov [EMAIL PROTECTED] wrote:
 My issue is that I need to be able to eject the CDROM tray even if there
 is no disk inside.

Here's a QD version (haven't tested the windows part, it's from an
old mailing list post, but it looks correct):


import os, sys
if 'win' in sys.platform:
# untested: found in old mailing list post:
# http://mail.python.org/pipermail/python-win32/2002-November/000593.html
import win32file
from win32con import *
drive = 'D:'
win32file.CreateFile(r'\\.\\' + drive, GENERIC_READ,
FILE_SHARE_READ,
 None, OPEN_EXISTING, 0, 0)
# IOCTL_STORAGE_EJECT_MEDIA = 0x002d4808 from winioctl.h
win32file.DeviceIoControl(h, 0x002d4808, , 0)
win32file.CloseHandle(h)
else: # does this work on OSX and BSD?
import fcntl
cd_device  = '/dev/cdrom'
if os.path.islink(cd_device):
base_path = os.path.dirname(cd_device)
cd_device = os.readlink(cd_device)
if not cd_device[0] == '/':
cd_device = os.path.join(base_path, cd_device)
cdrom = os.open(cd_device, os.O_RDONLY | os.O_NONBLOCK)
# CDROMEJECT = 0x5309 from linux/cdrom.h on linux 2.6
fcntl.ioctl(cdrom, 0x5309, 0)
os.close(cdrom)


NB: If you're using pygame, you can also just use it's builtin
commands:

import pygame.cdrom as cdrom
cdrom.init()
cd = cdrom.CD(0) # 0 = first cdrom device
cd.init()
cd.eject()
cd.quit()
cdrom.quit()

Regards,
Jordan

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


Re: number generator

2007-03-10 Thread MonkeeSage
On Mar 10, 3:16 am, greg [EMAIL PROTECTED] wrote:
 Another possibility is to generate a list of N non-random
 numbers that sum to M, and then adjust them up or down
 by random amounts. By performing up/down adjustments in
 pairs, you can maintain the sum invariant at each step.
 So then it's just a matter of how long you want to go
 on fiddling with them.

Taking your comment and running with it...this is pretty much
cheating, and requires that M be evenly divisible by N, and only works
well with smaller N values, and selections are limited to numbers in
the 1 to (M/N)+(M/N) range...but hey; other than that it's perfect,
heh.

import random
N, M = 10, 80
D= M/N
O= [D] * N
C= []
for i in O:
C.append(random.randint(1, D-1))
for i in range(0, len(O), 2):
O[i] -= C[i]
if i == len(O)-1:
O[random.randint(0, i-1)] += C[i]
else:
O[i+1] += C[i]
assert sum(O) == M
assert len(O) == N

Regards,
Jordan

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


Re: number generator

2007-03-10 Thread MonkeeSage
On Mar 10, 6:47 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 The fencepost method still seems to be simplest:

 t = sorted(random.sample(xrange(1,50), 4))
 print [(j-i) for i,j in zip([0]+t, t+[50])]

Simpler, true, but I don't think it gives any better distribution...

import random
def cheat(n, m):
N, M = n, m
D= M/N
O= [D] * N
C= []
for i in O:
C.append(random.randint(1, D-1))
for i in range(0, len(O), 2):
O[i] -= C[i]
if i == len(O)-1:
O[random.randint(0, i-1)] += C[i]
else:
O[i+1] += C[i]
print 'CHEAT:'
print O

def fence(n, m):
t = sorted(random.sample(xrange(1,m), n-1))
print 'FENCE:'
print [(j-i) for i,j in zip([0]+t, t+[m])]

for i in range(10):
print 'Run: %d:' % (i+1)
cheat(10, 80)
fence(10, 80)
print

Output:

Run: 1:
CHEAT:
[1, 15, 1, 15, 5, 11, 5, 11, 1, 15]
FENCE:
[4, 9, 24, 7, 3, 9, 11, 7, 3, 3]

Run: 2:
CHEAT:
[1, 15, 5, 11, 5, 11, 1, 15, 7, 9]
FENCE:
[15, 12, 13, 7, 1, 4, 5, 6, 4, 13]

Run: 3:
CHEAT:
[1, 15, 3, 13, 3, 13, 2, 14, 7, 9]
FENCE:
[2, 9, 12, 15, 4, 5, 2, 3, 19, 9]

Run: 4:
CHEAT:
[7, 9, 2, 14, 5, 11, 4, 12, 3, 13]
FENCE:
[2, 2, 4, 7, 1, 11, 15, 13, 6, 19]

Run: 5:
CHEAT:
[5, 11, 3, 13, 5, 11, 7, 9, 4, 12]
FENCE:
[2, 4, 11, 10, 13, 16, 2, 18, 1, 3]

Run: 6:
CHEAT:
[5, 11, 3, 13, 2, 14, 6, 10, 1, 15]
FENCE:
[1, 4, 13, 5, 2, 26, 5, 4, 16, 4]

Run: 7:
CHEAT:
[4, 12, 4, 12, 4, 12, 4, 12, 5, 11]
FENCE:
[8, 3, 5, 15, 8, 15, 2, 3, 10, 11]

Run: 8:
CHEAT:
[3, 13, 5, 11, 6, 10, 1, 15, 2, 14]
FENCE:
[25, 15, 2, 5, 2, 10, 6, 1, 9, 5]

Run: 9:
CHEAT:
[6, 10, 3, 13, 2, 14, 1, 15, 5, 11]
FENCE:
[11, 9, 3, 3, 7, 4, 8, 28, 1, 6]

Run: 10:
CHEAT:
[2, 14, 3, 13, 6, 10, 2, 14, 2, 14]
FENCE:
[12, 5, 23, 2, 3, 4, 4, 11, 5, 11]

Granted, I'm just eyeballing it, but they look fairly equal in terms
of distribution.

Regards,
Jordan

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


Re: Help controlling CDROM from python

2007-03-10 Thread MonkeeSage
On Mar 10, 4:11 pm, MonkeeSage [EMAIL PROTECTED] wrote:
 win32file.CreateFile(r'\\.\\' + drive, GENERIC_READ,
 FILE_SHARE_READ,
  None, OPEN_EXISTING, 0, 0)

Oops! That should have been:

h = win32file.CreateFile(r'\\.\\' + drive, GENERIC_READ,
 FILE_SHARE_READ, None,
 OPEN_EXISTING, 0, 0)

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


Re: Python in a desktop environment

2007-03-10 Thread MonkeeSage
On Mar 10, 9:23 pm, David Cramer [EMAIL PROTECTED] wrote:
 If you had an application that you were about to begin development on
 which you wanted to be cross platform (at least Mac and Windows),
 would you suggest using c++ and Python?

Depending on what exactly you're trying to do, a pure python solution
may be sufficient, though obviously a C/C++ backend would be portable
as well. In terms of GUI; GTK or QT would probably be your best bet
(my personal preference is for pygtk), though Wxidgets may be a viable
option if the others are not (I'm not sure how advanced GTK/QT support
is on OSX). Your question is kind of vague, so this response is vague
as well. More info is needed to answer in a more specific way.

Regards,
Jordan

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


Re: minimum age to learn python (a.k.a graphical vs text languages)

2007-03-10 Thread MonkeeSage
 first person shooter programming language 

OMG! Thank's freakin awsome, lol!!!

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


Re: number generator

2007-03-10 Thread MonkeeSage
On Mar 10, 11:26 pm, Steven D'Aprano
[EMAIL PROTECTED] wrote:
 To compare to the cheat method, calculate the mean and standard
 deviation of this sample, and compare to those from the other method.

I belieive you (mainly because I'm too lazy to write the sieve,
hehe). ;)

Regards,
Jordan

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


Re: Where to import?

2007-03-08 Thread MonkeeSage
On Mar 8, 5:49 pm, Bruno Desthuilliers
[EMAIL PROTECTED]
 1/ better to stick to naming conventions (class names in CamelCase)

  Ok. Thanks.

 FWIW:http://www.python.org/dev/peps/pep-0008/

By my reading, PEP8 doesn't specify CamelCase as preferred over the
other styles it mentions. non_camel_case is also considered good
style, as I understand (and is used all over the standard library).

Regards,
Jordan

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


Re: Where to import?

2007-03-08 Thread MonkeeSage
Disregard my last message, I'm stupid. I totally missed that Bruno was
talking about classname. Bruno is exactly right.

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


Re: I am a new guy on python world

2007-03-08 Thread MonkeeSage
Welcome. :)

Regards,
Jordan

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


Re: Where to import?

2007-03-08 Thread MonkeeSage
On Mar 8, 10:27 pm, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 Class names should be CamelCase. Read it again, and notice the difference
 between a Descriptive section and a Prescriptive one.

Yes, I misread Bruno's comment (missed that he was speaking of class
names). Disregard my post.

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


Re: finding monitor or screen resolution in Linux with standard python module

2007-03-07 Thread MonkeeSage
On Mar 7, 4:25 am, akbar [EMAIL PROTECTED] wrote:
 I googled and searched in archive. All I can find is finding
 resolution with Tkinter and pygame. Any idea to find monitor
 resolution with standard python module?
 I can check from output of: xprop -root
 _NET_DESKTOP_GEOMETRY(CARDINAL) . The problem is when you use Beryl or
 Xgl, it is not correct anymore because Beryl or Xgl set this value
 from amount of workspaces multiplied by monitor or screen resolution.

Perhaps read-edid [1] or ddcprobe [2] would work since they read the
info strait off the EDID. You could probably read the EDID from python
(mabye through the xlib binding?), but no need to reinvent the wheel.

[1] http://john.fremlin.de/programs/linux/read-edid/index.html
[2] http://sources.gentoo.org/viewcvs.py/gentoo-src/Xorgautoconfig/ddcprobe/

Regards,
Jordan

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


Re: catching exceptions from an except: block

2007-03-07 Thread MonkeeSage
On Mar 7, 4:58 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
except_retry: # the missing(???) keyword you're after

What is 'except_retry'?

To the OP, with the loop and the callables you could also break out of
the loop when the condition is met and use the else condition to raise
the exception.

def test(arg):
for f in int, float, str, hex:
try:
return f(arg)
break # breaks on f==str
except:
pass
else:
raise ValueError # remove str above to see this
print test('^%')

Regards,
Jordan


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


Re: SPE python IDE: Call for testers!

2007-03-06 Thread MonkeeSage
Very nice. One issue I've come across is that it doesn't seem to work
with  wxwidgets-2.8 (segfault when trying to load a file), so you
should probably set MIN_WX_VERSION to 2.8.

Regards,
Jordan

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


Re: Interface Implementation in Python

2007-03-06 Thread MonkeeSage
On Mar 6, 6:23 pm, [EMAIL PROTECTED] wrote:
 I dont want to expose the above Point3D implementation to the user /
 client side.To achieve that we can use interface concept.In Python to
 use interface concept.

In python you would use name mangling to hide parts of the interface
from the public.

class Point3D:
def __init__(self):
self.__x = 0.0
self.__y = 0.0
self.__z = 0.0

def __setPoint(x,y,z):
self.__x = x
self.__y = y
self.__z = z

def __getPoint(x,y,z):
x = self.__x
y = self.__y
z = self.__z

p = Point3D()
p.__setPoint(1,2,3)

# ...
# AttributeError: Point3D instance has no attribute '__setPoint'

Regards,
Jordan

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


Re: Is every number in a list in a range?

2007-03-05 Thread MonkeeSage
On Mar 5, 1:03 pm, Steven W. Orr [EMAIL PROTECTED] wrote:
 I have a list ll of intergers. I want to see if each number in ll is
 within the range of 0..maxnum

How about:

maxnum = 100
inlist = range(90, 120)
for i in [i for i in inlist if i = 0 and i = maxnum]:
# do something with i, it's in the valid range
print i

Regards,
Jordan

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


Re: Squisher -- a lightweight, self-contained alternative to eggs?

2007-03-05 Thread MonkeeSage
Adam,

Sounds like a nice idea to me. Pretty ingenious use of the zip/
bytecode headers and all too. Post a message when you release it
please.

Regards,
Jordan

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


Re: Squisher -- a lightweight, self-contained alternative to eggs?

2007-03-05 Thread MonkeeSage
Stef,

What Adam is talking about has nothing to do with windows or *nix.
He's talking about packing one or more .py files into a single
archive, which can be imported just like the regular .py files. This
means you can distribute a whole bunch of module files/dirs as a
single .pyc file. It just makes it easier to have a single file to
distribute rather than a whole bunch, or a zip that one has to unzip
into a certain directory, c. So you can have myscript.py +
myscriptfiles.pyc vs. myscript.py + somedepdir/ + someotherdepdir/ +
somedepfile.py...c.

If you still don't get it, you don't need it.

Regards,
Jordan

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


Re: Interface Implementation in Python

2007-03-05 Thread MonkeeSage
On Mar 5, 6:25 pm, [EMAIL PROTECTED] wrote:
 Hi,

  I would like to know the interface concept in Python.How the
 Interface is defined and implemented in Python?.

 How to access the interface fromn Client?

 Thanks
 PSB

Not sure exactly what you mean, but in python (like most dynamic
languages) an interface is simply a behavioral type system. Any
object can implement an interface, based on its signature. For
example; let's say you have a file object which implements read() and
write(). Any other object with a sufficiently similar signature (e.g.,
StringIO), can be said to implement the same interface. An interface
in python is simply a specified behavior, and any object which
implements that behavior can be said to have the same interface.

HTH,
Jordan

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


Re: Is every number in a list in a range?

2007-03-05 Thread MonkeeSage
On Mar 5, 7:24 pm, Paul Rubin http://[EMAIL PROTECTED] wrote:
 This genexp is better than a loop because it bails out immediately
 if it finds an out-of-range x.

That's true: assuming that input is sequential. But if it's farily
random (e.g., [10, 20, 12, 46, 202, 5, 102]), then you need a loop/
list comp. to check each index.

Regards,
Jordan

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


  1   2   3   >