Re: [Tutor] Builtin "property" decorator hiding exceptions

2007-04-19 Thread Andreas Kostyrka
* Jacob Abraham <[EMAIL PROTECTED]> [070419 10:08]:
> Hi Andreas Kostyrka,
> 
>I am aware that property is a data descriptor. And I still don't see why 
> if can't be uses as a decorator since decorators were created to fix the 
> issue.
> 
> getx= property(getx)

Simple, they don't return function objects. Basically, function
objects (methods) do the __get__ protocol that property is doing to
make the self parameter binding.

decorators, if you expect them to work like normal methods do have
certain limits what they can return.

Ever wondered why practically all (well, I did it for a closed source
contract once differently) decorators are functions that return
interior nested functions, instead of returning callable object
instances? That's why.

Andreas
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Switanek, Nick
Alan,

Please let us know when you have a draft of your tutorial on Beautiful
Soup and such. I'd be eager to have a look!

Thanks,
Nick
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Builtin "property" decorator hiding exceptions

2007-04-19 Thread Kent Johnson
Andreas Kostyrka wrote:
> * Jacob Abraham <[EMAIL PROTECTED]> [070419 10:08]:
>> Hi Andreas Kostyrka,
>>
>>I am aware that property is a data descriptor. And I still don't see why 
>> if can't be uses as a decorator since decorators were created to fix the 
>> issue.
>>
>> getx= property(getx)
> 
> Simple, they don't return function objects.

That is not a requirement, afaik. classmethod() and staticmethod() don't 
return function objects either and they are usable as decorators.

@property
def foo()...

is equivalent to
def foo()...
foo = property(foo)

which is the usual usage.

To argue from authority :-) Ian Bicking agrees with me:
http://blog.ianbicking.org/property-decorator.html

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Builtin "property" decorator hiding exceptions

2007-04-19 Thread Kent Johnson
Jacob Abraham wrote:
> Hi,
> 
>The sample script below throws the exception "AttributeError: input" 
> rather than the expected exception "AttributeError: non_existent_attribute".  
> 
>Please help me write a decorator or descriptor of my own that fixes the 
> issue.
> 
> class Sample(object):
> def __init__(self):
> self.arguments = {}
> 
> def __getattr__(self, name):
> ret_val = self.arguments.get(name, None)
> if ret_val != None: return ret_val
> raise AttributeError, name
> 
> @property
> def input(self):
> self.non_existent_attribute
> 
> 
> sample = Sample()
> sample.input

I don't fully understand what is going on here but it seems that it is 
your __getattr__() that is hiding the exception.

If I take out __getattr__(), I get
AttributeError: 'Sample' object has no attribute 'non_existent_attribute'

I think this is what is happening:
- the input attribute is fetched
- input is a descriptor so its __get__ method is called
- __get__ tries to find non_existent_attribute by the usual methods, 
which fail
- __get__ calls __getattr__ which raises AttributeError
- __get__ raises AttributeError

OK, so think about it - trying to access .input has raised an 
AttributeError, i.e. attribute access through the normal mechanism has 
failed.

Now __getattr__ is called for input and again AttributeError is raised; 
this is the error you see.

If you put some print statements into __getattr__ you can see this is 
the order of events.

This is not the behaviour you want but it does make a certain sense.

If you raise a different exception in __getattr__ it is propagated out.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Questions of Maths

2007-04-19 Thread Abu Ismail
Thank you very much guys, this has been most helpful.

At the moment I run the program as Alan suggests. However, the goal is
to incorporate the program into Glade2 GUI and I am not sure that it
will work with Tk, although I must admit I have not tried it out yet.

Abu Ismail

On 4/18/07, János Juhász <[EMAIL PROTECTED]> wrote:
> Hi Abu,
>
> > Question: how to determine whether point C is to the left or to the
> > right of the line AB?
>
> When the line given by A(Xa,Ya) and B(Xb, Yb),
> the area of the A-B-C triangle can be calculated with the value of next
> determinant / 2
>
> | Xa, Ya, 1 |
> | Xb, Yb, 1 |
> | Xc, Yc, 1 | / 2
>
> So:
>
> Area = ( Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb) ) / 2
>
> Area > 0 | the points are clockwise (C is on the left)
> Area < 0 | the points are counterclockwise (C is on the right)
> Area = 0 | the points are on the same line
>
>
> It can be written in a python function
>
> ###
> def TriArea(a, b, c):
> #Area = (Xa(Yb-Yc) - Xb(Ya-Yc) + Xc(Ya-Yb)) /2
> return ( a[0] * (b[1]-c[1]) - b[0] * (a[1]-c[1]) + c[0] * (a[1]-b[1])
> )/2
>
> ###
> # to test it.
> print TriArea((0,0), (10,0), (2,2))
> print TriArea((0,0), (10,0), (2,-2))
> print TriArea((0,0), (10,0), (2,0))
> ###
>
>
> The biggest advantage of this calculation is that,
> it never goes to zero division exception.
>
>
>
> Best regards,
> Janos
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Alan Gauld


"Switanek, Nick" <[EMAIL PROTECTED]> wrote

Please let us know when you have a draft of your tutorial on 
Beautiful

Soup and such. I'd be eager to have a look!


Here is the current draft, the concepts bits are all there  (nothing
on Beautiful Soup as yet) but the example is giving me some headaches
so it could change significantly over the next weeks. But early 
feedback

is always welcome!

The idea is to do the example using only the standard library
tools then repeat with BS to show how much easier it is.
But I'm hitting problems getting the standard tools to work!

Alan G. 
Title: Web Client Programming





Web Client Programming


What will we cover?

A brief history of the web
The fundamentals of http
Sending requests to a web server
Processing html





Note: In this topic I refer to a lot of conceptual 
ideas for which only limited knowledge is required to 
write the code discussed. I try to provide links, 
mainly to Wikipedia articles, but if there is no link 
you will find most of the subjects discussed in more 
depth on Wikipedia.
 

A Brief History of the World Wide Web

The story of the 
world wide web 
and its invention by 
Tim Berners-Lee 
is probably one of the best known in computing. 
However it is worth revisiting some of the key points 
in the story to provide a background to why the web 
and its technology are the way they are today. 
The web was invented by Berners-Lee to solve 
a real problem that he and his colleagues at 
CERN 
were experiencing namely, document sharing. They had a 
large number of documents in various locations and in 
different formats. Each required understanding of 
concepts that were explained in other documents. Many 
were works in progress, being developed by multiple 
authors. Berners-Lee realised that a techology existed 
which could greatly ease the situation, it was 
Hypertext. 
Hypertext had been around in various forms for many years, 
in fact the idea pre-dated the inventionof the modern computer!
There were several Hypertext solutions available on 
computers when Berners-Lee studied the problem, but 
they were either expensive and proprietary or only 
capable of running on a single computer. Berners-Lee's 
big contribution was to take the idea and put it on 
a network. This was what enabled the collaboration of 
many workers at once and the access to many diversely 
located documents. By making the network access 
transparent to the user it was as if the library 
was one gigantic document all cross-linked and seamlessly 
joined together, truly a world wide web of information.

Hypertext, HTML and static content

Berners-Lee had already built a type of hypertext 
system and he had experience with the internet so it 
was fairly natural for him to take these two ideas 
and join them together. In doing so he invented 
several component parts which together form the web.
The Hypertext concept required a mechanism for 
linking documents together, and so Berners-Lee invented 
a text formatting, or markup, system which he 
called Hyper Text Markup Language (HTML) based on an 
existing standard called Standard Generalised Markup 
Language (SGML). All web pages are written in HTML, 
either by a human author or by a computer program. 
Web browsers display their pages by interpreting 
the HTML markup tags and presenting the formatted 
content. This is not the place to try and teach HTML, so
if you don't already know how to create simple HTML 
documents then I suggest you find a good reference 
or tutorial, like the one 
here.

Having defined a markup language Berners-Lee 
could now create basic hypertext documents, like 
this tutorial. The pages could be formatted, 
images inserted and links to other documents
created. So far no networking is involved. The 
next step was to make these documents accessible 
over the network and to do that required the 
definition of a standard address format for 
content. This is the now ubiquitous Uniform 
Resource Locator or URL. The first part of 
a URL identifies the protocol to be used, usually 
http for the web. The next part uses 
standard internet naming to identify a server 
(and optional port, the default being 80) 
and the final part is the logical location of 
the content on the server. I say logical because, 
although the specification looks like an absolute 
directory path in Unix, it is in fact relative to
some fixed location known to the server, and indeed 
may not be a real location at all, since the server 
may translate the location into an application 
invokation or other form of data source. So if 
we look at the full URL of this page it is:



protocolIP addressportlocation


http://www.freenetpages.co.uk
:80/hp/alan.gauld/tutwebc.htm




One problem with the static hypertext content that 
this scheme provided was that it was read-only. There 
was no way to interact with the content, nor 
indeed could the content be easily modified. 
Berners-Lee wanted more, he wanted the ability 
to interact with the co

Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Kent Johnson
Alan Gauld wrote:
> 
> "Switanek, Nick" <[EMAIL PROTECTED]> wrote
> 
>> Please let us know when you have a draft of your tutorial on Beautiful
>> Soup and such. I'd be eager to have a look!
> 
> Here is the current draft, the concepts bits are all there  (nothing
> on Beautiful Soup as yet) but the example is giving me some headaches
> so it could change significantly over the next weeks. But early feedback
> is always welcome!

FWIW most real-world HTML parsers (including Beautiful Soup) seem to be 
based directly on SMTPlib, not htmllib or HTMLParser.

On a lawyerly note, I think your Google example violates Google's terms 
of service which prohibits any automated access.
http://www.google.com/accounts/TOS

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Tim Golden
Kent Johnson wrote:
> FWIW most real-world HTML parsers (including Beautiful Soup) seem to be 
> based directly on SMTPlib, not htmllib or HTMLParser.

I'm assuming you mean sgmllib here?

TJG
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Kent Johnson
Tim Golden wrote:
> Kent Johnson wrote:
>> FWIW most real-world HTML parsers (including Beautiful Soup) seem to 
>> be based directly on SMTPlib, not htmllib or HTMLParser.
> 
> I'm assuming you mean sgmllib here?

:-) yes, I mean sgmllib.SGMLParser

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Alan Gauld
"Kent Johnson" <[EMAIL PROTECTED]> wrote

> On a lawyerly note, I think your Google example violates Google's 
> terms
> of service which prohibits any automated access.
> http://www.google.com/accounts/TOS

Thanks for pointing that out Kent.

It probably explains why they send me a Restricted HTTP error.
I was going to try fooling them by messing with the http headers
but I'll find a friendlier web site... The reason for trying to use
Google was that they do offer an XML/RPC route in and I
was intending to go on to show how much easier a proper
API was.

Oh well, another bright idea bites the dust.

Alan G.

PS I didn't actually intend to send the draft to the group
but hit ReplyAll out of habit. It was only meant to go to
Nick... But in this case it's probably as well I did!



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Alan Gauld
"Kent Johnson" <[EMAIL PROTECTED]> wrote in

> FWIW most real-world HTML parsers (including Beautiful Soup) seem to 
> be
> based directly on SMTPlib, not htmllib or HTMLParser.

Yes, I noticed that, although htmllib is itself based on sgmllib...
And it has a better event based parsing model but unfortunately
it doesn't throw errors when you get an http error back,
which makes HTMLParser much more user friendly for
beginners...

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Alan Gauld

"Alan Gauld" <[EMAIL PROTECTED]> wrote

> it doesn't throw errors when you get an http error back,

Oops, confusing myself here.
Its urllib2 that throws errors and nothing to do with HTMLParser.
The advantage of HTMLParser is the lack of a need for a 
formatter and writer object.

Sorry for any confusion.

Alan G

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] screen scraping web-based email (Alan Gauld)

2007-04-19 Thread Kent Johnson
Alan Gauld wrote:
> "Alan Gauld" <[EMAIL PROTECTED]> wrote
> 
>> it doesn't throw errors when you get an http error back,
> 
> Oops, confusing myself here.
> Its urllib2 that throws errors and nothing to do with HTMLParser.
> The advantage of HTMLParser is the lack of a need for a 
> formatter and writer object.

sgmllib doesn't need a formatter either, that is added by htmllib.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Custom metaclass?

2007-04-19 Thread Michael Hannon
Greetings.  I've been looking at O'Reilly's "Python Cookbook", 2nd 
edition, just for my own edification.  In particular, I'm looking at 
chapter 6, "Object-Oriented Programming".

Recipe 6.3, "Restricting Attribute Setting", intends to solve the 
problem that,  by default, users can add and modify attributes of class 
instances, or even classes themselves, as in the following example:

 >>> class Foo(object): pass
 ...
 >>> f = Foo()
 >>> f.age = 42
 >>> f.age
 42
 >>> Foo.loc = 'Tralfamadore'
 >>> g = Foo()
 >>> g.loc
 'Tralfamadore'

The approach, in essence, is a fairly standard one: redefine the 
__setattr__ method to add some logic to enforce whatever restrictions 
you choose, but the details are a bit convoluted.  Copyright law 
probably prohibits me from posting the entire recipe, but here's the 
piece that leads to my question (see below):

class NoNewAttrs(object):
 """ subclasses of NoNewAttrs inhibit addition of new attributes,
 while allowing existing attributed to be set to new values.
 """
 # block the addition new attributes to instances of this class
 __setattr__ = no_new_attributes(object.__setattr__)
 class __metaclass__(type):
 "simple custom metaclass to block adding new attrs to this class"
 __setattr__ = no_new_attributes(type.__setattr__)

(Beware line breaks introduced by email software.)

Finally, my question: can somebody enlighten me as to how and why the 
"custom metaclass",

 class __metaclass__(type):

does something useful?

Thanks.

- Mike
-- 
Michael Hannonmailto:[EMAIL PROTECTED]
Dept. of Physics  530.752.4966
University of California  530.752.4717 FAX
Davis, CA 95616-8677
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Custom metaclass?

2007-04-19 Thread Andrei
Michael Hannon  physics.ucdavis.edu> writes:

> The approach, in essence, is a fairly standard one: redefine the 
> __setattr__ method to add some logic to enforce whatever restrictions 
> you choose, but the details are a bit convoluted.  Copyright law 
> probably prohibits me from posting the entire recipe, but here's the 


Well, here's a dummy that simply ignores requests to add attributes, instead
printing a message about the attempt to the console, so we have a concrete
example to look at:

def no_new_attributes(*args, **kwargs):
print 'called ', args, kwargs
return no_new_attributes

class NoNewAttrs(object):
__setattr__ = no_new_attributes(object.__setattr__)
class __metaclass__(type):
__setattr__ = no_new_attributes(type.__setattr__)

nna = NoNewAttrs()
#NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
try:
print 'object nna.x =' + str(nna.x)
except:
print 'object nna.x doesn\'t exist'

NoNewAttrs.x = 5
try:
print 'class nna.x =', nna.x
except:
print 'class nna.x doesn\'t exist'

> Finally, my question: can somebody enlighten me as to how and why the 
> "custom metaclass",
> 
>  class __metaclass__(type):
> 
> does something useful?

A metaclass is to a class like a class is to an object. The way a class
customizes the behavior of an object, a metaclass customizes the behavior of a
class. It's all a bit mind-bending and I don't think I'm an expert on the
subject, but let's see how far we get.

Try running the example above with the  __metaclass__ code and without: you'll
see that if you leave it out, you can still add attributes to the class itself
(even though not to the object), so your console will say:

  object nna.x doesn't exist
  class nna.x = 5

If however you put the metaclass in, you'll get:

  object nna.x doesn't exist
  called  (, 'x', 5) {}
  class nna.x = class nna.x doesn't exist

Without the metaclass code, it would be trivial to work around the __setattr__
limitation. Just try uncommenting the line "NoNewAttrs.__setattr__ =
object.__setattr__". If you disabled the metaclass, you'll see that nna.x will
be set. If the metaclass is enabled, it will not be set.

This being Python, you can still work around all this metaclass safety by adding
using this code:

NoNewAttrs.__metaclass__.__setattr__ = type.__setattr__
NoNewAttrs.__setattr__ = object.__setattr__
nna.x = 5
print 'After reset: nna.x =', nna.x

Run this and you'll see it will have restored the attribute-setting
functionality even if it's theoretically blocked. I'm not sure there is a way to
absolutely completely stop users from adding attributes.


Yours,

Andrei

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor