Re: Blog source code in Python

2006-06-23 Thread Lad
Frederic and Klaus,
Thank you for the reply
L.

Klaus Alexander Seistrup wrote:
 Lazy Lad wrote:

  Is there a blog application source available in Python?

 Several.  Did you try Google before you posted your question?  The search
 term python blog has http://wiki.python.org/moin/PythonBlogSoftware
 within the first 10 hits.

 Cheers,

 --
 Klaus Alexander Seistrup
 Copenhagen, Denmark
 http://surdej.dk/

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


Re: Specifing arguments type for a function

2006-06-23 Thread George Sakkis
Dennis Lee Bieber wrote:
 On 22 Jun 2006 16:48:47 -0700, George Sakkis [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:

  What does __setitem__ have to do with iterability ?

   It confirms that the object is indexable, and mutable -- ie; a list,
 not a tuple or a string.

Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ? I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications  (e.g.
strings). It's not rocket science.

George

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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Anton van Straaten
Chris Smith wrote:
 I don't recall who said what at this 
 point, but earlier today someone else posted -- in this same thread -- 
 the idea that static type advocates want to classify some languages as 
 untyped in order to put them in the same category as assembly language 
 programming.  That's something I've never seen, and I think it's far 
 from the goal of pretty much anyone; but clearly, *someone* was 
 concerned about it.  I don't know if much can be done to clarify this 
 rhetorical problem, but it does exist.

For the record, I'm not concerned about that problem as such.  However, 
I do think that characterizations of dynamically typed languages from a 
static type perspective tend to oversimplify, usually because they 
ignore the informal aspects which static type systems don't capture.

Terminology is a big part of this, so there are valid reasons to be 
careful about how static type terminology and concepts are applied to 
languages which lack formally defined static type systems.

 The *other* bit that's been brought up in this thread is that the word 
 type is just familiar and comfortable for programmers working in 
 dynamically typed languages, and that they don't want to change their 
 vocabulary.

What I'm suggesting is actually a kind of bridge between the two 
positions.  The dynamically typed programmer tends to think in terms of 
values having types, rather than variables.  What I'm pointing out is 
that even those programmers reason about something much more like static 
types than they might realize; and that there's a connection between 
that reasoning and static types, and also a connection to the tags 
associated with values.

If you wanted to take the word type and have it mean something 
reasonably consistent between the static and dynamic camps, what I'm 
suggesting at least points in that direction.  Obviously, nothing in the 
dynamic camp is perfectly isomorphic to a real static type, which is why 
I'm qualifying the term as latent type, and attempting to connect it 
to both static types and to tags.

 The *third* thing that's brought up is that there is a (to me, somewhat 
 vague) conception going around that the two really ARE varieties of the 
 same thing.  I'd like to pin this down more, and I hope we get there, 
 but for the time being I believe that this impression is incorrect.  At 
 the very least, I haven't seen a good way to state any kind of common 
 definition that withstands scrutiny.  There is always an intuitive word 
 involved somewhere which serves as an escape hatch for the author to 
 retain some ability to make a judgement call, and that of course 
 sabotages the definition.  So far, that word has varied through all of 
 type, type error, verify, and perhaps others... but I've never 
 seen anything that allows someone to identify some universal concept of 
 typing (or even the phrase dynamic typing in the first place) in a way 
 that doesn't appeal to intuition.

It's obviously going to be difficult to formally pin down something that 
is fundamentally informal.  It's fundamentally informal because if 
reasoning about the static properties of terms in DT languages were 
formalized, it would essentially be something like a formal type system.

However, there are some pretty concrete things we can look at.  One of 
them, which as I've mentioned elsewhere is part of what led me to my 
position, is to look at what a soft type inferencer does.  It takes a 
program in a dynamically typed language, and infers a static type scheme 
for it (obviously, it also defines an appropriate type system for the 
language.)  This has been done in both Scheme and Erlang, for example.

How do you account for such a feat in the absence of something like 
latent types?  If there's no static type-like information already 
present in the program, how is it possible to assign a static type 
scheme to a program without dramatically modifying its source?

I think it's reasonable to look at a situation like that and conclude 
that even DT programs contain information that corresponds to types. 
Sure, it's informal, and sure, it's usually messy compared to an 
explicitly defined equivalent.  But the point is that there is 
something there that looks so much like static types that it can be 
identified and formalized.

 Undoubtedly, some programmers sometimes perform reasoning about their 
 programs which could also be performed by a static type system.  

I think that's a severe understatement.  Programmers always reason about 
things like the types of arguments, the types of variables, the return 
types of functions, and the types of expressions.  They may not do 
whole-program inference and proof in the way that a static type system 
does, but they do it locally, all the time, every time.

BTW, I notice you didn't answer any of the significant questions which I 
posed to Vesa.  So let me pose one directly to you: how should I rewrite 
the first sentence in the preceding paragraph 

Re: OverflowError: math range error...

2006-06-23 Thread Sheldon
Thanks for the tips!
I am going to look into this some more.

/Sheldon

Simon Forman skrev:

 Sheldon wrote:
  Hi,
 
  I have a written a script that will check to see if the divisor is zero
  before executing but python will not allow this:
 
  if statistic_array[0:4]  0.0:
  statistic_array[0,0:4] =
  int(multiply(divide(statistic_array[0,0:4],statistic_array \
  [0,4]),1.0))/100.0
 
  Does anyone know why Python is complaining:
 
  statistic_array[0,0:4] =
  int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),1.0))/100.0
 
  OverflowError: math range error
 
  and how do I get around this problem? This stupid because there is a if
  statement preventing this dividing by zero.
 
  Sincerely,
  Sheldon

 I don't know what special math modules you're using, but python usually
 raises ZeroDivisionError for divide-by-zero problems.

 Try printing the intermediate values of each step in your problem code.

 d = divide(statistic_array[0,0:4], statistic_array[0,4])
 print d

 m = multiply(d, 1.0)
 print m

 i = int(m)
 print i

 statistic_array[0,0:4] = i
 
 
 That might help you track down what's wrong.

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

Re: OverflowError: math range error...

2006-06-23 Thread Sheldon
Thanks for the tips!
I am going to look into this some more. I am not used to using Numeric
and the logical functions. I didn't think about what you pointed out
and somewhere the returned values from these logical methods are not
what I expect.  I will rewrite the whole thing using alltrue instead.

/Sheldon

Robert Kern skrev:

 Sheldon wrote:
  Hi,
 
  I have a written a script that will check to see if the divisor is zero
  before executing but python will not allow this:
 
  if statistic_array[0:4]  0.0:
  statistic_array[0,0:4] =
  int(multiply(divide(statistic_array[0,0:4],statistic_array \
  [0,4]),1.0))/100.0
 
  Does anyone know why Python is complaining:
 
  statistic_array[0,0:4] =
  int(multiply(divide(statistic_array[0,0:4],statistic_array[0,4]),1.0))/100.0
 
  OverflowError: math range error
 
  and how do I get around this problem? This stupid because there is a if
  statement preventing this dividing by zero.

 What kind of arrays are you using? If it's Numeric (and I think it is because
 numarray and numpy would throw an error at the if: statement), then your test 
 is
 incorrect.

 Comparisons yield arrays of boolean values. When a Numeric boolean array is 
 used
 as a truth value (like in an if: statement), then it will return True is *any*
 of the values are True. Use Numeric.alltrue(statistic_array[:4]  0.0) 
 instead.

 Both numarray and numpy throw an exception when one attempts to use arrays as
 truth values since the desired meaning (alltrue or sometrue) is ambiguous.

 --
 Robert Kern

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

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

Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Anton van Straaten
Marshall wrote:
The short answer is that I'm most directly referring to the types in
the programmer's head.
 
 
 In the database theory world, we speak of three levels: conceptual,
 logical, physical. In a dbms, these might roughly be compared to
 business entities described in a requirements doc, (or in the
 business owners' heads), the (logical) schema encoded in the
 dbms, and the b-tree indicies the dbms uses for performance.
 
 So when you say latent types, I think conceptual types.

That sounds plausible, but of course at some point we need to pick a 
term and attempt to define it.  What I'm attempting to do with latent 
types is to point out and emphasize their relationship to static types, 
which do have a very clear, formal definition.  Despite some people's 
skepticism, that definition gives us a lot of useful stuff that can be 
applied to what I'm calling latent types.

 The thing about this is, both the Lisp and the Haskell programmers
 are using conceptual types (as best I can tell.) 

Well, a big difference is that the Haskell programmers have language 
implementations that are clever enough to tell them, statically, a very 
precise type for every term in their program.  Lisp programmers usually 
don't have that luxury.  And in the Haskell case, the conceptual type 
and the static type match very closely.

There can be differences, e.g. a programmer might have knowledge about 
the input to the program or some programmed constraint that Haskell 
isn't capable of inferring, that allows them to figure out a more 
precise type than Haskell can.  (Whether that type can be expressed in 
Haskell's type system is a separate question.)

In that case, you could say that the conceptual type is different than 
the inferred static type.  But most of the time, the human is reasoning 
about pretty much the same types as the static types that Haskell 
infers.  Things would get a bit confusing otherwise.

 And also, the
 conceptual/latent types are not actually a property of the
 program; 

That's not exactly true in the Haskell case (or other languages with 
static type inference), assuming you accept the static/conceptual 
equivalence I've drawn above.

Although static types are often not explicitly written in the program in 
such languages, they are unambiguously defined and automatically 
inferrable.  They are a static property of the program, even if in many 
cases those properties are only implicit with respect to the source 
code.  You can ask the language to tell you what the type of any given 
term is.

 they are a property of the programmer's mental
 model of the program.

That's more accurate.  In languages with type inference, the programmer 
still has to figure out what the implicit types are (or ask the language 
to tell her).

You won't get any argument from me that this figuring out of implicit 
types in a Haskell program is quite similar to what a Lisp, Scheme, or 
Python programmer does.  That's one of the places the connection between 
static types and what I call latent types is the strongest.

(However, I think I just heard a sound as though a million type 
theorists howled in unison.[*])

[*] most obscure inadvertent pun ever.

 It seems we have languages:
 with or without static analysis
 with or without runtime type information (RTTI or tags)
 with or without (runtime) safety
 with or without explicit type annotations
 with or without type inference
 
 Wow. And I don't think that's a complete list, either.

Yup.

 I would be happy to abandon strong/weak as terminology
 because I can't pin those terms down. (It's not clear what
 they would add anyway.)

I wasn't following the discussion earlier, but I agree that strong/weak 
don't have strong and unambiguous definitions.

 Uh, oh, a new term, manifest. Should I worry about that?

Well, people have used the term manifest type to refer to a type 
that's explicitly apparent in the source, but I wouldn't worry about it. 
  I just used the term to imply that at some point, the idea of latent 
type has to be converted to something less latent.  Once you explicitly 
identify a type, it's no longer latent to the entity doing the identifying.

But if we ask Javascript what it thinks the type of timestwo is, by
evaluating typeof timestwo, it returns function.  That's because the
value bound to timestwo has a tag associated with it which says, in
effect, this value is a function.
 
 
 Well, darn. It strikes me that that's just a decision the language
 designers
 made, *not* to record complete RTTI. 

No, there's more to it.  There's no way for a dynamically-typed language 
to figure out that something like the timestwo function I gave has the 
type number - number without doing type inference, by examining the 
source of the function, at which point it pretty much crosses the line 
into being statically typed.

 (Is it going to be claimed that
 there is an *advantage* to having only incomplete RTTI? It is a
 serious question.)

More than an 

Re: Help req: Problems with MySQLdb

2006-06-23 Thread [EMAIL PROTECTED]
for x in range(self.MAX_CRAWL_THREADS+1):
self.con.append(
[MySQLdb.connect(host,username,passwor,database,PORT),0])

PORT is an extra argument you might not have perhaps
rodmc wrote:
 I have written an application that connects to a database on a remote
 machine which uses MySQLdb 1.2.0. The application works perfectly when
 connecting to the database from a remote machine, however when it
 attempts to connect to a database on the same machine a connection
 error is generated. I have attached what little info I can below.

 DBSERVERIP = 1.2.3.4
 db = MySQLdb.connect(host=DBSERVERIP, user=user, passwd=password,
 db=nuke)
 --- it refuses to connect on the above line and the exception is caught
 and a message displayed.

 I have tried changing the server IP to localhost or the hostname,
 however the same problem arises.

 Information: Python 2.3.5, MySQLdb 1.2.0, MySQL 5.0.21 and Windows 2K
 pro.

 I would be grateful for any help with this problem.

 Kind regards,

 rod

Also not catching exceptions is a bad idea (crash thud) for long term
programs short term testing its possible it could be good.

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


Re: map() return of flat tuple list

2006-06-23 Thread Mirco Wahab
Thus spoke [EMAIL PROTECTED] (on 2006-06-23 00:57):

 Maybe you want something like this (but this doesn't use map):
 [(r,c) for r, row in enumerate(m) for c in xrange(len(row))]

Ahh, its a 'list comprehension', nice.  Now,
lets see how the decorate/undecorate sort
turns out to look in Python:

arr = [
   [3,3,3,3],
   [3,3,3,1],
   [3,3,3,3] ]


print \
   sorted(
  [ (j,i) for j, row in enumerate(arr) for i in xrange(len(row)) ],
  lambda a,b: (arr[a[0]][a[1]] - arr[b[0]][b[1]])
   )[ 0 ]


== prints indices: (1,3)

He, this looks more like Haskell than like
Python (for me, it looks awful ;-)

I'll try to come up with at least one
map inside the comprehension, if that
works - just to avoid the dual for ;-)

Reagrds and thanks

Mirco

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


reaching to the notification area

2006-06-23 Thread Bayazee
Hi
i want to make an icon in the notification area by python .
how can I make a notification area button likewise windows system tray
and show custem menu on right click or ...
(i want to use pyqt ...)
ThanX

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


Re: Using SQLite3 with python 2.5 beta

2006-06-23 Thread Fredrik Lundh
Harold Shore wrote:

 I do have SQLite3 installed on my system, but after doing a 
 plain vanilla compilation of the the 2.5 beta and trying 
 the SQLite code given in the release notes I get the message 
 NameError: name 'sqlite3' is not defined.
 
 I wonder what the requirement means that when the necessary 
 headers are available?  How would they need to be made 
 available?

if you're installing from RPM:s (or similar), look for -dev or -devel 
packages.

most package providers distinguish between runtime files (required to 
run a prebuilt program that's been linked against a specific library) 
and development files (required to actually build such a program).

/F

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


Re: code is data

2006-06-23 Thread Fredrik Lundh
Ravi Teja wrote:

 You blogged on Django. Let's use that. Don't you think model creation
 in Django can be represented better, given that it is done often
 enough?

nope, because 1) it's not done very often, and 2) the existing syntax is 
  already very minimal, and defined in terms of a language that I 
already understand.

there might be cognitive theories that argue that the length of the 
symbols used to describe something is more important than the symbols 
you use, and how they can be chunked by the brain, but sturgeon's law 
applies to cognitive scientists too ;-)

 Since you are on thread and are a prominent and involved member of the
 Python community, I would like it if you (or any such other) can
 provide feedback on the rest of my previous post rather than be
 dismissive by just a small portion of it. Perhaps, that will give me
 some insight how these language design decisions are rationally made (I
 am not strictly a programmer by profession, much less a language
 designer).

see Ian's posts for some excellent discussion.

/F

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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Rob Thorpe
David Hopwood wrote:
 Rob Thorpe wrote:
  David Hopwood wrote:
 
 As far as I can tell, the people who advocate using typed and untyped
 in this way are people who just want to be able to discuss all languages in
 a unified terminological framework, and many of them are specifically not
 advocates of statically typed languages.
 
  Its easy to create a reasonable framework. My earlier posts show simple
  ways of looking at it that could be further refined, I'm sure there are
  others who have already done this.
 
  The real objection to this was that latently/dynamically typed
  languages have a place in it.

 You seem to very keen to attribute motives to people that are not apparent
 from what they have said.

The term dynamically typed is well used and understood.  The term
untyped is generally associated with languages that as you put it have
no memory safety, it is a pejorative term.  Latently typed is not
well used unfortunately, but more descriptive.

Most of the arguments above describe a static type system then follow
by saying that this is what type system should mean, and finishing by
saying everything else should be considered untyped. This seems to me
to be an effort to associate dynamically typed languages with this
perjorative term.

  But some of the advocates of statically
  typed languages wish to lump these languages together with assembly
  language a untyped in an attempt to label them as unsafe.

 A common term for languages which have defined behaviour at run-time is
 memory safe. For example, Smalltalk is untyped and memory safe.
 That's not too objectionable, is it?

Memory safety isn't the whole point, it's only half of it.  Typing
itself is the point. Regardless of memory safety if you do a
calculation in a latently typed langauge, you can find the type of the
resulting object.

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


Re: map() return of flat tuple list

2006-06-23 Thread bearophileHUGS
Mirco:
He, this looks more like Haskell than like Python (for me, it looks awful ;-)

Maybe this is more readable:

ar = [[3,3,3,3],
  [3,3,3,1],
  [3,3,4,3]]

print sorted( [(r,c) for r,row in enumerate(ar) for c in
xrange(len(row))],
  key=lambda (r,c): ar[r][c]
)[0]

I don't know if operator.itemgetter can be used here, I think it's too
much complex.

With python 2.5 you can probably simplify it a little (and speed it up)
with something like:

print min( [ (r,c) for r,row in enumerate(ar) for c in xrange(len(row))
],
   key=lambda (r,c): arr[r][c]
 )

Bye,
bearophile

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


Is there any good methods to read a encrypted password file?

2006-06-23 Thread [EMAIL PROTECTED]
Is there any good methods to read a encrypted password file?

hi, all:
   I've a zipped file with a password .
  currently i use it by this method:
   $ unzip -p secret.zip | python my-pexpect.py

  but i want to remove the unzip -p secret.zip process.
  that is :
  $ python my-pexpect.py   [whe python prgram will ask for a password
for secret.zip]

  how can i do this?

  thanks.

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


Re: String negative indices?

2006-06-23 Thread Filip Wasilewski
[EMAIL PROTECTED] wrote:

 Logically, I should be able to enter x[-2:-0] to get the last and next to 
 last characters. However, since Python doesn't distinguish between positive 
 and negative zero, this doesn't work. Instead, I have to enter x[-2:].

Hooray! Logically there is no such thing as positive or negative zero,
or did I miss something in the primary?

PS. x[len(x)-2 : len(x)-0]

cheers,
fw

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


Re: Help req: Problems with MySQLdb

2006-06-23 Thread Bruno Desthuilliers
Simon Forman wrote:
 rodmc wrote:
 
Hi,

Thanks for your email. Well I am kind of new to exceptions in Python,
but here is the code used below, as you can see it is somewhat basic.
Is there a way to display more information about the exception?

Best,

rod

 
 
 Use the traceback module (See
 http://docs.python.org/lib/module-traceback.html for info on it.)
 
 import traceback
 
 try:
 db = MySQLdb.connect(host=DBSERVERIP, user=user,
 passwd=password, db=nuke)
 except:
 print A database connection error has occurred

How can you assert it is a database connection error ?

 traceback.print_exc()
 return False
 else:
 pass
 
 #The rest of the program

You get the same result - with a more accurate error message - by not
handling the exception at all.

 
 It's generally very difficult to figure out what's going wrong without
 the traceback in front of you.

indeed.


 Also, try an empty string (i.e. ) as your hostname, it's shorthand
 for 'localhost'.
 
 
 Hope this helps,
 ~Simon
 


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Hi
 
 I'd like to use metaclasses to dynamically generate a class based on a
 parameter to the objects init function.

Do you really need a metaclass for this ?

 For example:
 
 class MetaThing(type):
 def __init__(cls, name, bases, dict, extra_information):
 super(MetaThing, cls).__init__(name, bases, dict)
 #setup the class based on the parameter extra_information
 
 class Thing:
 __metaclass__ = MetaThing
 def __init__(self, extra_information):
  #Somehow pass extra_information to the MetaThing
 
 extra_information = 1
 t = Thing(extra_information)

Why would you want a new *class* here ?

 The above sample won't work but I hope it demonstrates what I'm trying
 to do.

Not enough, I'm afraid - unless it's just me being dumb. From what I see
here, you just can add the extra informations on the object in the
initializer. What's your *real* use case ?




-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Andreas Rossberg
Marshall wrote:
 
 What we generally (in programming) call variables are locals
 and globals. If the languages supports an update operation
 on those variables, then calling them variables makes sense.
 But variable has become such a catch-all term that we call
 
   public static final int FOO = 7;
 
 a variable, even though it can never, ever vary.
 
 That doesn't make any sense.

It does, because it is only a degenerate case. In general, you can have 
something like

   void f(int x)
   {
  const int foo = x+1;
  //...
   }

Now, foo is still immutable, it is a local, but it clearly also varies.

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


Saying latently-typed language is making a category mistake

2006-06-23 Thread Vesa Karvonen
In comp.lang.functional Anton van Straaten [EMAIL PROTECTED] wrote:
[...]
 I reject this comparison.  There's much more to it than that.  The point 
 is that the reasoning which programmers perform when working with an 
 program in a latently-typed language bears many close similiarities to 
 the purpose and behavior of type systems.

 This isn't an attempt to jump on any bandwagons, it's an attempt to 
 characterize what is actually happening in real programs and with real 
 programmers.  I'm relating that activity to type systems because that is 
 what it most closely relates to.
[...]

I think that we're finally getting to the bottom of things.  While reading
your reponses something became very clear to me: latent-typing and latent-
types are not a property of languages.  Latent-typing, also known as
informal reasoning, is something that all programmers do as a normal part
of programming.  To say that a language is latently-typed is to make a
category mistake, because latent-typing is not a property of languages.

A programmer, working in any language, whether typed or not, performs
informal reasoning.  I think that is fair to say that there is a
correspondence between type theory and such informal reasoning.  The
correspondence is like the correspondence between informal and formal
math.  *But* , informal reasoning (latent-typing) is not a property of
languages.

An example of a form of informal reasoning that (practically) every
programmer does daily is termination analysis.  There are type systems
that guarantee termination, but I think that is fair to say that it is not
yet understood how to make a practical general purpose language, whose
type system would guarantee termination (or at least I'm not aware of such
a language).  It should also be clear that termination analysis need not
be done informally.  Given a program, it may be possible to formally prove
that it terminates.

I'm now more convinced than ever that (latently|dynamically)-typed
language is an oxymoron.  The terminology really needs to be fixed.

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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread rossberg
Anton van Straaten wrote:

 Languages with latent type systems typically don't include type
 declarations in the source code of programs.  The static type scheme
 of a given program in such a language is thus latent, in the English
 dictionary sense of the word, of something that is present but
 undeveloped.  Terms in the program may be considered as having static
 types, and it is possible to infer those types, but it isn't necessarily
 easy to do so automatically, and there are usually many possible static
 type schemes that can be assigned to a given program.

 Programmers infer and reason about these latent types while they're
 writing or reading programs.  Latent types become manifest when a
 programmer reasons about them, or documents them e.g. in comments.

I very much agree with the observation that every programmer performs
latent typing in his head (although Pascal Constanza's seems to have
the opposite opinion).

But I also think that latently typed language is not a meaningful
characterisation. And for the very same reason! Since any programming
activity involves latent typing - naturally, even in assembler! - it
cannot be attributed to any language in particular, and is hence
useless to distinguish between them. (Even untyped lambda calculus
would not be a counter-example. If you really were to program in it,
you certainly would think along lines like this function takes two
chuch numerals and produces a third one.)

I hear you when you define latently typed languages as those that
support the programmer's latently typed thinking by providing dynamic
tag checks. But in the very same post (and others) you also explain in
length why these tags are far from being actual types. This seems a bit
contradictory to me.

As Chris Smith points out, these dynamic checks are basically a
necessaity for a well-defined operational semantics. You need them
whenever you have different syntactic classes of values, but lack a
type system to preclude interference. They are just an encoding for
differentiating these syntactic classes. Their connection to types is
rather coincidential.

- Andreas

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


Re: Program slowing down with greater memory use

2006-06-23 Thread Rene Pijlman
Dan Stromberg:
What's the deal here? 

The sketchy information in your post doesn't rule out any possibility.

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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Andreas Rossberg
David Hopwood wrote:

Values refers to the concrete values existent in the semantics of a
programming language. This set is usually infinite, but basically fixed.
To describe the set of values of an abstract type you would need
fresh values that did not exist before (otherwise the abstract type
would be equivalent to some already existent type). So you'd need at
least a theory for name generation or something similar to describe
abstract types in a types-as-sets metaphor.
 
 Set theory has no difficulty with this. It's common, for example, to see
 the set of strings representing propositions used in treatments of
 formal systems.

Oh, I was not saying that this particular aspect cannot be described in 
set theory (that was a different argument, about different issues). Just 
that you cannot naively equate types with a set of underlying values, 
which is what is usually meant by the types-are-sets metaphor - to 
capture something like type abstraction you need to do more. (Even then 
it might be arguable if it really describes the same thing.)

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


Unicode problem with exec

2006-06-23 Thread Thomas Heller
I'm using code.Interactive console but it doesn't work correctly
with non-ascii characters.  I think it boils down to this problem:

Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32
Type help, copyright, credits or license for more information.
 print uä
ä
 exec 'print uä'
Traceback (most recent call last):
  File stdin, line 1, in ?
  File string, line 1, in ?
  File c:\python24\lib\encodings\cp850.py, line 18, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in position 
0: character maps to undefined
 ^Z

Why does the exec call fail, and is there a workaround?

Thanks,
Thomas

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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Patricia Shanahan
Vesa Karvonen wrote:
...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware of such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to formally prove
 that it terminates.

To make the halting problem decidable one would have to do one of two
things: Depend on memory size limits, or have a language that really is
less expressive, at a very deep level, than any of the languages
mentioned in the newsgroups header for this message.

A language for which the halting problem is decidable must also be a
language in which it is impossible to simulate an arbitrary Turing
machine (TM). Otherwise, one could decide the notoriously undecidable TM
halting problem by generating a language X program that simulates the TM
and deciding whether the language X program halts.

One way out might be to depend on the boundedness of physical memory. A
language with a fixed maximum memory size cannot simulate an arbitrary
TM. However, the number of states for a program is so great that a
method that depends on its finiteness, but would not work for an
infinite memory model, is unlikely to be practical.

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


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread sashang

Bruno Desthuilliers wrote:
 [EMAIL PROTECTED] wrote:
  Hi
 
  I'd like to use metaclasses to dynamically generate a class based on a
  parameter to the objects init function.

 Do you really need a metaclass for this ?

  For example:
 
  class MetaThing(type):
  def __init__(cls, name, bases, dict, extra_information):
  super(MetaThing, cls).__init__(name, bases, dict)
  #setup the class based on the parameter extra_information
 
  class Thing:
  __metaclass__ = MetaThing
  def __init__(self, extra_information):
   #Somehow pass extra_information to the MetaThing
 
  extra_information = 1
  t = Thing(extra_information)

 Why would you want a new *class* here ?

  The above sample won't work but I hope it demonstrates what I'm trying
  to do.

 Not enough, I'm afraid - unless it's just me being dumb. From what I see
 here, you just can add the extra informations on the object in the
 initializer. What's your *real* use case ?



The extra_information is used in MetaThing to tell it what attributes
to add to the class. For example:

class MetaThing(type):
 def __init__(cls, name, bases, dict, extra_information):
 super(MetaThing, cls).__init__(name, bases, dict)
 #setup the class based on the parameter extra_information
 setattr(cls, make_name(extra_information),
make_object(extra_information))

Does that clarify things? I might have the wrong approach - I'm new to
metaclasses. However I do think the solution to my problem lies with
them since I have to dynamically generate a class and metaclasses
provide a mechanism for doing this.

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


* in Python

2006-06-23 Thread placid
Hi all,

Can someone tell me what * in the following code means/does a Google
search didnt turn up anything as i dont know what the * is called
(related to Python and i dont think Python has pointers)

def test(*args):
 pass

and sometimes its;

def test(**args):
 pass


Cheers

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


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Michele Simionato
[EMAIL PROTECTED] wrote:
 However I do think the solution to my problem lies with
 them since I have to dynamically generate a class and metaclasses
 provide a mechanism for doing this.

You rarely need a custom metaclass to generate classes. A class factory

def makeclass(classname, *attributes):
   cls = type(classname, mybases, mydic)
   for name, value in attributes:
  setattr(cls, name, attr)
   return cls

is the typical solution for your use case.

OTOH, if you are looking for use classes for metaclasses, look at the
Python Wiki
and use Google. 

   Michele Simionato

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


Re: What is a type error?

2006-06-23 Thread Pascal Costanza
Matthias Blume wrote:
 Pascal Costanza [EMAIL PROTECTED] writes:
 
 Chris Smith wrote:

 While this effort to salvage the term type error in dynamic
 languages is interesting, I fear it will fail.  Either we'll all
 have to admit that type in the dynamic sense is a psychological
 concept with no precise technical definition (as was at least hinted
 by Anton's post earlier, whether intentionally or not) or someone is
 going to have to propose a technical meaning that makes sense,
 independently of what is meant by type in a static system.
 What about this: You get a type error when the program attempts to
 invoke an operation on values that are not appropriate for this
 operation.

 Examples: adding numbers to strings; determining the string-length of
 a number; applying a function on the wrong number of parameters;
 applying a non-function; accessing an array with out-of-bound indexes;
 etc.
 
 Yes, the phrase runtime type error is actually a misnomer.  What one
 usually means by that is a situation where the operational semantics
 is stuck, i.e., where the program, while not yet arrived at what's
 considered a result, cannot make any progress because the current
 configuration does not match any of the rules of the dynamic
 semantics.
 
 The reason why we call this a type error is that such situations are
 precisely the ones we want to statically rule out using sound static
 type systems.  So it is a type error in the sense that the static
 semantics was not strong enough to rule it out.
 
 Sending a message to an object that does not understand that message
 is a type error. The message not understood machinery can be seen
 either as a way to escape from this type error in case it occurs and
 allow the program to still do something useful, or to actually remove
 (some) potential type errors.
 
 I disagree with this.  If the program keeps running in a defined way,
 then it is not what I would call a type error.  It definitely is not
 an error in the sense I described above.

If your view of a running program is that it is a closed system, then 
you're right. However, maybe there are several layers involved, so what 
appears to be a well-defined behavior from the outside may still be 
regarded as a type error internally.

A very obvious example of this is when you run a program in a debugger. 
There are two levels involved here: the program signals a type error, 
but that doesn't mean that the system as a whole is stuck. Instead, the 
debugger takes over and offers ways to deal with the type error. The 
very same program run without debugging support would indeed simply be 
stuck in the same situation.

So to rephrase: It depends on whether you use the message not 
understood machinery as a way to provide well-defined behavior for the 
base level, or rather as a means to deal with an otherwise unanticipated 
situation. In the former case it extends the language to remove certain 
type errors, in the latter case it provides a kind of debugging facility 
(and it indeed may be a good idea to deploy programs with debugging 
facilities, and not only use debugging tools at development time).

This is actually related to the notion of reflection, as coined by Brian 
C. Smith. In a reflective architecture, you distinguish between various 
interpreters, each of which interprets the program at the next level. A 
debugger is a program that runs at a different level than a base program 
that it debugs. However, the reflective system as a whole is just a 
single program seen from the outside (with one interpreter that runs the 
whole reflective tower). This distinction between the internal and the 
external view of a reflective system was already made by Brian Smith.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is a type error?

2006-06-23 Thread Pascal Costanza
Chris Smith wrote:
 Pascal Costanza [EMAIL PROTECTED] wrote:
 What about this: You get a type error when the program attempts to 
 invoke an operation on values that are not appropriate for this operation.

 Examples: adding numbers to strings; determining the string-length of a 
 number; applying a function on the wrong number of parameters; applying 
 a non-function; accessing an array with out-of-bound indexes; etc.
 
 Hmm.  I'm afraid I'm going to be picky here.  I think you need to 
 clarify what is meant by appropriate.

No, I cannot be a lot clearer here. What operations are appropriate for 
what values largely depends on the intentions of a programmer. Adding a 
number to a string is inappropriate, no matter how a program behaves 
when this actually occurs (whether it continues to execute the operation 
blindly, throws a continuable exception, or just gets stuck).

 If you mean the operation will 
 not complete successfully as I suspect you do, then we're closer...

No, we're not. You're giving a purely technical definition here, that 
may or may not relate to the programmer's (or designer's) 
understanding of the domain.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-23 Thread Fredrik Lundh
placid wrote:

 Can someone tell me what * in the following code means/does a Google
 search didnt turn up anything as i dont know what the * is called

see sections 4.7.2 and 4.7.3 in the tutorial:

 http://docs.python.org/tut/node6.html#SECTION00674

for more details, see the description of the def statement in the 
language reference.

/F

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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Pascal Costanza
Marshall wrote:

 I am sceptical of the idea that when programming in a dynamically
 typed language one doesn't have to think about both models as well.
 I don't have a good model of the mental process of working
 in a dynamically typed language, but how could that be the case?
 (I'm not asking rhetorically.) Do you then run your program over
 and over, mechanically correcting the code each time you discover
 a type error? In other words, if you're not thinking of the type model,
 are you using the runtime behavior of the program as an assistant,
 the way I use the static analysis of the program as an assistant?

Yes.

 I don't accept the idea about pairing the appropriateness of each
 system according to whether one is doing exploratory programming.
 I do exploratory programming all the time, and I use the static type
 system as an aide in doing so. Rather I think this is just another
 manifestation of the differences in the mental processes between
 static typed programmers and dynamic type programmers, which
 we are beginning to glimpse but which is still mostly unknown.

Probably.

 Oh, and I also want to say that of all the cross-posted mega threads
 on static vs. dynamic typing, this is the best one ever. Most info;
 least flames. Yay us!

Yay! :)


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Pascal Costanza
Marshall wrote:
 Pascal Costanza wrote:
 Consider a simple expression like 'a + b': In a dynamically typed
 language, all I need to have in mind is that the program will attempt to
 add two numbers. In a statically typed language, I additionally need to
 know that there must a guarantee that a and b will always hold numbers.
 
 I still don't really see the difference.
 
 I would not expect that the dynamic programmer will be
 thinking that this code will have two numbers most of the
 time but sometimes not, and fail. I would expect that in both
 static and dynamic, the thought is that that code is adding
 two numbers, with the difference being the static context
 gives one a proof that this is so.

There is a third option: it may be that at the point where I am writing 
this code, I simply don't bother yet whether a and b will always be 
numbers. In case something other than numbers pop up, I can then make a 
decision how to proceed from there.

 In this simple example,
 the static case is better, but this is not free, and the cost
 of the static case is evident elsewhere, but maybe not
 illuminated by this example.

Yes, maybe the example is not the best one. This kind of example, 
however, occurs quite often when programming in an object-oriented 
style, where you don't know yet what objects will and will not respond 
to a message / generic function. Even in the example above, it could be 
that you can give an appropriate definition for + for objects other than 
numbers.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-23 Thread Duncan Booth
placid wrote:

 Hi all,
 
 Can someone tell me what * in the following code means/does a Google
 search didnt turn up anything as i dont know what the * is called
 (related to Python and i dont think Python has pointers)
 
* is for variable number of positional arguments, ** is for variable 
keyword arguments. The syntax is symmetrical when defining functions and 
when calling them.

See http://docs.python.org/ref/calls.html
and http://docs.python.org/ref/function.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Piet van Oostrum
 Marshall [EMAIL PROTECTED] (M) wrote:

M Torben Ægidius Mogensen wrote:
 
 That's not true.  ML has variables in the mathematical sense of
 variables -- symbols that can be associated with different values at
 different times.  What it doesn't have is mutable variables (though it
 can get the effect of those by having variables be immutable
 references to mutable memory locations).

M While we're on the topic of terminology, here's a pet peeve of
M mine: immutable variable.

M immutable = can't change
M vary-able = can change

M Clearly a contradiction in terms.

I would say that immutable = 'can't *be* changed' rather than 'can't
change'. But I am not a native English speaker.

Compare with this: the distance of the Earth to Mars is variable (it
varies), but it is also immutable (we can't change it).
-- 
Piet van Oostrum [EMAIL PROTECTED]
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Anton van Straaten
Vesa Karvonen wrote:
 I think that we're finally getting to the bottom of things.  While reading
 your reponses something became very clear to me: latent-typing and latent-
 types are not a property of languages.  Latent-typing, also known as
 informal reasoning, is something that all programmers do as a normal part
 of programming.  To say that a language is latently-typed is to make a
 category mistake, because latent-typing is not a property of languages.
 
 A programmer, working in any language, whether typed or not, performs
 informal reasoning.  I think that is fair to say that there is a
 correspondence between type theory and such informal reasoning.  The
 correspondence is like the correspondence between informal and formal
 math.  *But* , informal reasoning (latent-typing) is not a property of
 languages.

Well, it's obviously the case that latent types as I've described them 
are not part of the usual semantics of dynamically typed languages.  In 
other messages, I've mentioned types like number - number which have 
no meaning in a dynamically typed language.  You can only write them in 
comments (unless you implement some kind of type handling system), and 
language implementations aren't aware of such types.

OTOH, a programmer reasoning explicitly about such types, writing them 
in comments, and perhaps using assertions to check them has, in a sense, 
 defined a language.  Having done that, and reasoned about the types 
in his program, he manually erases them, leaving code written in the 
original dynamically-typed language.  You can think of it as though it 
were generated code, complete with comments describing types, injected 
during the erasure process.

So, to address your category error objection, I would say that latent 
typing is a property of latently-typed languages, which are typically 
informally-defined supersets of what we know as dynamically-typed languages.

I bet that doesn't make you happy, though.  :D

Still, if that sounds a bit far-fetched, let me start again at ground 
level, with a Haskell vs. Scheme example:

   let double x = x * 2

vs.:

   (define (double x) (* x 2))

Programmers in both languages do informal reasoning to figure out the 
type of 'double'.  I'm assuming that the average Haskell programmer 
doesn't write out a proof whenever he wants to know the type of a term, 
and doesn't have a compiler handy.

But the Haskell programmer's informal reasoning takes place in the 
context of a well-defined formal type system.  He knows what the type 
of double means: the language defines that for him.

The type-aware Scheme programmer doesn't have that luxury: before he can 
talk about types, he has to invent a type system, something to give 
meaning to an expression such as number - number.  Performing that 
invention gives him types -- albeit informal types, a.k.a. latent types.

In the Haskell case, the types are a property of the language.  If 
you're willing to acknowledge the existence of something like latent 
types, what are they a property of?  Just the amorphous informal cloud 
which surrounds dynamically-typed languages?  Is that a satisfactory 
explanation of these two quite similar examples?

I want to mention two other senses in which latent types become 
connected to real languages.  That doesn't make them properties of the 
formal semantics of the language, but the connection is a real one at a 
different level.

The first is that in a language without a rich formal type system, 
informal reasoning outside of the formal type system becomes much more 
important.  Conversely, in Haskell, even if you accept the existence of 
latent types, they're close enough to static types that it's hardly 
necessary to consider them.  This is why latent types are primarily 
associated with languages without rich formal type systems.

The second connection is via tags: these are part of the definition of a 
dynamically-typed language, and if the programmer is reasoning 
explicitly about latent types, tags are a useful tool to help ensure 
that assumptions about types aren't violated.  So this is a connection 
between a feature in the semantics of the language, and these 
extra-linguistic latent types.

 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware of such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to formally prove
 that it terminates.

Right.  And this is partly why talking about latent types, as opposed to 
the more general informal reasoning, makes sense: because latent types 
are addressing the same kinds of things that static types can capture. 
Type-like things.

 

windows and socket.dup

2006-06-23 Thread gangesmaster
what uses do you have to socket.dup? on *nixes it makes,
to dup() the socket before forking, but how can that be useful
on windows?



-tomer

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


Re: code is data

2006-06-23 Thread Anton Vredegoor
Paul Boddie wrote:

 Anton Vredegoor wrote:

 Yes, but also what some other posters mentioned, making Pythons internal
 parsing tree available to other programs (and to Python itself) by using
 a widely used standard like XML as its datatype.
 
 http://pysch.sourceforge.net/ast.html

Very interesting, it led me to some sxml describing pages and it also 
tricked me into reading some Python documentation that I had always 
considered to be hiding some arcane deep Python magic. I guess now that 
Python is officially entering tree territory (as opposed to providing 
third party functionality) it seems unavoidable that Python's officially 
endorsed tree datatype will also be used for some of its internal 
structures, thereby making it more accessible to programmers like me and 
to outside programmers.

 I was going to write a long reply to one of your previous messages, but
 the above link references a project which may intersect with some of
 your expectations. Meanwhile, it should be noted that the availability

Somehow I get the impression of getting away with my posts luckily, 
while you now are duping other interested readers into not reading your 
innermost feelings about this subject. Let's get it in the open, don't 
spare me :-)

 of Python AST processing tools is not a recent thing: the compiler
 module has been around for a long time, and it is possible to modify
 the AST and to generate bytecode from it; my own experiments have
 centred on producing other representations from the AST, and other more
 successful projects (eg. ShedSkin) produce other languages (eg. C++)
 from the AST.

Well maybe this trick of vehemently denying the existence of something 
on Usenet worked again, by materializing the thing as a reaction.

However, I knew of the existence of such languages but I am mostly 
interested in standardized code interchange, like for example with JSONP 
which fetches some external javascriptcode from another server using 
JSON and places the translated javascript into a webpage at the request 
of the clients browser or so it seems. Maybe a Python webserver could 
also emit pieces of javascript code by getting them from a *Python* code 
library after translating Python code on the fly?

That would open up the web to Python programmers without browsers 
needing to understand Python. Like Jython, but now as separately 
distributed functions from different servers.

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


Leo 4.4.1 beta 2 released

2006-06-23 Thread Edward K. Ream
Leo 4.4.1 beta 2 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.4.1:

- Multiple editors in Leo's body pane.
- Search commands now support regex replace patterns: \1, \2, etc.
- Support for external debuggers: see 
http://webpages.charter.net/edreamleo/debuggers.html
- The scripting plugin now creates a Debug Script button.
- New commands including run-unit-test, python-help and toggle-invisibles.

Links:
--
4.4.1:http://webpages.charter.net/edreamleo/new-4-4-1.html
4.4:  http://webpages.charter.net/edreamleo/new-4-4.html
Leo:  http://webpages.charter.net/edreamleo/front.html
Home: http://sourceforge.net/projects/leo/
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:  http://leo.tigris.org/source/browse/leo/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html


Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Pascal Costanza
Marshall wrote:
 Joe Marshall wrote:
 That's the important point:  I want to run broken code.
 
 I want to make sure I understand. I can think of several things
 you might mean by this. It could be:
 1) I want to run my program, even though I know parts of it
 are broken, because I think there are parts that are not broken
 and I want to try them out.
 2) I want to run my program, even though it is broken, and I
 want to run right up to a broken part and trap there, so I can
 use the runtime facilities of the language to inspect what's
 going on.
 
 
 I want to run
 as much of the working fragments as I can, and I want a `safety net' to
 prevent me from performing undefined operations, but I want the safety
 net to catch me at the *last* possible moment.
 
 This statement is interesting, because the conventional wisdom (at
 least as I'm used to hearing it) is that it is best to catch bugs
 at the *first* possible moment. But I think maybe we're talking
 about different continua here. The last last last possible moment
 is after the software has shipped to the customer, and I'm pretty
 sure that's not what you mean. I think maybe you mean something
 more like 2) above.

Nowadays, we have more options wrt what it means to ship code. It 
could be that your program simply runs as a (web) service to which you 
have access even after the customer has started to use the program. See 
http://www.paulgraham.com/road.html for a good essay on this idea.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Reuseable iterators - which is better?

2006-06-23 Thread zefciu
In the tutorial there is an example iterator class that revesrses the
string given to the constructor.  The problem is that this class works
only once, unlike built-in types like string.  How to modify it that it
could work several times?  I have tried two approaches.  They both work,
but which of them is stylistically better?

class Reverse: #original one
Iterator for looping over a sequence backwards
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #1st approach
Reuseable Iterator for looping over a sequence backwards
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
self.index = len(self.data) #Reset when previous
#
iterator goes out
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #2nd approach
Reuseable Iterator for looping over a sequence backwards
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = len(self.data) #Reset as a part of iterator
# creation
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bug in Makepy

2006-06-23 Thread Jim
 Always interpret it as hex, or always interpret it as decimal.

I see what you mean.  But I don't think I'll worry about it.

   -- Jim

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


Re: * in Python

2006-06-23 Thread placid

Duncan Booth wrote:
 placid wrote:

  Hi all,
 
  Can someone tell me what * in the following code means/does a Google
  search didnt turn up anything as i dont know what the * is called
  (related to Python and i dont think Python has pointers)
 
 * is for variable number of positional arguments, ** is for variable
 keyword arguments. The syntax is symmetrical when defining functions and
 when calling them.

 See http://docs.python.org/ref/calls.html
 and http://docs.python.org/ref/function.html

so * basically means that args is a list containing more arguments that
can change in size, whereas ** means that args is a dictionary of
key=value arguments?

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


Re: Status of optional static typing in Python?

2006-06-23 Thread John Roth
Christian Convey wrote:
 Hi guys,

 I'm looking at developing a somewhat complex system, and I think some
 static typing will help me keep limit my confusion.  I.e.:

 http://www.artima.com/weblogs/viewpost.jsp?thread=87182

 Does anyone know if/when that feature may become part of Python?

Optional static typing is listed as item # 3 in
PEP 3100 (Python 3.0 plans).
For a timeline, look at PEP 3000.

John Roth


 Thanks very much,
 Christian


 --
 Christian Convey
 Computer Scientist,
 Naval Undersea Warfare Centers
 Newport, RI
 (401) 832-6824
 [EMAIL PROTECTED]

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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Pascal Costanza
Vesa Karvonen wrote:
 In comp.lang.functional Anton van Straaten [EMAIL PROTECTED] wrote:
 [...]
 I reject this comparison.  There's much more to it than that.  The point 
 is that the reasoning which programmers perform when working with an 
 program in a latently-typed language bears many close similiarities to 
 the purpose and behavior of type systems.
 
 This isn't an attempt to jump on any bandwagons, it's an attempt to 
 characterize what is actually happening in real programs and with real 
 programmers.  I'm relating that activity to type systems because that is 
 what it most closely relates to.
 [...]
 
 I think that we're finally getting to the bottom of things.  While reading
 your reponses something became very clear to me: latent-typing and latent-
 types are not a property of languages.  Latent-typing, also known as
 informal reasoning, is something that all programmers do as a normal part
 of programming.  To say that a language is latently-typed is to make a
 category mistake, because latent-typing is not a property of languages.

I disagree with you and agree with Anton. Here, it is helpful to 
understand the history of Scheme a bit: parts of its design are a 
reaction to what Schemers perceived as having failed in Common Lisp (and 
other previous Lisp dialects).

One particularly illuminating example is the treatment of nil in Common 
Lisp. That value is a very strange beast in Common Lisp because it 
stands for several concepts at the same time: most importantly the empty 
list and the boolean false value. Its type is also interesting: it is 
both a list and a symbol at the same time. It is also interesting that 
its quoted value is equivalent to the value nil itself. This means that 
the following two forms are equivalent:

(if nil 42 4711)
(if 'nil 42 4711)

Both forms evaluate to 4711.

It's also the case that taking the car or cdr (first or rest) of nil 
doesn't give you an error, but simply returns nil as well.

The advantage of this design is that it allows you to express a lot of 
code in a very compact way. See 
http://www.apl.jhu.edu/~hall/lisp/Scheme-Ballad.text for a nice 
illustration.

The disadvantage is that it is mostly impossible to have a typed view of 
nil, at least one that clearly disambiguates all the cases. There are 
also other examples where Common Lisp conflates different types, and 
sometimes only for special cases. [1]

Now compare this with the Scheme specification, especially this section: 
http://www.schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-6.html#%25_sec_3.2

This clearly deviates strongly from Common Lisp (and other Lisp 
dialects). The emphasis here is on a clear separation of all the types 
specified in the Scheme standard, without any exception. This is exactly 
what makes it straightforward in Scheme to have a latently typed view of 
programs, in the sense that Anton describes. So latent typing is a 
property that can at least be enabled / supported by a programming 
language, so it is reasonable to talk about this as a property of some 
dynamically typed languages.



Pascal

[1] Yet Common Lisp allows you to write beautiful code, more often than 
not especially _because_ of these weird conflations, but that's a 
different topic.

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread George Sakkis
Dennis Lee Bieber wrote:
 On 22 Jun 2006 22:55:00 -0700, George Sakkis [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:


  Ok, I'll try once more: What does __setitem__ have to do with
  **iterability**, not mutability or indexability ? I was commenting on
  Maric's post that although some objects are typically iterable, they
  are often treated as atomic by some/many/most applications  (e.g.
  strings). It's not rocket science.
 
   And the absence of the setitem would indicate such an object -- it
 may be iterable in terms of retrieving subparts, but atomic WRT
 modification.

   That, at least, is how I interpreted the introduction of the test...

Applications that don't need to treat strings as iterables of
characters wouldn't do so even if strings were mutable. Atomicity has
to do with whether something is considered to be composite or not, not
whether it can be modified.

George

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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Pascal Costanza
Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it is 
 not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware of 
 such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to formally 
 prove
 that it terminates.
 
 To make the halting problem decidable one would have to do one of two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.

Not quite. See http://en.wikipedia.org/wiki/ACL2


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Chris Uppal
Andreas Rossberg wrote:
 Chris Uppal wrote:
 
It's worth noting, too, that (in some sense) the type of an object
can change over time[*].
  
   No. Since a type expresses invariants, this is precisely what may
   *not* happen. If certain properties of an object may change then the
   type of
   the object has to reflect that possibility. Otherwise you cannot
   legitimately call it a type.
 
  Well, it seems to me that you are /assuming/ a notion of what kinds of
  logic can be called type (theories), and I don't share your
  assumptions.  No offence intended.

 OK, but can you point me to any literature on type theory that makes a
 different assumption?

'Fraid not.  (I'm not a type theorist -- for all I know there may be lots, but
my suspicion is that they are rare at best.)

But perhaps I shouldn't have used the word theory at all.  What I mean is that
there is one or more logic of type (informal or not -- probably informal) with
respect to which the object in question has changed it categorisation.   If no
existing type /theory/ (as devised by type theorists) can handle that case,
then that is a deficiency in the set of existing theories -- we need newer and
better ones.

But, as a sort of half-way, semi-formal, example: consider the type environment
in a Java runtime.  The JVM does formal type-checking of classfiles as it loads
them.  In most ways that checking is static -- it's treating the bytecode as
program text and doing a static analysis on it before allowing it to run (and
rejecting what it can't prove to be acceptable by its criteria).  However, it
isn't /entirely/ static because the collection of classes varies at runtime in
a (potentially) highly dynamic way.  So it can't really examine the whole
text of the program -- indeed there is no such thing.  So it ends up with a
hybrid static/dynamic type system -- it records any assumptions it had to make
in order to find a proof of the acceptability of the new code, and if (sometime
in the future) another class is proposed which violates those assumptions, then
that second class is rejected.


  I see no reason,
  even in practise, why a static analysis should not be able to see that
  the set of acceptable operations (for some definition of acceptable)
  for some object/value/variable can be different at different times in
  the execution.

 Neither do I. But what is wrong with a mutable reference-to-union type,
 as I suggested? It expresses this perfectly well.

Maybe I misunderstood what you meant by union type.  I took it to mean that the
type analysis didn't know which of the two types was applicable, and so would
reject both (or maybe accept both ?).  E..g  if at instant A some object, obj,
was in a state where it to responds to #aMessage, but not #anotherMessage; and
at instant B it is in a state where it responds to #anotherMessage but not
#aMessage.  In my (internal and informal) type logic, make the following
judgements:

In code which will be executed at instant A
obj aMessage.type correct
obj anotherMessage.   type incorrect

In code which will be executed at instant B
obj aMessage. type incorrect
obj anotherMessage.type correct

I don't see how a logic with no temporal element can arrive at all four those
judgements, whatever it means by a union type.

-- chris


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


Re: What is a type error?

2006-06-23 Thread Chris Uppal
Eliot Miranda wrote:

[me:]
  Taking Smalltalk /specifically/, there is a definite sense in which it
  is typeless -- or trivially typed -- in that in that language there are
  no[*] operations which are forbidden[**],

 Come one Chris U.   One has to distinguish an attempt to invoke an
 operation with it being carried out.  There is nothing in Smalltalk to
 stop one attempting to invoke any operation on any object.  But one
 can only actually carry-out operations on objects that implement them.
 So, apart from the argument about inadvertent operation name overloading
 (which is important, but avoidable), Smalltalk is in fact
 strongly-typed, but not statically strongly-typed.

What are you doing /here/, Eliot, this is Javaland ?  Smalltalk is thatta
way -

 ;-)


But this discussion has been all about /whether/ it is ok to apply the notion
of (strong) typing to what runtime-checked languages do.   We all agree that
the checks happen, but the question is whether it is
reasonable/helpful/legitimate to extend the language of static checking to the
dynamic case.  (I'm on the side which says yes, but good points have been made
against it).

The paragraph you quoted doesn't represent most of what I have been saying -- 
it was just a side-note looking at one small aspect of the issue from a
different angle.

-- chris


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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Chris Uppal
Anton van Straaten wrote:

 In that case, you could say that the conceptual type is different than
 the inferred static type.  But most of the time, the human is reasoning
 about pretty much the same types as the static types that Haskell
 infers.  Things would get a bit confusing otherwise.

Or any mechanised or formalised type system, for any language.  If a system
doesn't match pretty closely with at least part of the latent type systems (in
your sense) used by the programmers, then that type system is useless.

(I gather that it took, or maybe is still taking, theorists a while to get to
grips with the infromal type logics which were obvious to working OO
programmers.)

-- chris


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


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Chris Uppal
David Hopwood wrote:

  But some of the advocates of statically
  typed languages wish to lump these languages together with assembly
  language a untyped in an attempt to label them as unsafe.

 A common term for languages which have defined behaviour at run-time is
 memory safe. For example, Smalltalk is untyped and memory safe.
 That's not too objectionable, is it?

I find it too weak, as if to say: well, ok, it can't actually corrupt memory
as such, but the program logic is still apt go all over the shop...

-- chris


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


Re: What is a type error?

2006-06-23 Thread Chris Uppal
Chris Smith wrote:

[me:]
  I think we're agreed (you and I anyway, if not everyone in this thread)
  that we don't want to talk of the type system for a given language.
  We want to allow a variety of verification logics.  So a static type
  system is a logic which can be implemented based purely on the program
  text without making assumptions about runtime events (or making
  maximally pessimistic assumptions -- which comes to the same thing
  really).  I suggest that a dynamic type system is a verification
  logic which (in principle) has available as input not only the program
  text, but also the entire history of the program execution up to the
  moment when the to-be-checked operation is invoked.

 I am trying to understand how the above statement about dynamic types
 actually says anything at all.  So a dynamic type system is a system of
 logic by which, given a program and a path of program execution up to
 this point, verifies something.  We still haven't defined something,
 though.

That was the point of my first sentence (quoted above).  I take it, and I
assumed that you shared my view, that there is no single the type system -- 
that /a/ type system will yield judgements on matters which it has been
designed to judge.  So unless we either nominate a specific type system or
choose what judgements we want to make (today) any discussion of types is
necessarily parameterised on the class(es) of Judgements.  So, I don't -- 
can't -- say /which/ judgements my dynamic type systems will make.  They may
be about nullablity, they may be about traditional type, they may be about
mutability...

When we look at a specific language (and its implementation), then we can
induce the logic(s) that whatever dynamic checks it applies define.
Alternatively we can consider other dynamic type systems which we would like
to formalise and mechanise, but which are not built into our language of
choice.


 We also haven't defined what happens if that verification
 fails.

True, and a good point.  But note that it only applies to systems which are
actually implemented in code (or which are intended to be so).

As a first thought, I suggest that a dynamic type system should specify a
replacement action (which includes, but is not limited to, terminating
execution).  That action is taken /instead/ of the rejected one.  E.g. we don't
actually read off the end of the array, but instead a signal is raised. (An
implementation might, in some cases, find it easier to implement the checks by
allowing the operation to fail, and then backtracking to pretend that it had
never happened, but that's irrelevant here).  The replacement action must -- of
course -- be valid according to the rules of the type system.

Incidentally, using that idea, we get a fairly close analogy to the difference
between strong and weak static type systems.  If the dynamic type system
doesn't specify a valid replacement action, or if that action is not guaranteed
to be taken, then it seems that the type system or the language implementation
is weak in very much the same sort of way as -- say -- the 'C' type system is
weak and/or weakly enforced.

I wonder whether that way of looking at it -- the error never happens since
it is replaced by a valid operation -- puts what I want to call dynamic type
systems onto a closer footing with static type systems.  Neither allows the
error to occur.

(Of course, /I/ -- the programmer -- have made a type error, but that's
different thing.)


 In other words, I think that everything so far is essentially just
 defining a dynamic type system as equivalent to a formal semantics for a
 programming language, in different words that connote some bias toward
 certain ways of looking at possibilities that are likely to lead to
 incorrect program behavior.  I doubt that will be an attractive
 definition to very many people.

My only objections to this are:

a) I /want/ to use the word type to describe the kind of reasoning I do (and
some of the mistakes I make)

b) I want to separate the systems of reasoning (whether formal or informal,
static or dynamic, implemented or merely conceptual, and /whatever/ we call 'em
;-) from the language semantics.  I have no objection to some type system
being used as part of a language specification, but I don't want to restrict
types to that.


  Note that not all errors that I would want to call type errors are
  necessarily caught by the runtime -- it might go happily ahead never
  realising that it had just allowed one of the constraints of one of the
  logics I use to reason about the program.  What's known as an
  undetected bug -- but just because the runtime doesn't see it, doesn't
  mean that I wouldn't say I'd made a type error.  (The same applies to
  any specific static type system too, of course.)

 In static type system terminology, this quite emphatically does NOT
 apply.  There may, of course, be undetected bugs, but they are not type
 errors.  If they were type errors, then 

Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Anton van Straaten
[EMAIL PROTECTED] wrote:
 I very much agree with the observation that every programmer performs
 latent typing in his head 

Great!

 (although Pascal Constanza's seems to have
 the opposite opinion).

I'll have to catch up on that.

 But I also think that latently typed language is not a meaningful
 characterisation. And for the very same reason! Since any programming
 activity involves latent typing - naturally, even in assembler! - it
 cannot be attributed to any language in particular, and is hence
 useless to distinguish between them. (Even untyped lambda calculus
 would not be a counter-example. If you really were to program in it,
 you certainly would think along lines like this function takes two
 chuch numerals and produces a third one.)

Vesa raised a similar objection in his post 'Saying latently typed 
language is making a category mistake'.  I've made some relevant 
responses to that post.

I agree that there's a valid point in the sense that latent types are 
not a property of the semantics of the languages they're associated with.

But to take your example, I've had the pleasure of programming a little 
in untyped lambda calculus.  I can tell you that not having tags is 
quite problematic.  You certainly do perform latent typing in your head, 
but without tags, the language doesn't provide any built-in support for 
it.  You're on your own.

I'd characterize this as being similar to other situations in which a 
language has explicit support for some programming style (e.g. FP or 
OO), vs. not having such support, so that you have to take steps to fake 
it.  The style may be possible to some degree in either case, but it's 
much easier if the language has explicit support for it. 
Dynamically-typed languages provide support for latent typing.  Untyped 
lambda calculus and assembler don't provide such support, built-in.

However, I certainly don't want to add to confusion about things like 
this.  I'm open to other ways to describe these things.  Part of where 
latently-typed language comes from is as an alternative to 
dynamically-typed language -- an alternative with connotations that 
I'm suggesting should be more compatible with type theory.

 I hear you when you define latently typed languages as those that
 support the programmer's latently typed thinking by providing dynamic
 tag checks. But in the very same post (and others) you also explain in
 length why these tags are far from being actual types. This seems a bit
 contradictory to me.

I don't see it as contradictory.  Tags are a mechanism.  An individual 
tag is not a type.  But together, tags help check types.  More below:

 As Chris Smith points out, these dynamic checks are basically a
 necessaity for a well-defined operational semantics. You need them
 whenever you have different syntactic classes of values, but lack a
 type system to preclude interference. They are just an encoding for
 differentiating these syntactic classes. Their connection to types is
 rather coincidential.

Oooh, I think I'd want to examine that coincidence very closely.  For 
example, *why* do we have different syntactic classes of values in the 
first place?  I'd say that we have them precisely to support type-like 
reasoning about programs, even in the absence of a formal static type 
system.

If you're going to talk about syntactic classes of values in the 
context of latent types, you need to consider how they relate to latent 
types.  Syntactic classes of values relate to latent types in a very 
similar way to that in which static types do.

One difference is that since latent types are not automatically 
statically checked, checks have to happen in some other way.  That's 
what checks of tags are for.

Chris Smith's observation was made in a kind of deliberate void: one in 
which the existence of anything like latent types is discounted, on the 
grounds that they're informal.  If you're willing to acknowledge the 
idea of latent types, then you can reinterpret the meaning of tags in 
the context of latent types.  In that context, tags are part of the 
mechanism which checks latent types.

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


Re: code is data

2006-06-23 Thread Max Erickson
Anton Vredegoor [EMAIL PROTECTED] wrote: 

 
 However, I knew of the existence of such languages but I am 
 mostly interested in standardized code interchange, like for 
 example with JSONP which fetches some external javascriptcode 
 from another server using JSON and places the translated 
 javascript into a webpage at the request of the clients browser 
 or so it seems. Maybe a Python webserver could also emit pieces 
 of javascript code by getting them from a *Python* code library 
 after translating Python code on the fly? 
 

 Anton 

I have no idea how close it is to what you are talking about, but pypy  
does have some sort of python-javascript support:

http://codespeak.net/pypy/dist/pypy/doc/getting-
started.html#translating-the-flow-graph-to-javascript-code

About two thirds down, if the above link is broken:

http://codespeak.net/pypy/dist/pypy/doc/getting-started.html


max

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


Re: code is data

2006-06-23 Thread Kay Schluehr

Anton Vredegoor wrote:
 Paul Boddie wrote:

  Anton Vredegoor wrote:

  Yes, but also what some other posters mentioned, making Pythons internal
  parsing tree available to other programs (and to Python itself) by using
  a widely used standard like XML as its datatype.
 
  http://pysch.sourceforge.net/ast.html

 Very interesting, it led me to some sxml describing pages and it also
 tricked me into reading some Python documentation that I had always
 considered to be hiding some arcane deep Python magic. I guess now that
 Python is officially entering tree territory (as opposed to providing
 third party functionality) it seems unavoidable that Python's officially
 endorsed tree datatype will also be used for some of its internal
 structures, thereby making it more accessible to programmers like me and
 to outside programmers.

I had the same initial impression with the deep aspects of Python
parser API but I learned soon that I just stumbled about an awkward
kind parse-tree representation. The structures are as simple as they
could be - due to the nice LL(1) Python grammar which are reflected.

I think node manipulation is just a first basic step for defining
source transformers i.e. they provide a sound basis. For usability
purposes a template language is a far better solution.

Here is my own attempt. Defining a repeat statement ( for demonstration
purposes ) using EasyExtend requires following translation:

repeat:
suite
until:
test

==

while 1:
   suite
   if test:
   break

The placeholders suite and test correspond to nodes in the
parse-tree ( and constants in symbol.py ). The repeat-stmt is defined
by an added grammar rule. The corresponding node in the parse-tree is
dispatched against Transformer.handle_repeat_stmt() during parse-tree
traversal. Matching against suite and test in the repeat_stmt node
is done by applying:

suite_node = find_node(repeat_node, symbol.suite)
test_node = find_node(repeat_node, symbol.test, level=1)

What becomes tedious is the creation of the corresponding while_stmt
node which is the expected result of the transformation. I actually
want to use the declaration as it is written above and insert the
suite_node and the test_node where the placeholders suite and test
are defined. Using EasyExtend one can define an extension language
where the placeholders ( and some enhanced versions of those ) become
language elements! Given this one can put everything together:

import macro# module that corresonds to the macro extension
language

class FastTransformer(Transformer):
def handle_repeat_stmt(self, repeat_node):
suite_node = find_node(repeat_node, symbol.suite)
test_node  = find_node(repeat_node, symbol.test, level=1)
target_stmt = 
while 1:
suite
if test:
break

while_node =  macro.expand(target_stmt,
  {'suite': suite_node,
'test': test_node},
   goal =
symbol.while_stmt)
return any_stmt(while_node)

This is pretty safe and works recursively: if the suite node contains
another repeat_stmt node it will be replaced as well.

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


Re: Network Programming in Python

2006-06-23 Thread diffuser78
How will Pyon help my cause ?

Bill Maxwell wrote:
 On 22 Jun 2006 12:02:14 -0700, [EMAIL PROTECTED] wrote:

 I am a newbie in python. I want to learn and implement a small
 networking concept. Please help me. Every help is appreciated.
 
 I have one Linux Box and one Windows PC. I want to have a daemon
 running on Windows PC which listens on some specicif port number. I
 want to send a TCP/IP or UDP/IP packet from Linux box to Windows PC to
 start some application. As Windows PC recieves such a packet from Linux
 Box it executes a certain .exe file. I want to implement this concept.
 
 In short I want to remotely send command from Linux to Windows PC to
 start a particular application.


 Have you checked out Pyro (Python Remote Objects)?
 
   http://pyro.sourceforge.net/
 
 Bill

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


Re: Reuseable iterators - which is better?

2006-06-23 Thread Diez B. Roggisch
zefciu schrieb:
 In the tutorial there is an example iterator class that revesrses the
 string given to the constructor.  The problem is that this class works
 only once, unlike built-in types like string.  How to modify it that it
 could work several times?  I have tried two approaches.  They both work,
 but which of them is stylistically better?
 
 class Reverse: #original one
 Iterator for looping over a sequence backwards
 def __init__(self, data):
 self.data = data
 self.index = len(data)
 def __iter__(self):
 return self
 def next(self):
 if self.index == 0:
 raise StopIteration
 self.index = self.index - 1
 return self.data[self.index]
 
 class Reverse: #1st approach
 Reuseable Iterator for looping over a sequence backwards
 def __init__(self, data):
 self.data = data
 self.index = len(data)
 def __iter__(self):
 return self
 def next(self):
 if self.index == 0:
   self.index = len(self.data) #Reset when previous
 #
 iterator goes out
   raise StopIteration
 self.index = self.index - 1
 return self.data[self.index]
 
 class Reverse: #2nd approach
 Reuseable Iterator for looping over a sequence backwards
 def __init__(self, data):
 self.data = data
 def __iter__(self):
   self.index = len(self.data) #Reset as a part of iterator
 # creation
 return self
 def next(self):
 if self.index == 0:
 raise StopIteration
 self.index = self.index - 1
 return self.data[self.index]



None. You don't reuse iterators! In the actualy example, reusage is 
possible due to the whole data being known  available. But there might 
be cases where this isn't possible - e.g. fetching data from a remote 
location which is too large to fit into memory for re-iteration.

So generally speakiing, if you need an iterator, construct it.

Regards,

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


Re: Unicode problem with exec

2006-06-23 Thread Diez B. Roggisch
Thomas Heller schrieb:
 I'm using code.Interactive console but it doesn't work correctly
 with non-ascii characters.  I think it boils down to this problem:
 
 Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on 
 win32
 Type help, copyright, credits or license for more information.
 print uä
 ä
 exec 'print uä'
 Traceback (most recent call last):
  File stdin, line 1, in ?
  File string, line 1, in ?
  File c:\python24\lib\encodings\cp850.py, line 18, in encode
return codecs.charmap_encode(input,errors,encoding_map)
 UnicodeEncodeError: 'charmap' codec can't encode character u'\x84' in 
 position 0: character maps to undefined
 ^Z
 
 Why does the exec call fail, and is there a workaround?

Most probably because you failed to encode the snippet as whole - so the 
embedded unicode literal isn't encoded properly.

As your exec-encoding seems to be cp850, maybe

exec uprint u'ä'.encode(cp850)

works.

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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Matthias Blume
Pascal Costanza [EMAIL PROTECTED] writes:

 Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it
 is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware
 of such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to
 formally prove
 that it terminates.
 To make the halting problem decidable one would have to do one of
 two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.

 Not quite. See http://en.wikipedia.org/wiki/ACL2

What do you mean not quite?  Of course, Patricia is absolutely
right.  Termination-guaranteeing languages are fundamentally less
expressive than Turing-complete languages.  ACL2 was not mentioned in
the newsgroup header.
-- 
http://mail.python.org/mailman/listinfo/python-list


re question

2006-06-23 Thread Daniel Sch
Hello re gurus,

I wrote this pattern trying to get the name and the content of VHDL 
package
I know that the file is a valid VHDL code, so actually there is no need to 
perform
validation after 'end' token is found, but since it works fine I don't want 
to touch it.

this is the pattern

pattern = 
re.compile(r'^\s*package\s+(?Pname\w+)\s+is\s+(?Pcontent.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
re.DOTALL | re.MULTILINE | re.IGNORECASE)

and the problem is that
package TEST is xyz end;
works but
package TEST123 is xyz end;
fails

\w is supposed to match [a-zA-Z0-9_] so I don't understand why numbers and 
undescore let the pattern fail?
(there is a slight suspicion that it may be a re bug)

I also tried this pattern with the same results

pattern = 
re.compile(r'^\s*package\s+(?Pname.+?)\s+is\s+(?Pcontent.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
re.DOTALL | re.MULTILINE | re.IGNORECASE)

something must be wrong with (?Pname\w+) inside the main pattern

thanks in advance

--
Daniel 


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


Re: serial port servo control

2006-06-23 Thread Si Ballenger
On 22 Jun 2006 08:18:08 -0700, [EMAIL PROTECTED] wrote:

So I ordered a mini SSC II (the servo controller), in order to
control some servos from the computer.  I was hoping to use python to
do the control but have two questions...

1) How should I write to the serial port with python? I found the
module pyserial:
http://pyserial.sourceforge.net/
on the python cheeseshop, and it looks solid but I thought you might
have a better suggestion.

2) To control the servos I have to send the SSC II a string of 3
numbers, 3 bytes long (so 3 numbers in the range 0 - 255, each as a
single byte, one after another).  In C I'd do this by sending 3
char's, as they're only 1 byte, but i'm not exactly sure how to do it
in Python.

Maybe a little off topic, but I've got a page below with some mini ssc
control info.

http://www.geocities.com/zoomkat/index.htm

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


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Bruno Desthuilliers wrote:
 
[EMAIL PROTECTED] wrote:

Hi

I'd like to use metaclasses to dynamically generate a class based on a
parameter to the objects init function.

Do you really need a metaclass for this ?


For example:

class MetaThing(type):
def __init__(cls, name, bases, dict, extra_information):
super(MetaThing, cls).__init__(name, bases, dict)
#setup the class based on the parameter extra_information

class Thing:
__metaclass__ = MetaThing
def __init__(self, extra_information):
 #Somehow pass extra_information to the MetaThing

extra_information = 1
t = Thing(extra_information)

Why would you want a new *class* here ?


The above sample won't work but I hope it demonstrates what I'm trying
to do.

Not enough, I'm afraid - unless it's just me being dumb. From what I see
here, you just can add the extra informations on the object in the
initializer. What's your *real* use case ?

 
 The extra_information is used in MetaThing to tell it what attributes
 to add to the class. For example:
 
 class MetaThing(type):
  def __init__(cls, name, bases, dict, extra_information):
  super(MetaThing, cls).__init__(name, bases, dict)
  #setup the class based on the parameter extra_information
  setattr(cls, make_name(extra_information),
 make_object(extra_information))
 
 Does that clarify things? I might have the wrong approach

There's at least something wrong here : the metaclass code is executed
when the class statement (the one for a class having this metaclass) is
eval'd. It won't be called on class instanciation.

http://www.python.org/download/releases/2.2.3/descrintro/#__new__

Also, you need to understand that modifying a class with impact all it's
instances.

 - I'm new to
 metaclasses. However I do think the solution to my problem lies with
 them since I have to dynamically generate a class

You don't have to create classes for this - it's perfectly legal to set
attributes (data or methods) on a per-object basis. Classes are more
object-factories than rigid types. Just add the needed extra attributes
in the __init__ (the class one, not the metaclass) and you should be done.

  and metaclasses
 provide a mechanism for doing this.

Metaclasses provides a hook on class creation process. But AFAICT, you
don't necessarily need metaclasses to dynamically create classes...




-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Flight search automation

2006-06-23 Thread George Sakkis
I'm trying to use mechanize to fill in a find a flight form and then
get back the results, but I'm not sure how to make it wait until the
results page appears; the response after submitting the form is the
please wait while we are searching for your flights page. Any ideas ?

George

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


Re: * in Python

2006-06-23 Thread Bruno Desthuilliers
placid wrote:
 Duncan Booth wrote:
 
placid wrote:


Hi all,

Can someone tell me what * in the following code means/does a Google
search didnt turn up anything as i dont know what the * is called
(related to Python and i dont think Python has pointers)


* is for variable number of positional arguments, ** is for variable
keyword arguments. The syntax is symmetrical when defining functions and
when calling them.

See http://docs.python.org/ref/calls.html
and http://docs.python.org/ref/function.html
 
 
 so * basically means that args is a list

A tuple IIRC

 containing more arguments that
 can change in size, whereas ** means that args is a dictionary of
 key=value arguments?
 

Why don't you try by yourself in the Python shell ? One of the nice
things with Python is that it's quite easy to explore and experiment.


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is Expressiveness in a Computer Language

2006-06-23 Thread Andreas Rossberg
Chris Uppal wrote:

Well, it seems to me that you are /assuming/ a notion of what kinds of
logic can be called type (theories), and I don't share your
assumptions.  No offence intended.

OK, but can you point me to any literature on type theory that makes a
different assumption?
 
 'Fraid not.  (I'm not a type theorist -- for all I know there may be lots, but
 my suspicion is that they are rare at best.)

I would suspect the same :-). And the reason is that type has a 
well-established use in theory. It is not just my assumption, it is 
established practice since 80 or so years. So far, this discussion has 
not revealed the existence of any formal work that would provide a 
theory of dynamic types in the sense it is used to characterise 
dynamically typed languages.

So what you are suggesting may be an interesting notion, but it's not 
what is called type in a technical sense. Overloading the same term 
for something different is not a good idea if you want to avoid 
confusion and misinterpretations.

 But, as a sort of half-way, semi-formal, example: consider the type 
 environment
 in a Java runtime.  The JVM does formal type-checking of classfiles as it 
 loads
 them.  In most ways that checking is static -- it's treating the bytecode as
 program text and doing a static analysis on it before allowing it to run (and
 rejecting what it can't prove to be acceptable by its criteria).  However, it
 isn't /entirely/ static because the collection of classes varies at runtime in
 a (potentially) highly dynamic way.  So it can't really examine the whole
 text of the program -- indeed there is no such thing.  So it ends up with a
 hybrid static/dynamic type system -- it records any assumptions it had to make
 in order to find a proof of the acceptability of the new code, and if 
 (sometime
 in the future) another class is proposed which violates those assumptions, 
 then
 that second class is rejected.

Incidentally, I know this scenario very well, because that's what I'm 
looking at in my thesis :-). All of this can easily be handled 
coherently with well-established type machinery and terminology. No need 
to bend existing concepts and language, no need to resort to dynamic 
typing in the way Java does it either.

 In code which will be executed at instant A
 obj aMessage.type correct
 obj anotherMessage.   type incorrect
 
 In code which will be executed at instant B
 obj aMessage. type incorrect
 obj anotherMessage.type correct
 
 I don't see how a logic with no temporal element can arrive at all four those
 judgements, whatever it means by a union type.

I didn't say that the type system cannot have temporal elements. I only 
said that a type itself cannot change over time. A type system states 
propositions about a program, a type assignment *is* a proposition. A 
proposition is either true or false (or undecidable), but it is so 
persistently, considered under the same context. So if you want a type 
system to capture temporal elements, then these must be part of a type 
itself. You can introduce types with implications like in context A, 
this is T, in context B this is U. But the whole quoted part then is 
the type, and it is itself invariant over time.

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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Pascal Costanza
Matthias Blume wrote:
 Pascal Costanza [EMAIL PROTECTED] writes:
 
 Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it
 is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware
 of such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to
 formally prove
 that it terminates.
 To make the halting problem decidable one would have to do one of
 two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.
 Not quite. See http://en.wikipedia.org/wiki/ACL2
 
 What do you mean not quite?  Of course, Patricia is absolutely
 right.  Termination-guaranteeing languages are fundamentally less
 expressive than Turing-complete languages.  ACL2 was not mentioned in
 the newsgroup header.

ACL2 is a subset of Common Lisp, and programs written in ACL2 are 
executable in Common Lisp. comp.lang.lisp is not only about Common Lisp, 
but even if it were, ACL2 would fit.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread Bruno Desthuilliers
George Sakkis wrote:
 Dennis Lee Bieber wrote:
 
On 22 Jun 2006 16:48:47 -0700, George Sakkis [EMAIL PROTECTED]
declaimed the following in comp.lang.python:


What does __setitem__ have to do with iterability ?

  It confirms that the object is indexable, and mutable -- ie; a list,
not a tuple or a string.
 
 
 Ok, I'll try once more: What does __setitem__ have to do with
 **iterability**, not mutability or indexability ? 

Nothing.

 I was commenting on
 Maric's post that although some objects are typically iterable, they
 are often treated as atomic by some/many/most applications  (e.g.
 strings). It's not rocket science.

No, it's not rocket science.

It's not rocket science neither to understand that, for the concrete
examples you used (ie strings and tuples), it's quite easy to detect'em
without testing the concrete type.

As you said, what is to be considered as scalar and what's to be
considered as sequence highly depends on the problem at hand. But doing
the distinction does not always implies testing concrete type or mro.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Specifing arguments type for a function

2006-06-23 Thread Bruno Desthuilliers
George Sakkis wrote:
 Dennis Lee Bieber wrote:
 
On 22 Jun 2006 22:55:00 -0700, George Sakkis [EMAIL PROTECTED]
declaimed the following in comp.lang.python:



Ok, I'll try once more: What does __setitem__ have to do with
**iterability**, not mutability or indexability ? I was commenting on
Maric's post that although some objects are typically iterable, they
are often treated as atomic by some/many/most applications  (e.g.
strings). It's not rocket science.


  And the absence of the setitem would indicate such an object -- it
may be iterable in terms of retrieving subparts, but atomic WRT
modification.

  That, at least, is how I interpreted the introduction of the test...
 
 
 Applications that don't need to treat strings as iterables of
 characters wouldn't do so even if strings were mutable. Atomicity has
 to do with whether something is considered to be composite or not, not
 whether it can be modified.

Sure. Do you have any generic solution for this ?


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded Python calling app via COM

2006-06-23 Thread Jim
 Pythoncom.GetActiveObject will retrieve the running instance of the app.

Thanks Roger, that does seem to do the trick.  I haven't tested to see
what happens if there are two instances of the app running, I'm hoping
it will return the frontmost visible one.

  -- Jim

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


Re: Flight search automation

2006-06-23 Thread mkPyVS
Is there an http page redirect call to the client once the java
releases it's wait que?

George Sakkis wrote:
 I'm trying to use mechanize to fill in a find a flight form and then
 get back the results, but I'm not sure how to make it wait until the
 results page appears; the response after submitting the form is the
 please wait while we are searching for your flights page. Any ideas ?
 
 George

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


Re: code is data

2006-06-23 Thread Bruno Desthuilliers
Anton Vredegoor wrote:
(snip)

 However, I knew of the existence of such languages but I am mostly
 interested in standardized code interchange, like for example with JSONP
 which fetches some external javascriptcode from another server using
 JSON and places the translated javascript into a webpage at the request
 of the clients browser or so it seems.

This is AJAX with JSON instead of XML (should we call this AJAJ ?-).
It's quite handy, since it saves both the extra bits to be transfered
(XML is way much verbose than JSON) and the XML to javascript parsing.

 Maybe a Python webserver could
 also emit pieces of javascript code by getting them from a *Python* code
 library after translating Python code on the fly?

If you restrict this on data, it's already done (Turbogears uses this
for AJAX).

 That would open up the web to Python programmers without browsers
 needing to understand Python. Like Jython, but now as separately
 distributed functions from different servers.
 
 Anton


-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread J�rgen Exner
Vesa Karvonen wrote:
 In comp.lang.functional Anton van Straaten [EMAIL PROTECTED]
 wrote: [...]
 I reject this comparison.  There's much more to it than that.  The

 I think that we're finally getting to the bottom of things.  While
 reading your reponses something became very clear to me:
 latent-typing and latent- types are not a property of languages.
 Latent-typing, also known as informal reasoning, is something that

And what does this have to do with Perl? Are you an alter ego of Xha Lee who 
spills his 'wisdom' across any newsgroup he can find?

jue 


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


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Carl Banks
[EMAIL PROTECTED] wrote:
 Hi

 I'd like to use metaclasses to dynamically generate a class based on a
 parameter to the objects init function.

 For example:

 class MetaThing(type):
 def __init__(cls, name, bases, dict, extra_information):
 super(MetaThing, cls).__init__(name, bases, dict)
 #setup the class based on the parameter extra_information

 class Thing:
 __metaclass__ = MetaThing
 def __init__(self, extra_information):
  #Somehow pass extra_information to the MetaThing

 extra_information = 1
 t = Thing(extra_information)

Tricky.  First of all, __init__ belongs to the class, not the object.
(Sometimes it's convenient to say it's the object's __init__ method,
but when mucking around with metaclasses it's important be precise
about what belongs to who, otherwise everyone gets confused.)  Because
__init__ belongs to the class, the object's class must already exist
before calling it, which is contrary to what you seem to want to do.

It seem as if, when creating an object, you want to create it's very
own class to go with it.  I suppose there could be use case for it, but
I highly recommend you consider whether features like instance methods
or classmethods can accomplish what you want.  If you'd still rather
that a Thing have its very own class, I recommend you forget about
metaclasses and use a factory function with a closure:

def create_thing(extra_information):
class Thing(object):
def __init__(self):
# use extra_information here
...
return Thing()

If you don't like this, or if you insist on using a metaclass, and you
don't care that you'll be confusing the hell out of anyone reading the
code, the answer is to override the class's __new__ method.  Unlike
__int__, the __new__ method can return any object it wants, including
an object of a different class.  The class should subclass itself in
its __new__ method, providing the passed extra_information to the
constructor of the new subclass, then return an object created from
that subclass.  The subclass should override __new__ so as not to
repeat the hijinks of the class's __new__.

Don't follow?  The actual source code won't be much easier.  Here's an
example.

class MetaThing(type):
def __new__(metacls,name,bases,clsdict,extra_information):
# use extra_information
return type.__new__(metacls,name,bases,clsdict)

class Thing(object):
 def __new__(cls,extra_information):
 clsdict = {'__new__':object.__new__}
 my_very_own_class = MetaThing(
 Subthing,(Thing,),clsdict,extra_information)
 return object.__new__(my_very_own_class)

Note that Thing doesn't and shouldn't define __metaclass__, since it
creates its subclass directly from the metaclass's constructor.  You
could, of course, also use the closure method I demonstrated above in
Thing's __new__ method--essentially you'd be using Thing's __new__
method as the factory function.


 The above sample won't work but I hope it demonstrates what I'm trying
 to do.

Again, I highly recommend you consider whether what you're trying to
do can be done more easily with instance or class methods.


Carl Banks

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


hard to explain for a french ;-)

2006-06-23 Thread AZAIS Bruce
Title: Message



hi 
everybody,

i have a problem 
with a script.
aftera 
research with my directory, i want to do a popup of a person's photo but i don't 
know the syntax (i'm a newbie):

with a 
_javascript_ : a target="_blank" tal:attributes="href 
python:"_javascript_:popup(/intranet/nom_agents/'+result.fullname+'/photo)""Popup/a 
don't work

with the 
function window.open : a href="" tal:attributes="python:onClick 
string:_javascript_:window.open(/intranet/nom_agents/'+result.fullname+'/photo)"Popup/a 
don't work

i try that 
:

a 
target="_blank" tal:attributes='href 
python:"/intranet/nom_agents/"+result.fullname+"/photo"'img 
src=""/a it's good but, it's open the photo in a 
large window, not in a popup.

do you understand my 
problem ? (it's not easy to explain that in english for me)
thank you for all 
and have a good day.
Bruce







*
"Le contenu de ce courriel et ses eventuelles pièces jointes sont
confidentiels. Ils s'adressent exclusivement à la personne destinataire.
Si cet envoi ne vous est pas destiné, ou si vous l'avez reçu par erreur,
et afin de ne pas violer le secret des correspondances, vous ne devez pas
le transmettre à d'autres personnes ni le reproduire. Merci de le renvoyer
à l'émetteur et de le détruire.

Attention : L'Organisme de l'émetteur du message ne pourra être tenu responsable de l'altération
du présent courriel. Il appartient au destinataire de vérifier que les
messages et pièces jointes reçus ne contiennent pas de virus.
Les opinions contenues dans ce courriel et ses éventuelles pièces
jointes sont celles de l'émetteur. Elles ne reflètent pas la position de l'Organisme
sauf s'il en est disposé autrement dans le présent courriel."
**
-- 
http://mail.python.org/mailman/listinfo/python-list

what exceptions may file() and read() throw?

2006-06-23 Thread Daniel Sch
Hello,

currently I am using this instance method

def getFilecontent(self, filename):
try:
return file(filename).read()
except IOError, err_msg:
print err_msg
sys.exit(1)
except:
print unknown exception in PackageParser
sys.exit(1)

I tried to open a file for which I don't have the permissions to read 
(etc/shadow)
and I tried to open a file which doesn't exist
in both cases I got IOError exception, so my question is
does it make sence to have

except:
print unknown exception in PackageParser
sys.exit(1)

or is it a dead code?
are there some good reference sources to see what file() and read()
may throw, IMHO it's OS dependent.

Regards, Daniel



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


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Patricia Shanahan
Pascal Costanza wrote:
 Matthias Blume wrote:
 Pascal Costanza [EMAIL PROTECTED] writes:

 Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it
 is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware
 of such
 a language).  It should also be clear that termination analysis 
 need not
 be done informally.  Given a program, it may be possible to
 formally prove
 that it terminates.
 To make the halting problem decidable one would have to do one of
 two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.
 Not quite. See http://en.wikipedia.org/wiki/ACL2

 What do you mean not quite?  Of course, Patricia is absolutely
 right.  Termination-guaranteeing languages are fundamentally less
 expressive than Turing-complete languages.  ACL2 was not mentioned in
 the newsgroup header.
 
 ACL2 is a subset of Common Lisp, and programs written in ACL2 are 
 executable in Common Lisp. comp.lang.lisp is not only about Common Lisp, 
 but even if it were, ACL2 would fit.

To prove Turing-completeness of ACL2 from Turing-completeness of Common
Lisp you would need to run the reduction the other way round, showing
that any Common Lisp program can be converted to, or emulated by, an
ACL2 program.

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


Re: * in Python

2006-06-23 Thread Duncan Booth
Bruno Desthuilliers wrote:

 so * basically means that args is a list
 
 A tuple IIRC

In a function definition * means that any remaining position arguments will 
be passed in as a tuple. In a function call the * means that any sequence 
will be unpacked as positional arguments: it doesn't have to be a list or 
a tuple.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Carl Banks
[EMAIL PROTECTED] wrote:
 The extra_information is used in MetaThing to tell it what attributes
 to add to the class. For example:

 class MetaThing(type):
  def __init__(cls, name, bases, dict, extra_information):
  super(MetaThing, cls).__init__(name, bases, dict)
  #setup the class based on the parameter extra_information
  setattr(cls, make_name(extra_information),
 make_object(extra_information))

 Does that clarify things?

Why do the extra attributes need to be part of the class?  ISTM each
instance has its own class; therefore there it doesn't matter whether a
member is a class member or an instance member.


Carl Banks

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


Re: * in Python

2006-06-23 Thread placid

Bruno Desthuilliers wrote:
 placid wrote:
  Duncan Booth wrote:
 
 placid wrote:
 
 
 Hi all,
 
 Can someone tell me what * in the following code means/does a Google
 search didnt turn up anything as i dont know what the * is called
 (related to Python and i dont think Python has pointers)
 
 
 * is for variable number of positional arguments, ** is for variable
 keyword arguments. The syntax is symmetrical when defining functions and
 when calling them.
 
 See http://docs.python.org/ref/calls.html
 and http://docs.python.org/ref/function.html
 
 
  so * basically means that args is a list

 A tuple IIRC

  containing more arguments that
  can change in size, whereas ** means that args is a dictionary of
  key=value arguments?
 

 Why don't you try by yourself in the Python shell ? One of the nice
 things with Python is that it's quite easy to explore and experiment.

i did try it in a  Python shell after i learnt what it was. Like i said
*args will be a list, but when i try **args with the following code it
doesnt work

def test(**args):
keys = args.keys()
for key in keys:
print key+=+args(key)



 --
 bruno desthuilliers
 python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
 p in '[EMAIL PROTECTED]'.split('@')])

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


Re: what exceptions may file() and read() throw?

2006-06-23 Thread Duncan Booth
Daniel Schüle wrote:

 Hello,
 
 currently I am using this instance method
 
 def getFilecontent(self, filename):
 try:
 return file(filename).read()
 except IOError, err_msg:
 print err_msg
 sys.exit(1)
 except:
 print unknown exception in PackageParser
 sys.exit(1)
 
 I tried to open a file for which I don't have the permissions to read 
 (etc/shadow)
 and I tried to open a file which doesn't exist
 in both cases I got IOError exception, so my question is
 does it make sence to have
 
 except:
 print unknown exception in PackageParser
 sys.exit(1)
 
 or is it a dead code?

It is dead code in the sense that it simply converts every exception into a 
SystemExit exception thereby losing information from the message and the 
traceback which might have helped you track down the problem. If you aren't 
able to do anything useful with an exception then the best thing is almost 
always to let it propogate upwards to somewhere it can be handled usefully. 
That generally means that exceptions you haven't thought of need to be 
communicated to a human who can lodge a bug report or fix the code.

You can't easily list the exceptions that your code could throw. There are 
some obvious ones apart from IOError: say filename was an int (or even 
certain strings) you would get TypeError, or you might get MemoryError or 
KeyboardInterrupt. More obscurely, if you reused file as a global variable 
you could generate any exception at all.

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


Re: re question

2006-06-23 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], Daniel Schüle wrote:

 this is the pattern
 
 pattern = 
 re.compile(r'^\s*package\s+(?Pname\w+)\s+is\s+(?Pcontent.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
  
 re.DOTALL | re.MULTILINE | re.IGNORECASE)
 
 and the problem is that
 package TEST is xyz end;
 works but
 package TEST123 is xyz end;
 fails

For me both work:

In [11]:pattern = (
t.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', )\s+is\s+(?Pconten
   .11.:re.DOTALL | re.MULTILINE | re.IGNORECASE))

In [12]:pattern.match('package TEST is xyz end;')
Out[12]:_sre.SRE_Match object at 0x405b1650

In [13]:pattern.match('package TEST123 is xyz end;')
Out[13]:_sre.SRE_Match object at 0x405b15f8

I have copy and pasted you code.

For debugging re's in Python you might take a
look at http://kodos.sourceforge.net/

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

Re: * in Python

2006-06-23 Thread Duncan Booth
placid wrote:

 i did try it in a  Python shell after i learnt what it was. Like i said
 *args will be a list, but when i try **args with the following code it
 doesnt work
 
 def test(**args):
 keys = args.keys()
 for key in keys:
 print key+=+args(key)
 

When you post here, it helps if instead of saying 'it doesnt work' you say 
what you expected to happen and what actually happened (and quote exact 
error messages, dont paraphrase them).

If I try your code it works fine: it defines a function.

If I try to call your function, even though you didn't include a call in 
what 'doesnt work', then I get the exception I would expect, namely that 
you are trying to call args as though it were a function 'args(key)' 
instead of subscripting it as a dictionary 'args[key]'. Fixing that will 
then generate a different error, but I'm sure you'll be able to figure it 
out.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Matthias Blume
Pascal Costanza [EMAIL PROTECTED] writes:

 Matthias Blume wrote:
 Pascal Costanza [EMAIL PROTECTED] writes:
 
 Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type systems
 that guarantee termination, but I think that is fair to say that it
 is not
 yet understood how to make a practical general purpose language, whose
 type system would guarantee termination (or at least I'm not aware
 of such
 a language).  It should also be clear that termination analysis need not
 be done informally.  Given a program, it may be possible to
 formally prove
 that it terminates.
 To make the halting problem decidable one would have to do one of
 two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.
 Not quite. See http://en.wikipedia.org/wiki/ACL2
 What do you mean not quite?  Of course, Patricia is absolutely
 right.  Termination-guaranteeing languages are fundamentally less
 expressive than Turing-complete languages.  ACL2 was not mentioned in
 the newsgroup header.

 ACL2 is a subset of Common Lisp, and programs written in ACL2 are
 executable in Common Lisp. comp.lang.lisp is not only about Common
 Lisp, but even if it were, ACL2 would fit.

So what?

Patricia said less expressive, you said subset.  Where is the
contradiction?

Perhaps you could also bring up the subset of Common Lisp where the
only legal program has the form:

   nil

Obviously, this is a subset of Common Lisp and, therefore, fits
comp.lang.lisp.  Right?

Yes, if you restrict the language to make it less expressive, you can
guarantee termination.  Some restrictions that fit the bill already
exist.  IMHO, it is still wrong to say that Lisp guaratees
termination, just because there is a subset of Lisp that does.

Matthias

PS: I'm not sure if this language guarantees termination, though.  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Flight search automation

2006-06-23 Thread George Sakkis
mkPyVS wrote:

 Is there an http page redirect call to the client once the java
 releases it's wait que?

Sorry, I've no idea.. not even sure if they use java or whether this
matters. Can you guess by trying, say, http://www.travelocity.com/ ?
Expedia and Orbitz have also a waiting page, hopefully I can figure
them out once I have one working.

George

 George Sakkis wrote:
  I'm trying to use mechanize to fill in a find a flight form and then
  get back the results, but I'm not sure how to make it wait until the
  results page appears; the response after submitting the form is the
  please wait while we are searching for your flights page. Any ideas ?
  
  George

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


Re: what exceptions may file() and read() throw?

2006-06-23 Thread Daniel Sch
Hi

 You can't easily list the exceptions that your code could throw. There are
 some obvious ones apart from IOError: say filename was an int (or even
 certain strings) you would get TypeError, or you might get MemoryError or
 KeyboardInterrupt. More obscurely, if you reused file as a global variable
 you could generate any exception at all.

I undestand now, so it would be better to let it in the code
in case it's triggered (I triggered it by passing int instead of str, as you 
said)
I would at least know where to look
I wouldn't call it dead code then ... dead code is more like

if False:
do_something()

thank you

Regards, Daniel


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


Re: * in Python

2006-06-23 Thread Bruno Desthuilliers
Duncan Booth wrote:
 Bruno Desthuilliers wrote:
 
 
so * basically means that args is a list

A tuple IIRC
 
 
 In a function definition * means that any remaining position arguments will 
 be passed in as a tuple. In a function call the * means that any sequence 
 will be unpacked as positional arguments: it doesn't have to be a list or 
 a tuple.

yes, of course - I only saw it from the function's POV.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * in Python

2006-06-23 Thread Bruno Desthuilliers
placid wrote:
 Bruno Desthuilliers wrote:
 
(snip)
Why don't you try by yourself in the Python shell ? One of the nice
things with Python is that it's quite easy to explore and experiment.
 
 
 i did try it in a  Python shell after i learnt what it was. Like i said
 *args will be a list, but when i try **args with the following code it
 doesnt work

doesn't work is the most useless description of a problem.

 def test(**args):
 keys = args.keys()
 for key in keys:
 print key+=+args(key)

you want args[key], not args(key)

And you forget to tell how you called this code and what you got.

FWIW:
Python 2.4.3 (#1, Jun  3 2006, 17:26:11)
[GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type help, copyright, credits or license for more information.
 def test(**kw):
... for item in kw.items():
... print %s : %s % item
...
 test()
 test(parrot=dead, walk=silly, nose=big)
nose : big
parrot : dead
walk : silly
 test(**{'answer':42})
answer : 42



-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Pascal Costanza
Patricia Shanahan wrote:
 Pascal Costanza wrote:
 Matthias Blume wrote:
 Pascal Costanza [EMAIL PROTECTED] writes:

 Patricia Shanahan wrote:
 Vesa Karvonen wrote:
 ...
 An example of a form of informal reasoning that (practically) every
 programmer does daily is termination analysis.  There are type 
 systems
 that guarantee termination, but I think that is fair to say that it
 is not
 yet understood how to make a practical general purpose language, 
 whose
 type system would guarantee termination (or at least I'm not aware
 of such
 a language).  It should also be clear that termination analysis 
 need not
 be done informally.  Given a program, it may be possible to
 formally prove
 that it terminates.
 To make the halting problem decidable one would have to do one of
 two
 things: Depend on memory size limits, or have a language that 
 really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.
 Not quite. See http://en.wikipedia.org/wiki/ACL2

 What do you mean not quite?  Of course, Patricia is absolutely
 right.  Termination-guaranteeing languages are fundamentally less
 expressive than Turing-complete languages.  ACL2 was not mentioned in
 the newsgroup header.

 ACL2 is a subset of Common Lisp, and programs written in ACL2 are 
 executable in Common Lisp. comp.lang.lisp is not only about Common 
 Lisp, but even if it were, ACL2 would fit.
 
 To prove Turing-completeness of ACL2 from Turing-completeness of Common
 Lisp you would need to run the reduction the other way round, showing
 that any Common Lisp program can be converted to, or emulated by, an
 ACL2 program.

Sorry, obviously I was far from being clear. ACL2 is not 
Turing-complete. All iterations must be expressed in terms of 
well-founded recursion.


Pascal

-- 
3rd European Lisp Workshop
July 3 - Nantes, France - co-located with ECOOP 2006
http://lisp-ecoop06.bknr.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Maric Michaud
Le Vendredi 23 Juin 2006 16:03, Carl Banks a écrit :
 Don't follow?  The actual source code won't be much easier.  Here's an
 example.

     class MetaThing(type):
         def __new__(metacls,name,bases,clsdict,extra_information):
             # use extra_information
             return type.__new__(metacls,name,bases,clsdict)

     class Thing(object):
          def __new__(cls,extra_information):
              clsdict = {'__new__':object.__new__}
              my_very_own_class = MetaThing(
                  Subthing,(Thing,),clsdict,extra_information)
              return object.__new__(my_very_own_class)

Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances are 
class.
Something like that :

In [114]: class MetaClass(object) :
   .: def __new__(cls, name, bases=(), **some_attributes) :
   .: return type('newtype %s' % name, bases, some_attributes)
   .:
   .:


Let's play with it :


In [115]: Concrete1 = MetaClass('conc1', (), classprop=1, method=lambda 
s : fun)

In [116]: Concrete2 = MetaClass('conc1', (), classprop=1, method=lambda 
s : fun)

In [117]: isinstance(Concrete1(), Concrete2)
Out[117]: False

In [118]: isinstance(Concrete1(), Concrete1)
Out[118]: True

In [119]: Concrete1().method()
Out[119]: 'fun'

In [120]: Concrete1.classprop
Out[120]: 1

In [121]: class Abstract(object) :
   .: def __init__(self) : self._attr = self._attr_type()
   .:
   .:

In [122]: Concrete = MetaClass('concrete_with_list', (Abstract,), 
_attr_type=list)

In [123]: Concrete()._attr
Out[123]: []

In [124]: Concrete = MetaClass('concrete_with_int', (Abstract,), 
_attr_type=int)

In [125]: Concrete()._attr
Out[125]: 0

In [126]: type(Concrete)
Out[126]: type 'type'

In [127]: type(Concrete())
Out[127]: class '__main__.newtype concrete_with_int'


regards,



-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Alex Martelli
Carl Banks [EMAIL PROTECTED] wrote:

 [EMAIL PROTECTED] wrote:
  The extra_information is used in MetaThing to tell it what attributes
  to add to the class. For example:
 
  class MetaThing(type):
   def __init__(cls, name, bases, dict, extra_information):
   super(MetaThing, cls).__init__(name, bases, dict)
   #setup the class based on the parameter extra_information
   setattr(cls, make_name(extra_information),
  make_object(extra_information))
 
  Does that clarify things?
 
 Why do the extra attributes need to be part of the class?  ISTM each
 instance has its own class; therefore there it doesn't matter whether a
 member is a class member or an instance member.

It matters for a member that is actually a special-method: Python's
automatic search for special methods (except on old-style classes) does
NOT look at per-instance members, only at per-class ones.

But, as many have already said, a custom metaclass is probably not the
optimal tool for this task (and it's definitely wrong to alter a
metaclass's __init__'s signature in incompatible ways -- you would never
be able to make classes with metaclass MetaThing with a normal class
statement, since the intrinsic call to the metaclass's __init__ fails!).


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


Re: what exceptions may file() and read() throw?

2006-06-23 Thread Bruno Desthuilliers
Daniel Schüle wrote:
 Hi
 
 
You can't easily list the exceptions that your code could throw. There are
some obvious ones apart from IOError: say filename was an int (or even
certain strings) you would get TypeError, or you might get MemoryError or
KeyboardInterrupt. More obscurely, if you reused file as a global variable
you could generate any exception at all.
 
 
 I undestand now, so it would be better to let it in the code
 in case it's triggered 

Nope. Let it propagate, so you have a full traceback. traceback are usefull.




-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using metaclassed to dynamically generate a class based on a parameter to the objects init function.

2006-06-23 Thread Maric Michaud
Le Vendredi 23 Juin 2006 17:09, Maric Michaud a écrit :
 Hmmm, rigourously speaking, metaclasses in OOP are classes whose instances
 are class.
Ooops, sorry i didn't notice you were calling type's __new__ (and not 
object'sone).


-- 
_

Maric Michaud
_

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Saying latently-typed language is making a category mistake

2006-06-23 Thread Chris Smith
Patricia Shanahan [EMAIL PROTECTED] wrote:
 Vesa Karvonen wrote:
 ...
  An example of a form of informal reasoning that (practically) every
  programmer does daily is termination analysis.  There are type systems
  that guarantee termination, but I think that is fair to say that it is not
  yet understood how to make a practical general purpose language, whose
  type system would guarantee termination (or at least I'm not aware of such
  a language).  It should also be clear that termination analysis need not
  be done informally.  Given a program, it may be possible to formally prove
  that it terminates.
 
 To make the halting problem decidable one would have to do one of two
 things: Depend on memory size limits, or have a language that really is
 less expressive, at a very deep level, than any of the languages
 mentioned in the newsgroups header for this message.

Patricia, perhaps I'm misunderstanding you here.  To make the halting 
problem decidable is quite a different thing than to say given a 
program, I may be able to prove that it terminates (so long as you also 
acknowledge the implicit other possibility: I also may not be able to 
prove it in any finite bounded amount of time, even if it does 
terminate!)

The fact that the halting problem is undecidable is not a sufficient 
reason to reject the kind of analysis that is performed by programmers 
to convince themselves that their programs are guaranteed to terminate.  
Indeed, proofs that algorithms are guaranteed to terminate even in 
pathological cases are quite common.  Indeed, every assignment of a 
worst-case time bound to an algorithm is also a proof of termination.

This is, of course, a very good reason to reject the idea that the 
static type system for any Turing-complete language could ever perform 
this same kind analysis.

-- 
Chris Smith - Lead Software Developer / Technical Trainer
MindIQ Corporation
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Absolute noob to Linux programming needs language choice help

2006-06-23 Thread Alex Martelli
[EMAIL PROTECTED] wrote:

 Hey guys,
 
 I am absolutely new to Linux programming, with no w##s programming
 experience except a small amount of C++ console apps.
 Reasonably new to Linux, BSD etc, got good sound networking base of
 knowledge and dont have any problem working the command line etc.
 
 I want to learn a language that I can use in my networking duties that
 is most likely to be of use to me. I have a few choices I can think of
 being:
 
 Python
 Perl
 C
 
 Any other Langs out there that would be better suited?
 
 I want to be able to use the app's I write in OpenBSD and RH versions
 of Linux
 
 What would you reccomend (Unbiased opinion please, I'm after the
 functionality I'll love it later :) )

C is extremely low-level -- you'll want to know it well if you ever need
to program something inside the kernel (or study kernel sources to
understand some detail or anomaly), but for general programming it's a
lot of unwarranted effort.

Python, Perl, and a third language you have not mentioned, Ruby, are
very high level, and each is suitable for just about the same range of
programming (almost any programming, except very low-level;-).  The
choice between the three cannot really be based on language level or
power because those aspects essentially coincide; rather, you should
choose based on your tastes, and practical considerations such as the
availability of libraries and other tools (which tends to be excellent
for all three languages, so it's unlikely to guide your choice all that
much).  If you want to make sure you have no regrets later, a minimal
amount of study of all three is warranted before you pick one to get
deeper into, IMHO.

Me, I knew the Perl of the time very well when I met Python, and I've
studied Ruby later -- Python definitely meets _my_ needs optimally; but
other people, with very different tastes, could well choose differently!


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


Re: re question

2006-06-23 Thread Daniel Sch
Hi

[...]

hm, that's wired
I just tried it in python shell and it works but same code as script file 
fails

for anyone who want to see for himself

# package.vhd file
bash % cat package.vhd
library ieee;
use ieee.std_logic_1164.all;

package TEST123 is
constant BASE
End Package Test;


# parser.py
bash % cat parser.py
#!/usr/bin/env python

import sys, re

reflags = re.DOTALL | re.MULTILINE | re.IGNORECASE

pattern = 
re.compile(r'^\s*package\s+(?Pname\w+)\s+is\s+(?Pcontent.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
reflags)

class PackageParser(object):
def __init__(self, filename):
self.package = file(filename).read()
def parse(self):
return pattern.search(self.package)

if __name__ == __main__:
p = PackageParser(package.vhd)
m = p.parse()
if m is None:
print nothing
sys.exit(1)
print m.group(content)
print m.group(name)


# testing
bash % ./parser.py
nothing

ps:
 sys.version
'2.4.2 (#2, Mar  3 2006, 13:32:59) \n[GCC 3.2.2 20030222 (Red Hat Linux 
3.2.2-5)]'

Regards, Daniel 


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


Re: String negative indices?

2006-06-23 Thread Steven D'Aprano
On Fri, 23 Jun 2006 02:17:39 -0700, Filip Wasilewski wrote:

 [EMAIL PROTECTED] wrote:
 
 Logically, I should be able to enter x[-2:-0] to get the last and next to 
 last characters. However, since Python doesn't distinguish between positive 
 and negative zero, this doesn't work. Instead, I have to enter x[-2:].
 
 Hooray! Logically there is no such thing as positive or negative zero,
 or did I miss something in the primary?

No, not in the primary, or even in the secondary, but possibly in the
tertiary.

For many purposes, it doesn't make sense to distinguish +0 from -0. But
for other purposes, it does.

For instance, in floating point maths, it may be useful for negative
numbers that underflow to be distinguished from positive numbers that
underflow. See, for example,
http://www.savrola.com/resources/negative_zero.html

In statistical mechanics, some systems can have negative absolute
temperatures, including negative zero. Counter-intuitively, negative
absolute temperatures aren't colder than absolute zero, but hotter than
any positive temperature. So, strangely enough, a temperature of -0K is
hotter than a infinitely hot temperature!

(Those wacky physicists and their mathematics...)

See http://en.wikipedia.org/wiki/Negative_absolute_temperature for a
description. And in case you think this is just a modern version of angels
dancing on the head of a pin, negative absolute temperatures are essential
for lasers.

In pure mathematics, zero is usually considered unsigned. However, in
non-standard analysis using so-called hyperreal or surreal numbers,
mathematicians use infinitesimals which are [sloppy hand-waving] like
signed zeroes. To put it another way, only slightly less sloppy,
infinitesimals are zero, but not all the same zero.

When doing calculus with complex numbers, it is very important to
distinguish which direction you are taking your limits in, and so
lim z - 0+0i is not necessarily the same as lim z - 0-0i.


-- 
Steven

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


Re: what exceptions may file() and read() throw?

2006-06-23 Thread [EMAIL PROTECTED]

Daniel Schüle wrote:
 Hello,

 currently I am using this instance method

 def getFilecontent(self, filename):
 try:
 return file(filename).read()
 except IOError, err_msg:
 print err_msg
 sys.exit(1)
 except:
 print unknown exception in PackageParser
 sys.exit(1)

 I tried to open a file for which I don't have the permissions to read
 (etc/shadow)
 and I tried to open a file which doesn't exist
 in both cases I got IOError exception, so my question is
 does it make sence to have

 except:
 print unknown exception in PackageParser
 sys.exit(1)

 or is it a dead code?
 are there some good reference sources to see what file() and read()
 may throw, IMHO it's OS dependent.

 Regards, Daniel

You also could do something like

   def getFilecontent(self, filename):
try:
return file(filename).read()
except IOError, err_msg:
print err_msg
sys.exit(1)
except Exception ,e:
print e.__class__, str(e)

Then the next tiome this happens you have more information on what
happened

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


Re: Network Programming in Python

2006-06-23 Thread Grant Edwards
On 2006-06-23, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 How will Pyon help my cause ?

What's Pyon?

-- 
Grant Edwards   grante Yow!  We are now enjoying
  at   total mutual interaction in
   visi.coman imaginary hot tub...
-- 
http://mail.python.org/mailman/listinfo/python-list


Python profiler and decorators

2006-06-23 Thread warspir
HiI was wondering about this while working on profiling my program using the profile module.Say we have the following:@decdef func: blah blah blahWhen profiling the whole program, what would the total time for func represent? The time spent just in the original function or the time spent spent in the function along with the execution of the decorator's code?
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list

Python in HTML

2006-06-23 Thread brochu121
Does anyone know of a way to embed python scripts into html, much like
you would javascript or php? I do not want to use this to connect to a
database, but rather for a functional script to be called when a user
clicks on a link to open a page.

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


Re: Python in HTML

2006-06-23 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Does anyone know of a way to embed python scripts into html, much like
 you would javascript or php? 

I think you'd better learn the profound difference between client-side
and server-side scripting.

 I do not want to use this to connect to a
 database, but rather for a functional script to be called when a user
 clicks on a link to open a page.

If it's client-side scripting, javascript is the only option.

-- 
bruno desthuilliers
python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >