Re: Accessors in Python (getters and setters)

2006-07-20 Thread Steve Holden
Dennis Lee Bieber wrote:
> On 19 Jul 2006 22:38:17 -0700, "mystilleef" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
> 
> 
>>permitted should be between an object and its mediator. Messages are
>>passed through the system via signals or events or established
>>protocols. What are the benefits? Well I can change the implementation
>>of any object at will without breaking the whole system. Or I can even
> 
> 
>   Python permits that using properties... But one doesn't have to code
> the properties from the get-go... Development can be done with direct
> attribute access, and if it is determined that some sort of conditioning
> logic is needed, it can be implemented WITHOUT CHANGING THE API.
> 
>   This IS an "established protocol" in Python.
> 
>>High coupling is bad. Exposing critical states of an object is bad. Any
>>decent computer science book will tell you that.
>>
> 
>   In Python, using, if needed, properties, this is transparent... The
> user of the object doesn't know, or need to know, if it is state or
> behavior -- all it sees is that it supplies a value for something,
> and/or retrieves a value for something.
> 
>>Obviously if I want to control access to an attribute, it means I don't
>>want it altered or I want to perform pre/post conditional computations
>>before/after the attribute is accessed. There's a reason it is called
>>access control.
>>
> 
>   Python properties support this, no need to have the user of the
> object explicitly call a getter or setter...
>  
> 
> 
>>changing states you never bothered to hide to begin with, then the
>>wisdom behind careful upfront planning begins to make sense.
>>
> 
>   If it isn't part of the documented API, it is the user's fault. That
> applies to all software...

I'm this thread represents proof tht you can lead a horse to water but 
you can't make him drink - especially when he thinks the water is 
Kool-Aid, and that attribute APIs can be abused in ways that 
method-based ones can't.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Steve Holden
mystilleef wrote:
[...]
> 
> I don't know it's your code not mine.
> 
> class Robust(object):
> 
>   def __init__(self):
>   # Arbitrarily changing this state to False will crash app or 
> will
>   # corrupt the whole event system.
>   self.__is_active = True
> 
>   def get_is_active(self):
>   return self.__is_active
> 
>   buffer_is_active = property(get_is_active, doc="True if buffer is
> editable")
> 
Let's ignore changes of state for the moment. The mystical difference 
that makes read access via

   some_robust.buffer_is_active()

acceptable and

   some_robust.__is_active

somehow dangerous (ignoring the fact that name_mangling will take place) 
is what?

>   def monitor_events(self):
>   # Only methods of this class can change __is_active.
>   # Add code to change __is_active here.
>   return
> 
I'm sure nobody would argue that if close synchronization between 
multiple attributes is required then write accessors are a bad idea. But 
using them unnecessarily just makes your code heavier, slower and less 
easy to maintain.

> See! I'm controlling access. Whee! And if one sober morning I want to
> change the name __is_active to __buffer_is_active, I won't have to hunt
> down 27000 lines of code to do it. Also a naive third party won't crash
> my system by changing Robust's state arbitrarily. Because in the real
> world when your program is buggy, you get bug reports, nasty emails
> among other forms of ridicule. And your supposed solution to my problem
> is me saying, "but...but...I told you not change is_active." Ha! And if
> you can't figure out why anyone would do this, then I'm not wasting my
> time here anymore. Someday you'll learn the hard way.
> 
It's way too late. My comments *are* based on engineering experience. 
One day you may realise that unnecessary complexity is a far bigger time 
waster than any imagined problems of direct attribute access. I suspect 
that if you are getting complaints if the nature you describe it's just 
because your software isn't that good.

> Thanks to the people who exposed me to Python's properties.
> 
> Bye
> 
Really? Promise? I fear we are arguing from different premises.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Depricated String Functions in Python

2006-07-20 Thread Steve Holden
Anoop wrote:
> Hi All
> 
> Can any one help me out with the various depricated string functions
> that is followed in Python.
> 
> For example how will be string.lower depricated.
> 
> As far as string.lower('PYTHON') is concerned it is depricated as
> 'PYTHON'.lower(). Both of them would return an output : >>> python
> 
> Thanks for your inputs
> 
I wonder if this isn't just an English problem: the fact that the 
functions of the string module is depracated just means that you are 
encouraged to use the string objects' methods instead, as the string 
module is likely to be removed at some time in the future.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: using names before they're defined

2006-07-20 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Steve Holden wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>I have a problem. I'm writing a simulation program with a number of
>>>mechanical components represented as objects. When I create instances
>>>of objects, I need to reference (link) each object to the objects
>>>upstream and downstream of it, i.e.
>>>
>>>supply = supply()
>>>compressor = compressor(downstream=combustor, upstream=supply)
>>>combuster = combuster(downstream=turbine, upstream=compressor)
>>>etc.
>>>
>>>the problem with this is that I reference 'combustor' before is it
>>>created. If I swap the 2nd and 3rd lines I get the same problem
>>>(compressor is referenced before creation).
>>>
>>>
>>>aargh!!! any ideas on getting around this?
>>>
>>
>>Yes. You are building a generic data structure, so you shouldn't really
>>be trying to store individual objects in variables like that. You need a
>>data structure that's appropriate to your problem.
>>
>>For example, you could consider storing them in a list, so you have
>>
>>components = [supply(), compressor(), combuster()]
>>
>>Then components[n] is upstream of components[n-1] and downstream of
>>components[n+1].
> 
> 
> Unfortunately, if he wanted to make the topology more complicated, for
> instance having two components downstream, it would be much more
> cumbersome to inherit the list object and implement this.
> 
I quite agree. That was why I began with "for example".
> 
>>In short, your thinking about data representation might need to become a
>>little more sophisticated.
> 
> 
> That sounds a little arrogant. sorry!
> 
Hmm, maybe it does, in which case I apologise retrospectively. But all 
the more appropriate suggestions have definitely been pointing that way.

Circuit design is a complex problem. I was merely trying to indicate 
that the naive approach was unlikely to succeed. Sure enough, a few 
posts later the OP admitted that there needed to be sub-chains for 
sub-circuits, and so on.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: New to threads. How do they work?

2006-07-20 Thread Dermot Doran
Hi 
 
I think the answer to your last question is that the threading module provides a high level interface (i.e. easier to  use) to the thread module.  The thread module is very low-level.  Any threaded python scripts I have written (not expert) have used the threading module which is, in my opinion, a very clean easy to use module.  Just takes a bit of hacking with to get used to.

 
Cheers!!
 
Dermot. 
On 19 Jul 2006 23:53:22 -0700, gel <[EMAIL PROTECTED]> wrote:
Dennis Lee Bieber wrote:> On 19 Jul 2006 19:08:12 -0700, "gel" <
[EMAIL PROTECTED]> declaimed the> following in comp.lang.python:>> > import thread> >>   Step one... Skip the thread module and use threading module instead.>> > def create():
> >> > pythoncom.CoInitialize()> > c = wmi.WMI()> > while 1 :> >> > print "watching creation"> > watcher = 
c.watch_for(notification_type="Creation",> > wmi_class="Win32_Process", delay_secs=1)>>   I don't know WMI, but is that delay a real sleep operation, or a> polling loop?
>>   And either could be a problem if they hold the GIL -- preventing> anything else from running until they return...>> >> > thread.start_new_thread(create(),())> > 
thread.start_new_thread(delete(),())>>   At the very least, I suggest commenting out the COM and WMI calls --> test threads that ONLY print output and do a time.sleep(1). That should> be sufficient to see if the threads themselves are being started.
> -->   WulfraedDennis Lee Bieber   KD6MOG>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/>   (Bestiaria Support Staff:   [EMAIL PROTECTED]
)>   HTTP://www.bestiaria.com/Thanks alot for your help.  I had tried using threading with adifferent setup in the function side but did not get success. I think
that I have winner now.  Thanks again.  What follows is the what I haveworking so far.  And another question why do you prefer to us threadingand thread?import wmiimport pythoncomimport threading
def create():   pythoncom.CoInitialize()   c = wmi.WMI()   while 1 :   print "watching creation"   watcher = c.watch_for(notification_type="Creation",
wmi_class="Win32_Process", delay_secs=1)   print watcher()def delete():   pythoncom.CoInitialize()   d = wmi.WMI()   while 1 :   print "watching deletion"
   watcher = d.watch_for(notification_type="Deletion",wmi_class="Win32_Process", delay_secs=1)   print watcher()import threadingthreading.Thread(target=create).start()
threading.Thread(target=delete).start()Cheers--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Getting and Setting Cookies

2006-07-20 Thread Vlad Dogaru
John J. Lee wrote:
> "Vlad Dogaru" <[EMAIL PROTECTED]> writes:
> [...]
> > I am trying to write a simple login script. I understand (or rather I
> > think I understand) how to set a cookie with the Cookie module. My
> > problem is getting the cookies that are currently set. How can I do
> > that?
>
> You still haven't explicitly said that you're writing server-side
> code.  If you are:
>
> IIRC, you .load() it from the HTTP header value, then you use it as a
> mapping (though, oddly, that seems undocumented, except in the
> "Example" section of the docs).  A working CGI-based example (written
> in a rather retro style for ease of deployment):
>
> http://codespeak.net/svn/wwwsearch/ClientCookie/trunk/cookietest.cgi
>
>
> If you want to iterate over all cookies using module Cookie (that
> script does not), use .keys(), .values() or .items() on your
> SimpleCookie instance (it's also a little odd that instances of class
> SimpleCookie do not represent a single cookie, but a collection of
> cookies).

That's pretty much what I was trying to find out. Thanks for the
pointer.

Vlad

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


Re: Coding style

2006-07-20 Thread Antoon Pardon
On 2006-07-19, Georg Brandl <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>
>>> Other than in PHP, Python has clear rules when an object of a builtin type
>>> is considered false (i.e. when it's empty). So why not take advantage of
>>> this?
>> 
>> Because it doesn't always do what I want.
>> 
>> I once had a producer consumer code. When the client asked whether new
>> items were available the function could return three different values
>> 
>>   1) a list with items, to be consumed
>>   2) an empty list (meaning there were no items available for the
>> moment but there could be in the future
>>   3) None (meaning the producer was done)
>> 
>> Just testing for the truth value of the returned result in order
>> to see whether the client should continue or not would often
>> have made the client exit prematurely.
>>
>> IME such cases where testing for the truth value of an object
>> don't give the expected result, happen often enough to make me
>> carefully think about what I want to test for and then explicitly
>> do so.
>
> You're right, carefully thinking is always a good thing. Not using a
> language feature just because it would fail in another case is not.

I would say the opposite is just as true. Using a language feature
just because it happens to give the right answer, is not a good thing.
You don't know how your code will evolve and my experience is that the
lesser you use this feature, the lesser the chance you will have
to track a nasty bug later.

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


Re: mysqldb problem

2006-07-20 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, liupei
wrote:

> when I set mysql some fields collate utf8_bin, and then fetch these
> fields is array.array,not the string I expected

Can you post some example code?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions to anyone who uses wxPython

2006-07-20 Thread Dermot Doran
Hi 
 
the "wxPython in Action" provides a very good explanation as to how to handle this sort of problem using a combination of pure Python threads and the wx.CallAfter function.  Also if you want more help on this you can join the wxPython mailing list via 
www.wxpython.org.
 
Here is a small example of what I'm talking about that uses a Queue object to get a background thread to await work from the main gui thread.  Note it is VERY important that all GUI updates are performed by the main thread in a wxPython program.

 
import wximport threadingimport Queue
class WorkerThread(threading.Thread):   def __init__(self, callBack):  threading.Thread.__init__(self)  self.callBack = callBack  self.work_queue = Queue.Queue()  self.setDaemon(True)  def run(self):
   wx.CallAfter(self.callBack, "Thread starting up...")  work_to_be_done = Truewhile work_to_be_done:   req = self.work_queue.get(True)   # Go and perform some long lasting task here!
   wx.CallAfter(self.callBack, "Sorry I was kind of busy just now!") def helloThere(self):   self.work_queue.put_nowait("This could be an object")  class MyFrame(
wx.Frame):  def __init__(self):  wx.Frame.__init__(self, None, -1, "Testing wxCallback and Python threads")self.worker_thread = WorkerThread(self.logMessage)panel = wx.Panel(self)
  test_btn = wx.Button(panel, -1, "Hello!")  self.log = wx.TextCtrl(panel, -1, "", style=wx.TE_MULTILINE|wx.TE_RICH2|wx.TE_READONLY)sizer = wx.BoxSizer(wx.VERTICAL)  sizer.Add(self.log
, 1, wx.EXPAND|wx.ALL, 5)  sizer.Add(test_btn, 0, wx.ALIGN_CENTER_HORIZONTAL)  panel.SetSizer(sizer)self.Bind(wx.EVT_BUTTON, self.onTestBtn, test_btn)  self.Bind(wx.EVT_CLOSE, self.onCloseWindow)

  self.worker_thread.start()   def onTestBtn(self, evt):  self.worker_thread.helloThere() def onCloseWindow(self, evt):  self.Destroy() def logMessage(self, msg):  self.log.AppendText
(msg)  self.log.AppendText("\n") if __name__ == '__main__': app = wx.PySimpleApp() frm = MyFrame() frm.Show() app.MainLoop()
 
Cheers!!
 
Dermot.
 
On 19 Jul 2006 22:52:09 -0700, Frank Millman <[EMAIL PROTECTED]> wrote:
damacy wrote:> hello. i'm using wxPython as my GUI package and whenever my program> executes a long process which takes at least 2 or 3 seconds, the user
> interface gets corrupted while executing the progrocess during the> period.>> i have tried the following lines of code...>> frame = mainwindow(None, -1, 'my program')> ...
> ...> frame.UpdateWindowUI()>> and it did not make any difference at all.>> could anyone help me?I don't really understand the question - what do you mean when you say
the user interface gets corrupted?Nevertheless, the following pointer may help -http://tinyurl.com/hj84lIt is an article in the wxPyWiki that discusses various ways of
handling longrunning tasks.HTHFrank Millman--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Depricated String Functions in Python

2006-07-20 Thread John Machin
On 20/07/2006 5:18 PM, Steve Holden wrote:
> Anoop wrote:
>> Hi All
>>
>> Can any one help me out with the various depricated string functions
>> that is followed in Python.
>>
>> For example how will be string.lower depricated.
>>
>> As far as string.lower('PYTHON') is concerned it is depricated as
>> 'PYTHON'.lower(). Both of them would return an output : >>> python
>>
>> Thanks for your inputs
>>
> I wonder if this isn't just an English problem: the fact that the 
> functions of the string module is depracated 

"depracated"? "functions ... is"? Yup, sure looks like an English 
problem to me :-)

Perhaps the docs should use simpler words like "outdated" or "not 
preferred" or such-like instead of "depr*e*cated".

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


Re: access to submodules

2006-07-20 Thread TG
okay, thanks everyone. this is much clearer now.

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


Re: Coding style

2006-07-20 Thread Antoon Pardon
On 2006-07-19, Donn Cave <[EMAIL PROTECTED]> wrote:
> In article <[EMAIL PROTECTED]>,
>  Georg Brandl <[EMAIL PROTECTED]> wrote:
>> Lawrence D'Oliveiro wrote:
>
>> > One of my rules is, always program like the language actually has a Boolean
>> > type, even if it doesn't. That means, never assume that arbitrary values
>> > can be interpreted as true or false, always put in an explicit comparison
>> > if necessary so it's obvious the expression is a Boolean.
>> 
>> You can do that, but it's not considered Pythonic. And it might be 
>> ineffective.
>> 
>> Other than in PHP, Python has clear rules when an object of a builtin type
>> is considered false (i.e. when it's empty). So why not take advantage of
>> this?
>
> I don't know whether she would welcome this or not, but here
> I provide an archive link to a classic post by Laura Creighton
> on this matter:
>
> http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360
>
> It's lengthy but very readable, and for me it has that quality of
> exposition where you feel at first reading as though you had
> already known all that -- even if you really hadn't.

Well for me it wasn't, I don't agree with it at all.

IMO, whether something is to be considered "True" or "False"
is application dependent. There are cases where I would
consider an empty sequence as True, because a sequence in
itself would mean, continue and the members would be
the current available elements to be processed.

Nothing is IMO not specific enough and doesn't make
the disctinction between nothing (temporarily) now
and nothing more (for ever).

That is why I think the distinction between True and
False is more usefull than the distinction between
nothing and something.

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


Re: Depricated String Functions in Python

2006-07-20 Thread Steve Holden
John Machin wrote:
> On 20/07/2006 5:18 PM, Steve Holden wrote:
> 
>>Anoop wrote:
>>
>>>Hi All
>>>
>>>Can any one help me out with the various depricated string functions
>>>that is followed in Python.
>>>
>>>For example how will be string.lower depricated.
>>>
>>>As far as string.lower('PYTHON') is concerned it is depricated as
>>>'PYTHON'.lower(). Both of them would return an output : >>> python
>>>
>>>Thanks for your inputs
>>>
>>
>>I wonder if this isn't just an English problem: the fact that the 
>>functions of the string module is depracated 
> 
> 
> "depracated"? "functions ... is"? Yup, sure looks like an English 
> problem to me :-)
> 
Nobody likes a smartarse :-)

> Perhaps the docs should use simpler words like "outdated" or "not 
> preferred" or such-like instead of "depr*e*cated".
> 
That probably wouldn't be a bad idea. Please note, however, that even if 
the documentation spelled everything correctly I would doubtless 
continue to mangle the spellings through typos.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: restricted environment

2006-07-20 Thread Gabriele *darkbard* Farina

Paul Rubin wrote:
> "Gabriele *darkbard* Farina" <[EMAIL PROTECTED]> writes:
> > Using a separate interpreter could be a solution, but restarting any
> > time the interpreter give me too much overhead and the application will
> > work as slow as a CGI app even if it runs using FastCGI.
>
> How many users are you talking about?  Can you have a separate FastCGI
> server for each one, running continuously?

I could be the last solution, but I'd like to understand if a can use
only one FastCGI server to handle all the scripts that need to run.
This is just to speed up a bit the system, making it possible to share
resources among applications.

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


Re: CSV with comments

2006-07-20 Thread GinTon
and which method is the best, Daniel's generator or the subclass?

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


Re: restricted environment

2006-07-20 Thread Gabriele *darkbard* Farina

faulkner wrote:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496746
> When you think of modifying the interpreter, think of the compiler
> module.

This seems a good solutions. Does it works correctly and safely ?

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


Re: Warning when new attributes are added to classes at run time

2006-07-20 Thread Bruno Desthuilliers
Matthew Wilson wrote:
> I sometimes inadvertently create a new attribute on an object rather
> update a value bound to an existing attribute.  For example:
> 
(snip)
> 
> I meant to update c.a but I created a new c.A.  I make this mistake
> probably hourly.
> 
> I suspect adding attributes at run time can be a beautiful thing, but in
> this particular instance, I'm only using this feature to hurt myself.

See other posts in this thread for some other possible solutions.

> I wrote a simple class that will warn me when I make this mistake in the
> future:
> 
> import warnings
> 
> class C(object):
> 
> warn_on_new_attributes = True
> 
> standard_attributes = []
> 
> def __setattr__(self, name, value):
> 
> if self.warn_on_new_attributes \
> and name is not 'warn_on_new_attributes' \
> and name not in self.standard_attributes:
> 
> warnings.warn("%s has no standard attribute %s."
>   % (self.__class__.__name__, name))
> 
> 
> self.__dict__[name] = value
Make it:
  object.__setattr__(self, name, value)

Your approach will lead to strange results if you mix it with properties
or other descriptors...


> class C1(C):
> 
> standard_attributes = ['a1', 'a2']

DRY violation here. And a potential problem with inheritance (as always
with class attributes).

(snip)


-- 
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 names before they're defined

2006-07-20 Thread Iain King

[EMAIL PROTECTED] wrote:
> Iain, thanks - very helpful.
>
> Really I'm trying to write a simulation program that goes through a
> number of objects that are linked to one another and does calculations
> at each object. The calculations might be backwards or fowards (i.e.
> starting at the supply or demand ends of the system and then working
> through the objects). And also, I might have multiple objects linked to
> a single object (upstream or downstream) - e.g. compressor -- multiple
> combusters - turbine
>
> I like your idea of using something like a setStreams method to
> establish the linking. The streams do reflect each other, although
> having many-to-one and vice versa will complicate that. I have not
> quite got my head around having multiple links. In C++ I would be
> thinking about something like a linked-list but I'm not sure that's the
> right approach here.
>
> Dave

You don't need linked-lists : python has a list type built in.
Example:

class Component():

upstream = []
downstream = []

def addUpstream(self, c):
self.upstream.append(c)
if not self in c.downstream:
c.addDownstream(self)

def addDownstream(self, c):
self.downstream.append(c)
if not self in c.upstream:
c.addUpstream(self)

def remUpstream(self, c):
c.downstream.remove(self)
self.upstream.remove(c)

def remDownstream(self, c):
c.upstream.remove(self)
self.downstream.remove(c)

def cascadeDownTest(self):
print self
# this could run forever if you connect components in a circle:
for c in self.downstream:
c.cascadeDownTest() 

Iain

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


Re: Partial classes

2006-07-20 Thread Bruno Desthuilliers
Stefan Behnel wrote:
> Kay Schluehr wrote:
> 
>>What about letting your teammates editing certain data-structures in
>>different files ( physical modules ) but using them in a uniform way
>>and enable a single access point. If you have partial classes there is
>>no reason why your team has to share a large file where they have to
>>edit a single class but break the class into different parts and edit
>>the parts separately. No one has to care for including any module
>>because the CLR fits all partial classes together at compile time.
> 
> 
> I can't believe I always used version control systems for that use case if
> it's that easily solved with partial classes.

Collaborative work is only one of the needs solved by VCS.


-- 
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: Accessors in Python (getters and setters)

2006-07-20 Thread mystilleef
Steve Holden wrote:
> mystilleef wrote:
> [...]
> >
> > I don't know it's your code not mine.
> >
> > class Robust(object):
> >
> > def __init__(self):
> > # Arbitrarily changing this state to False will crash app or 
> > will
> > # corrupt the whole event system.
> > self.__is_active = True
> >
> > def get_is_active(self):
> > return self.__is_active
> >
> > buffer_is_active = property(get_is_active, doc="True if buffer is
> > editable")
> >
> Let's ignore changes of state for the moment. The mystical difference
> that makes read access via
>
>some_robust.buffer_is_active()
>

buffer_is_active is not a method, it's a property. So:

some_robust.buffer_is_active

is appropriate.

> acceptable and
>
>some_robust.__is_active
>
> somehow dangerous (ignoring the fact that name_mangling will take place)
> is what?
>

We can't ignore name mangling. That's an illegal statement in Python.
So it is less dangerous.

> > def monitor_events(self):
> > # Only methods of this class can change __is_active.
> > # Add code to change __is_active here.
> > return
> >
> I'm sure nobody would argue that if close synchronization between
> multiple attributes is required then write accessors are a bad idea. But
> using them unnecessarily just makes your code heavier, slower and less
> easy to maintain.
>

Ah, I broke my own rule. That method is supposed to be private too.
Meaning no one can change the state of the object except the object
itself. The code is below

def __monitor_event(self):
# Perform whatever needs to be done to change state
return

__monitor_event is not supposed to be a write accessor. My point was
show how you can change the state of an object internally without
needing external access to it. Since some people are surprisingly
claiming it is not possible.

> > See! I'm controlling access. Whee! And if one sober morning I want to
> > change the name __is_active to __buffer_is_active, I won't have to hunt
> > down 27000 lines of code to do it. Also a naive third party won't crash
> > my system by changing Robust's state arbitrarily. Because in the real
> > world when your program is buggy, you get bug reports, nasty emails
> > among other forms of ridicule. And your supposed solution to my problem
> > is me saying, "but...but...I told you not change is_active." Ha! And if
> > you can't figure out why anyone would do this, then I'm not wasting my
> > time here anymore. Someday you'll learn the hard way.
> >
> It's way too late. My comments *are* based on engineering experience.
> One day you may realise that unnecessary complexity is a far bigger time
> waster than any imagined problems of direct attribute access. I suspect
> that if you are getting complaints if the nature you describe it's just
> because your software isn't that good.
>

And mine are based on future engineering predictions? Okay, one day I
shall see the light.

> > Thanks to the people who exposed me to Python's properties.
> >
> > Bye
> >
> Really? Promise? I fear we are arguing from different premises.
>

Yes, we are. We have been since about the 5th post on this thread if
you haven't noticed.

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


Re: function v. method

2006-07-20 Thread Bruno Desthuilliers
danielx wrote:
> Bruno Desthuilliers wrote:
> 
>>danielx wrote:

(snip)
>>>which gets me thinking again about
>>>the stuff I self-censored. Since the dot syntax does something special
>>>and unexpected in my case,
>>
>>"unexpected" ? Did you ever wondered how the instance or class was
>>passed as first arg when doing method calls ?
> 
> 
> Not knowing what's going on during method calls is exactly what
> motivated me to post.

!-)

Ok, so now you have to read about descriptors, __getattribute__ and
__setattr__.

> 
>>>why not use some more dot-magic to implement
>>>privates?
>>
>>What for ? What makes you think we need language-inforced access
>>restriction ?
> 
> 
> I knew someone would bring this up.

Indeed.

> The motivation would not be to
> provide restriction, but to help maintain clean api's. If you intended
> for users to use only a subset of the methods in your class, why not
> help them learn your api by presenting the stuff they can use not along
> side the stuff they should not?
>
> Obviously, such things would be omitted from your docs, but users also
> learn by interacting with Python, which is really one of Python's great
> virtues. When supporting documents aren't sufficient to learn an api
> (I'm sure this never happens, so just humor me), you can always turn to
> interactive Python.

...and source code...

> This is exactly what it's there for. If nothing is
> hidden, a user could be easily mislead to believe he can use a method
> when he really shouldn't.

Single leading underscore means "implementation, don't touch or you're
on your own".


-- 
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: Detecting socket connection failure

2006-07-20 Thread Ben Sizer
[EMAIL PROTECTED] wrote:
> First, the proof that
> something is there and rejecting the connection (or is it that this
> thing actually accepts the connection and then drops it?)...

Yes, it accepts it and then drops it, or perhaps drops it after
receiving some data? It's not a failed or rejected connection from a
socket point of view, however.

> In [4]: remote.recv(200)
> Out[4]: ''

Assuming I understand the socket module, given how under-documented it
is, I assume this means the socket has now been closed.

> How do I detect this case?  The recv may
> really not have any data for a long time, so a recv of no bytes is not
> a way to test the connection status.

You already received zero bytes the first time, which I believe means
the socket is closed, and you shouldn't pass it to select a second
time. You should never get zero bytes unless the socket is closed,
otherwise it would just sit there and wait until it has some bytes to
return to you. Select doesn't tell you that there's data waiting -
obviously it can't, as how would it handle the write case? - but in
fact tells you that the socket is 'ready', and operations upon it
should return immediately. And 'ready' in this case could well just
mean it's ready to tell you that it's not connected.

-- 
Ben Sizer

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


Re: Coding style

2006-07-20 Thread Antoon Pardon
On 2006-07-19, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 19 Jul 2006 12:27:39 GMT, Antoon Pardon <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>
>> 
>> I once had a producer consumer code. When the client asked whether new
>> items were available the function could return three different values
>> 
>>   1) a list with items, to be consumed
>>   2) an empty list (meaning there were no items available for the
>> moment but there could be in the future
>>   3) None (meaning the producer was done)
>>
>   You have a documented interface with a tri-state return... For this
> situation, you would need the explicit test... I'd probably end up with
> something like
>
> while True:
>   retrn = function()
>   if retrn is None:
>   break
>   elif retrn:
>   consume 

The problem is how people here react:

  Suppose I have the following kind of code:

while True:
  try:
if len(result) > 0:
  foo()
else
  bar()
  except TypeError:
break

This code makes the distinction between the three possibilities,
whether it is a good way or not I won't discuss, this is just
meant as an illustration.

Now I have a problem with the code between the if and else, so
I come to the newsgroup and post something like:

  I have a problem with the following kind of code, it seems
  to do blob, but I would have expected blib.

if len(result) > 0:
  foo()
else:
  ...


And before you know it someone will respond that I shouldn't
use
  
  if len(result) > 0:

but should just use:

  if result:


Which isn't at all helpfull with my original problem, but would
be wrong in the context where the code is actually used.

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


Re: how to know if socket is still connected

2006-07-20 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Grant Edwards wrote:

> If the server has closed the connection, then a recv() on the
> socket will return an empty string "", and a send() on the
> socket will raise an exception.

Would that still apply when trying to send an empty string?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-20 Thread Bruno Desthuilliers
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Bruno Desthuilliers
> wrote:
> 
> 
>>Lawrence D'Oliveiro wrote:
>>
>>>In message <[EMAIL PROTECTED]>, Bob Greschke
>>>wrote:
>>>
>>>
>>>
I'd go even one step further.  Turn it into English (or your favorite
non-computer language):

1. While list, pop.

2. While the length of the list is greater than 0, pop.

Which one makes more sense?  Guess which one I like.  CPU cycles be
damned.
:)
>>>
>>>
>>>One of my rules is, always program like the language actually has a
>>>Boolean type, even if it doesn't.
>>
>>Python has a boolean type.
> 
> 
> A _proper_ boolean type would _have_ to be used in conditionals.

Try using something that cannot be fed to bool() into a conditional.

> 
>>>That means, never assume that arbitrary values
>>>can be interpreted as true or false,
>>
>>There's nothing to assume, and nothing arbitrary in it.
>> It's all clearly
>>defined in whole letters in the language references.
> 
> 
> Not simply enough.

Then it's a documentation problem.

> 
>>>always put in an explicit comparison
>>>if necessary so it's obvious the expression is a Boolean.
>>
>>The fact that the expression is used in the context of a if statement is
>>clearly enough to denote a boolean expression.
> 
> 
> Which is an inconsistent use of the term "boolean" compared to your
> statement above that "Python has a boolean type", is it not?

No. It is not. A boolean expression is an expression you can pass to
bool().

> 
>>Explicitly testing against a boolean is uselessly redundant...
> 
> 
> Not sure this has anything with what I was saying.

You said:
"""
>>>always put in an explicit comparison
>>>if necessary so it's obvious the expression is a Boolean.
"""

Since the expression following an if will be handled as if passed to
bool() [1], adding a comparison to True will yield a strictly equivalent
result (True == True => True, False == True => False). From a boolean
logic POV, it's a no-op [2]. So it's useless and redundant.


[1] FWIW, it may be just how it works - I've not checked implementation.
Anyway you can easily verify by yourself that it works the same way.

[2] but it still requires extra work from the interpreter - without
changing anything to the result of the test.

FWIW, what would you rather use:

if  == True:
  return True
elif  == False:
  return False
else:
  raise "???"

or:

return bool()


-- 
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: how to know if socket is still connected

2006-07-20 Thread Steve Holden
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Grant Edwards wrote:
> 
> 
>>If the server has closed the connection, then a recv() on the
>>socket will return an empty string "", and a send() on the
>>socket will raise an exception.
> 
> 
> Would that still apply when trying to send an empty string?

Yes: sending an empty string demands no action on the server's part, as 
the receiver has already received it ... adding an empty string to 
whatever the sender currently has buffered does not require any state 
change on the sender's part.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Help Needed. Removing a Folder Problem

2006-07-20 Thread Kilicaslan Fatih
When I push a button to trigger the code:

def run(self, event):
cmd_out = self.A_com()
if App.runF != "":
os.mkdir('C:\copiedFiles')
  
for item in App.runF:
App.beCopied = str(item)
shutil.copy(App.beCopied,  
'C:\copiedFiles')
cmd = ' C:\copiedFiles\*.*' + cmd_out
os.system(cmd)
shutil.rmtree('C:\copiedFiles')
else:
tkMessageBox.showinfo("Window Text",
"Please Firstly Browse and Insert A File")


I encountered this error:

Traceback (most recent call last):
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345,
in __call__
return self.func(*args)
  File "C:\Python24\TkScripts\RCFolder.py", line 61,
in run
shutil.rmtree('C:\copiedFiles',
ignore_errors=False)# OLMADI!!!
  File "C:\Python24\lib\shutil.py", line 168, in
rmtree
onerror(os.remove, fullname, sys.exc_info())
  File "C:\Python24\lib\shutil.py", line 166, in
rmtree
os.remove(fullname)
OSError: [Errno 13] Permission denied:
'C:\\copiedFiles\\Analog.c'

1. What I want to do is to get the list of files I
inserted to a Listbox,
2. Creating a folder,(C:\copiedFiles)
3. Copying all of these files to this folder with the
same names,
4. Running  for all of the files in this folder,
5. Than removing this folder.

Can anyone enlighten me on this Error I have got and
how to solve it?

Regards


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Augument assignment versus regular assignment

2006-07-20 Thread Antoon Pardon
On 2006-07-19, Terry Reedy <[EMAIL PROTECTED]> wrote:
>
> "Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]

>> So IMV those preparation before the attachment, belong to
>> whatever the interpreter does before it actually attaches
>> an object to a name/slot.
>>
>> So the evaluation of the target is part of what is done by
>> STORE_SUBSCR or __setitem__.
>>
>> Now you can object to the fact that I have divided the work
>> within an opcode.
>
> But I won't.  The amount of duplication that can be factored out with 
> augmented assignment depends on the granularity of operations.

I can agree with that. But until now each time I tried to
suggest that the STORE_SUBSCR or __setitem__ are involved
in the evaluation of the target, I was told I shouldn't
look at things that way. 

> And the 
> granularity of operations depends on the interpreter.  Hence my claim that 
> the details are necessarily interpreter dependent.

Well my impression from reading the language reference is that
it suggests that a greater amount of duplication is factored out
than the granularity of the CPython implementation allows.

But since you already agreed that there is room for improvement
in the augmented assignment reference I will leave it at that.

I would like to thank everybody for their contributions, but I
think everything worth while has been said, so I will no longer
contribute to this thread.

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
mystilleef wrote:
> Bruno Desthuilliers wrote:
> 
>>mystilleef wrote:
>>
>>>Bruno Desthuilliers wrote:
>>>
>>>
mystilleef wrote:
>>
>>(snip)
>>
>>>Of course using setters for the sake of just using them is pointless.
>>
>>Indeed.
>>
>>
>>
>>
>>>The reason to use them is if pre-conditions or post-conditions need to
>>>be met. Or to control access to an objects states.
>>
>>Then why advocate *systematic* use of them ?
>>
>>(snip)
>
>I never advocated anything.

You advocated
"""
1). Make all attributes of a class private/protected .
2). If a "non-callable" attribute is going to be used outside a class,
think about making it a property and name the property well, because
you never know...
"""

>>>
>>>
>>>You use accessors when you need to control access to a data attribute.
>>
>>Indeed. And when you don't need too ? (the second 'o' is not a typo)
>>
> 
> 
> You make the attribute private/protected.

doh :(

Let's talk about psychorigid mindset...

> 
>>>That's not advocacy, that's common sense.
>>
>>I'm afraid we don't use the same definition of "common sense". Writing
>>useless code is not part of my definition of "common sense".
>>
>>(snip)
>>
>I agree. And I already told you I think in terms of state and behavior
>and not language dependent semantics.

Then why do you advise "(making) all attributes of a class
private/protected" and systematically using properties ?

>>>
>>>
>>>Because you don't want third parties illegimately tampering with an
>>>object's internal data and thus crashing your system?
>>
>>Let's try again...
>>
>>point 1 : there's *no* language-inforced access restriction in Python.
>>Just a *convention*.
>>
> 
> 
> Huh? What are properties for then?

To allow attribute syntax when you really have computation behind. Which
 1/ let you start with the simplest case (a simple attribute) and change
your mind latter
2/ offer the possibility to use an attribute syntax (instead of a method
call syntax) when it seems more natural.

> 
>>point 2 : so anyone *can* "illegimately tampering with an object's
>>internal data" at will.
>> 
> 
> And this is robust how?
> 

You can do just the same in Java or C++.

>>point 3 : anyway it's not *my* system that will then crash - but the
>>system of the one who "illegimately" played with my package's objects
>>internals. And as far as I'm concerned, it's none of my problem - they
>>were marked as implementation, so anyone playing with them is on it's
>>own. FWIW, I suspect that if someone want to muck with implementation,
>>he certainly has a good legitimate reason to do so, and will do her best
>>to not break anything. Else he's a complete idiot and there's no cure
>>for this.
>>
> 
> 
> You can't be serious. Please tell me you are joking.

I'm deadly serious and definitively not joking. There's no cure for
idiocy, and there's definitively nothing like an idiot-proof system.

> 
>>point 4 : since we have computed attributes, turning a "public data
>>attribute" (to use your idiom) into a "private/protected data attribute
>>with accessors" *without breaking the interface* is not even a non-brainer.
>>
>>Now, please, can you explain the difference between :
>>
>>class Complicated(object):
>>  def __init__(self, data):
>>self.data = data
>>  def _get_data(self):
>>return self._data
>>  def _set_data(self, data):
>>self._data = data
>>
>>and
>>
>>class Pragmatic(object):
>>  def __init__(self, data)
>>self.data = data
>>
>>
>>and find any *valid* reason to use the first solution instead of the
>>second ? ('that's what the book says' not being a valid reason).
>>
> 
> 
> I don't know it's your code not mine.

IOW : you're unable to find any valid reason to use the second solution
instead of the first (of course : there's none), but refuse to admit it.

> 
> class Robust(object):
> 
>   def __init__(self):
>   # Arbitrarily changing this state to False will crash app or 
> will
>   # corrupt the whole event system.
>   self.__is_active = True
> 
>   def get_is_active(self):
>   return self.__is_active
> 
>   buffer_is_active = property(get_is_active, doc="True if buffer is
> editable")
> 
>   def monitor_events(self):
>   # Only methods of this class can change __is_active.
>   # Add code to change __is_active here.
>   return

Yuck.

> See! I'm controlling access.

You are not controlling *anything*

r = Robust()
r._Robust__is_active = True

As I told you, there's no cure for idiocy.

> Whee! And if one sober morning I want to
> change the name __is_active to __buffer_is_active, I won't have to hunt
> down 27000 lines of code to do it. 

And what if you want to change 'buffer_is_active' to 'is_active' ?

> Also a naive third party won't crash
> my system by changing Robust's state arbitrarily.

Lol. cf above. And, may I repeat : y

Re: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
Dennis Lee Bieber wrote:
> On Wed, 19 Jul 2006 18:54:55 +0200, Bruno Desthuilliers
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
> 
> 
>>Indeed. And when you don't need too ? (the second 'o' is not a typo)
>>
> 
>   Pardon, but for the sense you intend, it should be:
> 
>   ... don't need, too?

Granted. Actually, it *was* a typo - but it happened to also make sens,
so I decided it was not a typo !-)

But I promise I'll be more carefull next time.

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


Bug? Certainly a new *behavior* from subprocess in 2.5 on Win32

2006-07-20 Thread Larry Hastings
I run the following script:
--
from subprocess import *
Popen("ls -l")
--
(yeah, I have ls.exe on Windows)

Under Python 2.4.2, this simply dumped the results of ls.exe to the
terminal--sorry, to the "command shell".

Under Python 2.5, both beta 1 and beta 2, it dumps the results to the
command shell, but *also* prints this:

Exception exceptions.AttributeError: "'NoneType' object has no
attribute 'append'" in > ignored

Calling Popen() with a stdout = subprocess.PIPE does not throw this
exception.

I vaguely intimate that this is a bug, though surely a minor one.

Cheers,


/larry/

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


Re: using names before they're defined

2006-07-20 Thread davehowey
Paddy,

thanks for your mail.

> In Digital electronics we have what are called netlists, (and also
> component lists)

yes, years back I did a 3rd year project on a 'logic simulator' which
used the kind of thing you are talking about. I think spice does as
well. Fortunately my problem is a little simpler, phew. [by the way, as
an aside, check out modelia/dymola for some really powerful simulation
stuff http://www.dynasim.se/ - it uses powerful symoblic algebra
algorithms to derive system equations and the solve them numerically]

> With a bit more effort you can create component and link factories
> that will name instances with the variable they are assigned to
> without having to put that information in twice.

sorry - could you explain a bit more? sounds interesting and also
brings me onto another question that has been bugging me, which is, if
I want to create components (as object instances) at run time (rather
than through a python code imported in), how do I do this? i.e. if I
hardcoded something like
turbine1 = turbine(...)
then python knows that turbine1 is a turbine. but if I had say some
kind of user interface and I want to create turbine1 (or suchlike) on
the fly, how do I actually do that? how do I create objects after run
time?

Dave

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Gerhard Fiedler
On 2006-07-20 04:15:33, Steve Holden wrote:

> mystilleef wrote:
> [...]
>> 
>> I don't know it's your code not mine.
>> 
>> class Robust(object):
>> 
>>  def __init__(self):
>>  # Arbitrarily changing this state to False will crash app or 
>> will
>>  # corrupt the whole event system.
>>  self.__is_active = True
>> 
>>  def get_is_active(self):
>>  return self.__is_active
>> 
>>  buffer_is_active = property(get_is_active, doc="True if buffer is
>> editable")
>> 
> Let's ignore changes of state for the moment. The mystical difference 
> that makes read access via
> 
>some_robust.buffer_is_active()
> 
> acceptable and
> 
>some_robust.__is_active
> 
> somehow dangerous (ignoring the fact that name_mangling will take place) 
> is what?
> 
>>  def monitor_events(self):
>>  # Only methods of this class can change __is_active.
>>  # Add code to change __is_active here.
>>  return
>> 
> I'm sure nobody would argue that if close synchronization between 
> multiple attributes is required then write accessors are a bad idea. But 
> using them unnecessarily just makes your code heavier, slower and less 
> easy to maintain.

I'm not sure, but there's one thing that has a potential to be the real
issue: what's the common way to create a property that is read-write for
the implementation and "read-only" for the interface? It seems to me that
this is what mystilleef is trying to do.

I know that Python doesn't really provide access control. But so far I've
learned that a leading underscore says "I'm implementation, don't touch me
unless you know what you're doing". So I imagine that I browse through code
and look for leading underscores for non-local object attributes, to spot
troublespots. So I imagine that using such attributes as "read-only"
interface elements may not be a good idea, because then you not only have
to spot them in outside code, you always also have to check whether that's
a read or a write access (to know whether it's something potentially
dangerous or not). I also don't know how you could use the computed
attribute methods to do different things for access from the outside and
from the inside (of the object).

So... _is_active is considered implementation. Don't mess with me, it says.
But the users of the class need access to it: read access. Do you just say
"read access isn't changing anything, so just use _is_active"? The
disadvantage is that the outside code is sprinkled with accesses to
attributes with leading underscores, which I assume looks kind of scary. Or
do you rename _is_active to is_active, indicating that access to it is
indeed allowed? Then you would have to do something in the attribute
accessors to control the write access -- because that still isn't a good
idea. But I need want to be able to write to it from inside the class...
but how, if the attribute accessor is preventing that? Is there a local
override for that? I'm sure there is... but is it a common technique?

I may have not used the correct terminology for everything, but I think
it's possible to parse that :)

And maybe that helps putting this to rest and make everybody happy :)

Gerhard

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Steve Holden
Gerhard Fiedler wrote:
> On 2006-07-20 04:15:33, Steve Holden wrote:
> 
> 
>>mystilleef wrote:
>>[...]
>>
>>>I don't know it's your code not mine.
>>>
>>>class Robust(object):
>>>
>>> def __init__(self):
>>> # Arbitrarily changing this state to False will crash app or 
>>> will
>>> # corrupt the whole event system.
>>> self.__is_active = True
>>>
>>> def get_is_active(self):
>>> return self.__is_active
>>>
>>> buffer_is_active = property(get_is_active, doc="True if buffer is
>>>editable")
>>>
>>
>>Let's ignore changes of state for the moment. The mystical difference 
>>that makes read access via
>>
>>   some_robust.buffer_is_active()
>>
>>acceptable and
>>
>>   some_robust.__is_active
>>
>>somehow dangerous (ignoring the fact that name_mangling will take place) 
>>is what?
>>
>>
>>> def monitor_events(self):
>>> # Only methods of this class can change __is_active.
>>> # Add code to change __is_active here.
>>> return
>>>
>>
>>I'm sure nobody would argue that if close synchronization between 
>>multiple attributes is required then write accessors are a bad idea. But 
>>using them unnecessarily just makes your code heavier, slower and less 
>>easy to maintain.
> 
> 
> I'm not sure, but there's one thing that has a potential to be the real
> issue: what's the common way to create a property that is read-write for
> the implementation and "read-only" for the interface? It seems to me that
> this is what mystilleef is trying to do.
> 
> I know that Python doesn't really provide access control. But so far I've
> learned that a leading underscore says "I'm implementation, don't touch me
> unless you know what you're doing". So I imagine that I browse through code
> and look for leading underscores for non-local object attributes, to spot
> troublespots. So I imagine that using such attributes as "read-only"
> interface elements may not be a good idea, because then you not only have
> to spot them in outside code, you always also have to check whether that's
> a read or a write access (to know whether it's something potentially
> dangerous or not). I also don't know how you could use the computed
> attribute methods to do different things for access from the outside and
> from the inside (of the object).
> 
> So... _is_active is considered implementation. Don't mess with me, it says.
> But the users of the class need access to it: read access. Do you just say
> "read access isn't changing anything, so just use _is_active"? The
> disadvantage is that the outside code is sprinkled with accesses to
> attributes with leading underscores, which I assume looks kind of scary. Or
> do you rename _is_active to is_active, indicating that access to it is
> indeed allowed? Then you would have to do something in the attribute
> accessors to control the write access -- because that still isn't a good
> idea. But I need want to be able to write to it from inside the class...
> but how, if the attribute accessor is preventing that? Is there a local
> override for that? I'm sure there is... but is it a common technique?
> 
> I may have not used the correct terminology for everything, but I think
> it's possible to parse that :)
> 
> And maybe that helps putting this to rest and make everybody happy :)
> 
The logical way would seem to be to provide a read property is_active() 
only. The implementation can access the _is_active instance variable 
that the property exposes, writing it as necessary. If the accessor 
gives direct access to the variable there's no need to use it inside the 
object implementation. Or have I misunderstood your requirements?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: wxPython: wxStaticBitmap and large images

2006-07-20 Thread Will McGugan

Roger Miller wrote:
> I have a WxPython app that displays images that are typically around
> 600x600 pixels. I use a wxStaticBitmap, which appears to work fine on
> Windows XP. However the documentation states that a StaticBitmap "...
> is meant for display of the small icons in the dialog boxes and is not
> meant to be a general purpose image display control. In particular,
> under Windows 9x the size of bitmap is limited to 64*64 pixels and thus
> you should use your own control if you want to display larger images
> portably".
>
> Assuming that I don't care about Windows 9X, should I be worried? Is
> there a better way to display images, hopefully without diving down
> into the device context level?

I would just roll your own control. Its not too complicated. Just
derive from a wxWindow and in your WM_PAINT hander, draw your bitmap.

An alternative may be to place your bitmap in html and use a
wxHtmlWindow to display it.

Will McGugan
--
http://www.willmcgugan.com

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Diez B. Roggisch
> Lol. I actually did *un*learn the hard way.
> 
> Mystilleef, I've started programing 17 years ago, and have done it
> professionnaly for almost 10 years now. I do not pretend to be a good
> programmer, but please believe that I do know my job. I've read the Book
> too, I've tried applying it blindly, then I used my brain. Once you
> understand the real reasons behind a "rule", you also understand when
> and how to apply or not apply it.


To second that:

"""
A Foolish Consistency is the Hobgoblin of Little Minds
"""

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


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


Re: using names before they're defined

2006-07-20 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
(snip)
> brings me onto another question that has been bugging me, which is, if
> I want to create components (as object instances) at run time (rather
> than through a python code imported in), how do I do this? i.e. if I
> hardcoded something like
> turbine1 = turbine(...)
> then python knows that turbine1 is a turbine. but if I had say some
> kind of user interface and I want to create turbine1 (or suchlike) on
> the fly, how do I actually do that? how do I create objects after run
> time?

Q&D possible solution, no error handling, etc
...just so you get an idea

# schema generated by a GUI
# or directly written in a .py config file
# or whatever

schema = {'turbine1': {'class': 'Turbine',
   'upstream' : ('frobnicator2',),
   'downstream' : () # nothing,
   },
  'frobnicator2' : {'class' : 'Frobnicator',
'upstream' : (),
'downstream' : ('frobnicator2',),
   },
 }

# code:

def get_class_by_name(name):
  return globals()[name]

def chain_from_schema(schema):
  objects = {}
  for name, desc in schema:
 klass =  get_class_by_name(desc['class'])
 objects[name] = klass()
  for name, desc in schema:
target = objects[name]
ups = [objects[upname] for upname in desc['upstream']]
downs = [objects[downname] for downname in desc['downstream']]
target.links(upstream=ups, downstream=downs)
  return objects


-- 
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: Recursive function returning a list

2006-07-20 Thread Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
> Bruno Desthuilliers wrote:
> 
>>[EMAIL PROTECTED] wrote:
> 
> [...]
> 
>>>Sorry, but I kinda agree with Boris here.
>>
>>On what ?
> 
> 
> On the argument that you are (implicitly?) disagreeing with him 

it's getting messy - too much level of indirection !-)

> on,
> obviously. That the OP problem is not definitely the default values
> question. 

Ok, I do agree that it's only *one* part of the problem - the other
(implied) being "what other possible solutions".

> As you say:
> 
> 
If the OP has other reasons to want to use an accumulator based solution
- which we don't know - then the possibility to use a default value is
important.
> 
> 
> My emphasis is on "we don't know".

At least we do agree on something !-)

> 
>>>Not that I am anybody here,
>>>really.
>>
>>Err... Are you you at least ?-)
>>
> 
> 
> I am. 

Great.

> Thanks for your concern:)

!-)

> 
(snip)
>>>I don't think there is actually a FAQ
>>>saying you must use the accumulator solution.
>>
>>Did I say so ? The FAQ I mention is about default values evaluation, and
>>it's the problem the OP was facing. Please re-read my post more carefully.
>>
> 
> 
> Actually, I have read your post right first time. And I do know you
> didn't say that (a FAQ for accumulators). I raised it just in case.
> What I don't agree with is that it is not the problem the OP was
> facing. The discussion was: is the real problem the default values
> problem, which he already got a solution for. Or was the real problem
> the list returning recursion problem, for which he (or subsequent
> google searchers, who are more likely to come to this thread after
> searching for "Recursive function returning a list") may benefit from a
> generator approach.

agreed.

(snip)

> Thanks for the function, though I regard it as kind of trivial for the
> level of discussion that we are having now. The problem solved by the
> accumulator is _not_ the building of a list recursively. It is doing so
> efficiently. Which is definitely not done by creating multiple
> temporary lists just to add them. I am sure you know the theory. More
> of relevance is that the generator based solution has also the same
> efficiency, so they are both better than the trivial solution.
> You have a point though. Your function is a solution. Just I don't
> regard it as the preferred solution for the problem as I see it. 

Nor do I.

>YMMV.

It doesn't

> To recap, the OP (and subsequent google searchers, if they pass by) has
> now the preferred solution according to you.

Please not that I didn't meant to present it as "the prefered solution".


-- 
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: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
mystilleef wrote:
(snip)
> 
> __monitor_event is not supposed to be a write accessor. My point was
> show how you can change the state of an object internally without
> needing external access to it. Since some people are surprisingly
> claiming it is not possible.

I failed to see anyone making such a claim.

(snip)


-- 
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: questions to anyone who uses wxPython

2006-07-20 Thread [EMAIL PROTECTED]

damacy wrote:
> hello. i'm using wxPython as my GUI package and whenever my program
> executes a long process which takes at least 2 or 3 seconds, the user
> interface gets corrupted while executing the progrocess during the
> period.

Hi Darnacy,

I had the same issue and used wxProcess to run the long process (in
this case a file copy) in a seperate process to the GUI

See src zip at :
http://www.latedecember.com/sites/software/LDBackup/

Thanks,
Davy Mitchell

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
Gerhard Fiedler wrote:
(snip)
> 
> I'm not sure, but there's one thing that has a potential to be the real
> issue: what's the common way to create a property that is read-write for
> the implementation and "read-only" for the interface? 

class Foo(object):
  @apply
  def _imp():
def fget(self):
  # code here
def fset(self, val):
  # code here
return property(**locals())

  @apply
  def api():
def fget(self):
  return self._imp
def fset(self, val):
  raise SomeException('read-only, sorry')
return property(**locals())


(snip)

> So... _is_active is considered implementation. Don't mess with me, it says.
> But the users of the class need access to it: read access. Do you just say
> "read access isn't changing anything, so just use _is_active"?

Certainly not.

> The
> disadvantage is that the outside code is sprinkled with accesses to
> attributes with leading underscores, which I assume looks kind of scary. Or
> do you rename _is_active to is_active, indicating that access to it is
> indeed allowed?

Certainly not (given I want is_active to be read-only).

> Then you would have to do something in the attribute
> accessors to control the write access -- because that still isn't a good
> idea. But I need want to be able to write to it from inside the class...
> but how, if the attribute accessor is preventing that?

Note that a read-only property named 'is_active' returning the value of
an attribute named '_is_active' doesn't prevent direct access to
'_is_active' attribute, neither from the class nor from the client code.

HTH
-- 
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: Depricated String Functions in Python

2006-07-20 Thread Anoop
Thanks Stefen

let me be more specific how would i have to write the following
function in the deprecated format

map(string.lower,list)

Thanks Anoop


Stefan Behnel wrote:
> Anoop wrote:
> > Can any one help me out with the various depricated string functions
> > that is followed in Python.
> >
> > For example how will be string.lower depricated.
> >
> > As far as string.lower('PYTHON') is concerned it is depricated as
> > 'PYTHON'.lower(). Both of them would return an output : >>> python
>
> I don't quite see the question in your post, but, yes, the module level
> functions of the "string" module are deprecated in favour of the methods of
> the str and unicode objects.
> 
> Stefan

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


SOAPy Question

2006-07-20 Thread gregarican
I apologize in advance for not googling in depth enough :-) I am
looking for use Python's SOAP implementation to pull some retail
pricing data for a work project. Our Internet access goes through an
authenticating proxy server. Can I access information in this scenario
using SOAPy? I have seen cases where the SOAP service requires
authentication and various SOAP implementations account for this. But I
am looking to specify the proxy server authentication to even get out
to the external SOAP service. 

Will this be doable?

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


Checking File permissions

2006-07-20 Thread Anoop
Hi All

Please tell me how to check the existence of a file and the read
permission to the file using python script

Thanks for ur inputs

Anoop

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


Checking File permissions

2006-07-20 Thread Anoop
Hi All

Please tell me how to check the existence of a file and the read
permission to the file using python script

Thanks for ur inputs

Anoop

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


Checking File permissions

2006-07-20 Thread Anoop
Hi All

Please tell me how to check the existence of a file and the read
permission to the file using python script

Thanks for ur inputs

Anoop

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


Re: Depricated String Functions in Python

2006-07-20 Thread Steve Holden
Anoop wrote:
> Thanks Stefen
> 
> let me be more specific how would i have to write the following
> function in the deprecated format
> 
> map(string.lower,list)
> 
To avoid the deprecated usage you would use the unbound method of the 
str type (that's the type of all strings):

  >>> lst = ['Steve', 'Holden']
  >>> map(str.lower, lst)
['steve', 'holden']
  >>>

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Depricated String Functions in Python

2006-07-20 Thread Simon Forman
Anoop wrote:
> Thanks Stefen
>
> let me be more specific how would i have to write the following
> function in the deprecated format
>
> map(string.lower,list)
>
> Thanks Anoop

Ah.  This is easy enough:

lower_list = [s.lower() for s in str_list]

Or, if you really like map() (or really don't like list comprehensions
;P ) you could use this:

lower_list = map(lambda s : s.lower(), str_list)


Hope this helps,
~Simon

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


Re: Depricated String Functions in Python

2006-07-20 Thread Duncan Booth
Anoop wrote:

> let me be more specific how would i have to write the following
> function in the deprecated format
> 
> map(string.lower,list)

What you just wrote is the deprecated format.

There are plenty of ways to write it in an undeprecated format. The 
simplest is probably:

[ s.lower() for s in list ]

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Bruno Desthuilliers wrote:
> >
> >>mystilleef wrote:
> >>
> >>>Bruno Desthuilliers wrote:
> >>>
> >>>
> mystilleef wrote:
> >>
> >>(snip)
> >>
> >>>Of course using setters for the sake of just using them is pointless.
> >>
> >>Indeed.
> >>
> >>
> >>
> >>
> >>>The reason to use them is if pre-conditions or post-conditions need to
> >>>be met. Or to control access to an objects states.
> >>
> >>Then why advocate *systematic* use of them ?
> >>
> >>(snip)
> >
> >I never advocated anything.
> 
> You advocated
> """
> 1). Make all attributes of a class private/protected .
> 2). If a "non-callable" attribute is going to be used outside a class,
> think about making it a property and name the property well, because
> you never know...
> """
> 
> >>>
> >>>
> >>>You use accessors when you need to control access to a data attribute.
> >>
> >>Indeed. And when you don't need too ? (the second 'o' is not a typo)
> >>
> >
> >
> > You make the attribute private/protected.
>
> doh :(
>
> Let's talk about psychorigid mindset...
>

Thanks, I'm insane.

> >
> >>>That's not advocacy, that's common sense.
> >>
> >>I'm afraid we don't use the same definition of "common sense". Writing
> >>useless code is not part of my definition of "common sense".
> >>
> >>(snip)
> >>
> >I agree. And I already told you I think in terms of state and behavior
> >and not language dependent semantics.
> 
> Then why do you advise "(making) all attributes of a class
> private/protected" and systematically using properties ?
> 
> >>>
> >>>
> >>>Because you don't want third parties illegimately tampering with an
> >>>object's internal data and thus crashing your system?
> >>
> >>Let's try again...
> >>
> >>point 1 : there's *no* language-inforced access restriction in Python.
> >>Just a *convention*.
> >>
> >
> >
> > Huh? What are properties for then?
>
> To allow attribute syntax when you really have computation behind. Which
>  1/ let you start with the simplest case (a simple attribute) and change
> your mind latter
> 2/ offer the possibility to use an attribute syntax (instead of a method
> call syntax) when it seems more natural.
>

Right, and what I'm I trying to do again?

> >
> >>point 2 : so anyone *can* "illegimately tampering with an object's
> >>internal data" at will.
> >>
> >
> > And this is robust how?
> >
>
> You can do just the same in Java or C++.
>

OMG!

> >>point 3 : anyway it's not *my* system that will then crash - but the
> >>system of the one who "illegimately" played with my package's objects
> >>internals. And as far as I'm concerned, it's none of my problem - they
> >>were marked as implementation, so anyone playing with them is on it's
> >>own. FWIW, I suspect that if someone want to muck with implementation,
> >>he certainly has a good legitimate reason to do so, and will do her best
> >>to not break anything. Else he's a complete idiot and there's no cure
> >>for this.
> >>
> >
> >
> > You can't be serious. Please tell me you are joking.
>
> I'm deadly serious and definitively not joking. There's no cure for
> idiocy, and there's definitively nothing like an idiot-proof system.
>

Sure, but calling users idiots for as result of your laziness or poor
design or lack of robustness is equally idiotic.

> >
> >>point 4 : since we have computed attributes, turning a "public data
> >>attribute" (to use your idiom) into a "private/protected data attribute
> >>with accessors" *without breaking the interface* is not even a non-brainer.
> >>
> >>Now, please, can you explain the difference between :
> >>
> >>class Complicated(object):
> >>  def __init__(self, data):
> >>self.data = data
> >>  def _get_data(self):
> >>return self._data
> >>  def _set_data(self, data):
> >>self._data = data
> >>
> >>and
> >>
> >>class Pragmatic(object):
> >>  def __init__(self, data)
> >>self.data = data
> >>
> >>
> >>and find any *valid* reason to use the first solution instead of the
> >>second ? ('that's what the book says' not being a valid reason).
> >>
> >
> >
> > I don't know it's your code not mine.
>
> IOW : you're unable to find any valid reason to use the second solution
> instead of the first (of course : there's none), but refuse to admit it.
>

Hey, I didn't write that code. You did! You deal with it. My input on
__your__ code at this point is irrelevant.

> >
> > class Robust(object):
> >
> > def __init__(self):
> > # Arbitrarily changing this state to False will crash app or 
> > will
> > # corrupt the whole event system.
> > self.__is_active = True
> >
> > def get_is_active(self):
> > return self.__is_active
> >
> > buffer_is_active = property(get_is_active, doc="True if buffer is
> > editable")
> >
> > def monitor_events(self):
> > # Only methods of this class can change

Encode filenames to safe format

2006-07-20 Thread Dara Durum
Hi !I want to encode filenames to safe format, like in browser url (space -> %20, etc.).What the module and function name that helps me in this project ?Thanx for it:dd
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Warning when new attributes are added to classes at run time

2006-07-20 Thread Matthew Wilson
On Thu 20 Jul 2006 04:32:28 AM EDT, Bruno Desthuilliers wrote:
>> self.__dict__[name] = value
> Make it:  
>   object.__setattr__(self, name, value)
>
> Your approach will lead to strange results if you mix it with properties
> or other descriptors...

Thanks!

>> class C1(C):
>> 
>> standard_attributes = ['a1', 'a2']
>
> DRY violation here. And a potential problem with inheritance (as always
> with class attributes).

Considering I had to look up what DRY meant before replying to this
message, I may be missing your point.  Is the repeat here that each
subclass has to define its own list of standard attributes?   Or, is it
that the standard_attributes list holds strings, but I could build that
list up by looking at my existing attributes?

If you're feeling charitable, can you explain what you mean a little
more?

TIA


-- 
A better way of running series of SAS programs:
http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about what lamda does

2006-07-20 Thread nephish
hey thanks for that last post, although some of it was a bit over my
head.
i think i am getting more of the differences here.

thanks again,
sk

danielx wrote:
> [EMAIL PROTECTED] wrote:
> > Hey there,
> > i have been learning python for the past few months, but i can seem to
> > get what exactly a lamda is for. What would i use a lamda for that i
> > could not or would not use a def for ? Is there a notable difference ?
> > I only ask because i see it in code samples on the internet and in
> > books.
> >
> > thanks for any clarity
> >
> > sk
>
> hehe. Lambda's are kind of a sensative subject for pythoners who come
> from Lisp. Guido being more of a C guy doesn't really like them, and
> thought they should be removed in py3k. Last time I checked, he was
> reconsidering because of public outcry, presumably from the Lisp crowd.
>
> The standard reason for getting rid of it is "anywhere you need a
> lambda, you can use a def". In addition to what has been said here,
> there is another one small difference between lambda's and functions,
> which is that when you use def, the object gets a name:
>
> >>> def foo(): pass
> ...
> >>> foo
> 
> # ^ foo knows its own name
> >>> bar
> 
> # ^ see ;)
> >>>
>
> Whereas, a lambda has no name; it's "anonymous":
>
> >>> spam = lambda: 1
> >>> spam
>  at 0x009D80F0>
> # ^ spam has an identity crisis ;)
> >>>
>
> Many people who do not come from Lisp do not understand what the use of
> a lambda is (and I have no idea what the purpose of having a name is).
> Even people who do question whether it belongs in Python. In Lisp,
> lambda's are the way things get done, because you can calculate
> anything using just defines and expressions. This style does not fit
> Python very well, since we do things using statements.
>
> Python's lambda really can't be as powerful as Lisp's because Python
> does not have expressions that do case analysis (this is not lambda's
> fault, of course ;). The reason is that you really want to put each
> case on its own set of lines. This enhances readability at the expense
> of terseness. Since Python's statements are terminated by a newline, it
> would be rather awkward to have a kind of expression where good style
> calls for it to be spread out accross multiple lines.
>
> You can try to simulate these kinds expressions using into a list or
> dictionary, but this becomes rather messy. I think the only way to get
> this done properly is to use eval. For example:
>
> def recursiveFunction(args):
>   ...  # do stuff...
>   choices = { True:"0", False:"recurisveFunction(newArgs)" }
>   return eval( choices[predicate] )
>
> The reason that you need eval is that you want to prevent any cases
> from being executed until you decide which one you want. This stay of
> execution is accomplished by wrapping quotes around our expressions.
> This example illustrates why we really need this kind of behavior,
> because without it, we would fall into an infinite loop. Even if it
> were safe to evaluate all cases, it's a big waste of time to do so.
>
> Lastly, I think there is also a performance concern for certain uses of
> lambda (correct me if I'm wrong). Say you have an expression with a
> lambda in it where you could have used a def. Every time you evaluate
> that expression, you have to construct a new lambda object, which takes
> time. If you had used a def instead, you could hav avoided having to
> construct multiple times.

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


Re: Help Needed. Removing a Folder Problem

2006-07-20 Thread Larry Bates
Note the error is permission denied.  I would guess that
either the file has read-only flag set or perhaps the
'' program is still running and has the file open
in a separate thread so you can't delete the directory
until it has completed.  You should take a look at the
subprocess module and use something like (not tested):

retcode = call([r' C:\copiedfiles\*.*', cmd_out])

This will wait for execution of  to complete prior
to returning.

-Larry Bates


Kilicaslan Fatih wrote:
> When I push a button to trigger the code:
> 
> def run(self, event):
> cmd_out = self.A_com()
> if App.runF != "":
> os.mkdir('C:\copiedFiles')
>   
> for item in App.runF:
> App.beCopied = str(item)
> shutil.copy(App.beCopied,  
> 'C:\copiedFiles')
> cmd = ' C:\copiedFiles\*.*' + cmd_out
> os.system(cmd)
> shutil.rmtree('C:\copiedFiles')
> else:
> tkMessageBox.showinfo("Window Text",
> "Please Firstly Browse and Insert A File")
> 
> 
> I encountered this error:
> 
> Traceback (most recent call last):
>   File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345,
> in __call__
> return self.func(*args)
>   File "C:\Python24\TkScripts\RCFolder.py", line 61,
> in run
> shutil.rmtree('C:\copiedFiles',
> ignore_errors=False)# OLMADI!!!
>   File "C:\Python24\lib\shutil.py", line 168, in
> rmtree
> onerror(os.remove, fullname, sys.exc_info())
>   File "C:\Python24\lib\shutil.py", line 166, in
> rmtree
> os.remove(fullname)
> OSError: [Errno 13] Permission denied:
> 'C:\\copiedFiles\\Analog.c'
> 
> 1. What I want to do is to get the list of files I
> inserted to a Listbox,
> 2. Creating a folder,(C:\copiedFiles)
> 3. Copying all of these files to this folder with the
> same names,
> 4. Running  for all of the files in this folder,
> 5. Than removing this folder.
> 
> Can anyone enlighten me on this Error I have got and
> how to solve it?
> 
> Regards
> 
> 
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


subprocess module

2006-07-20 Thread placid
Hi all,

If someone could give me an example of creating a subprocess (on
Windows) using the subprocess module and Popen class and connecting to
its stdout/stdin file handles. I googled for a bit but the only example
i found was here ;

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


-- Cheers

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


Re: Warning when new attributes are added to classes at run time

2006-07-20 Thread Bruno Desthuilliers
Matthew Wilson wrote:
> On Thu 20 Jul 2006 04:32:28 AM EDT, Bruno Desthuilliers wrote:
(snip)
> 
>>>class C1(C):
>>>
>>>standard_attributes = ['a1', 'a2']
>>
>>DRY violation here. And a potential problem with inheritance (as always
>>with class attributes).
> 
> 
> Considering I had to look up what DRY meant before replying to this
> message, I may be missing your point.  Is the repeat here that each
> subclass has to define its own list of standard attributes?   Or, is it
> that the standard_attributes list holds strings, but I could build that
> list up by looking at my existing attributes?

Mostly the second. But now, how are you going to build that list from
"existing attributes" before these attributes exists ?-) (chicken and
egg problem here...)

FWIW, you could use custom descriptors to build the 'schema', then use a
metaclass to detect these descriptors and build the "allowed attributes"
list. But the whole thing seems overkill to me if it's only to solve
typo problems (can be interesting for other reasons...).

Re-read the three first answers to your post - unit-tests,
pylint/pychecker, eventually slots...

My 2 cents

-- 
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: Depricated String Functions in Python

2006-07-20 Thread riquito

Steve Holden ha scritto:

> Anoop wrote:
> > Thanks Stefen
> >
> > let me be more specific how would i have to write the following
> > function in the deprecated format
> >
> > map(string.lower,list)
> >
> To avoid the deprecated usage you would use the unbound method of the
> str type (that's the type of all strings):
>
>   >>> lst = ['Steve', 'Holden']
>   >>> map(str.lower, lst)
> ['steve', 'holden']
>   >>>

This isn't exactly equal to use string.lower, because this work with
just encoded strings, when string.lower works with unicode too.
I'm used to have a "lower" func like this one
def lower(x): return x.lower()
to use in map. Of course it's a problem when you need many different
methods.

A solution could be something like this
>>> def doit(what):
...def func(x):
...   return getattr(x,what)()
...return func
...
>>> map(doit('lower'),['aBcD',u'\xc0'])
['abcd', u'\xe0']
>>> map(doit('upper'),['aBcD',u'\xc0'])
['ABCD', u'\xc0']

The best is to use in advance just unicode or encoded strings in your
program, but this is not always possible :-/

Riccardo Galli

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


Re: Checking File permissions

2006-07-20 Thread Avell Diroll
Anoop wrote:
> Please tell me how to check the existence of a file and the read
> permission to the file using python script

You can check the os module (os.stat comes to mind).

For an exemple you can have a look at :
http://www.pixelbeat.org/talks/python/ls.py

Regards,

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


Re: Checking File permissions

2006-07-20 Thread Larry Bates
Note: You really don't have to post the same question
3 times (2 in response to yourself).

import os

if os.path.exists(pathname):
  

To see if a file is writeable:

import stat

def iswriteable(path):
mode=os.stat(path)[stat.ST_mode]
return bool(stat.S_IMODE(mode) & stat.S_IWRITE)


Larry Bates

Anoop wrote:
> Hi All
> 
> Please tell me how to check the existence of a file and the read
> permission to the file using python script
> 
> Thanks for ur inputs
> 
> Anoop
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Py2exe & (Py)QT4

2006-07-20 Thread shane . external
I'm having trouble using Py2exe with a PyQT-based python project. Or
possibly I'm having a problem with PyQT and Py2exe makes it apparent.
Whichever it is, I run into trouble with importing QtCore and QtGui.
The error reported is:

 Traceback (most recent call last):
   File "xmlEdit.py", line 3, in ?
   File "PyQt4\QtCore.pyc", line 12, in ?
   File "PyQt4\QtCore.pyc", line 10, in __load
 ImportError: DLL load failed: Invalid access to memory location.

Line 10 is the import of QtCore.pyd, which is  included in the dist
folder. Curiously, this is the same error I get when I input "from
PyQt4 import QtCore, QtGui" into IDLE, so I'm not even sure it's a
Py2exe issue. I'm not quite sure what the error means, only that it
isn't that the file is not found (a Module Not Found error occurs if I
remove QtCore.pyd).

It run just fine from the command line. Can anyone shed some light on
this? QT version is 4.1.3. Python is 2.4.3 and PyQT is 4.0.1.

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


Re: SOAPy Question

2006-07-20 Thread gregarican
Please disregard, as I googled my way to the answer. I used SOAPProxy
to specify the information I needed to get out to the external SOAP
service. All is well and away we go :-)

gregarican wrote:
> I apologize in advance for not googling in depth enough :-) I am
> looking for use Python's SOAP implementation to pull some retail
> pricing data for a work project. Our Internet access goes through an
> authenticating proxy server. Can I access information in this scenario
> using SOAPy? I have seen cases where the SOAP service requires
> authentication and various SOAP implementations account for this. But I
> am looking to specify the proxy server authentication to even get out
> to the external SOAP service. 
> 
> Will this be doable?

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


Re: Help Needed. Removing a Folder Problem

2006-07-20 Thread Kilicaslan Fatih


--- Larry Bates <[EMAIL PROTECTED]> wrote:

> Note the error is permission denied.  I would guess
> that
> either the file has read-only flag set or perhaps
> the
> '' program is still running and has the file
> open
> in a separate thread so you can't delete the
> directory
> until it has completed.  You should take a look at
> the
> subprocess module and use something like (not
> tested):
> 
> retcode = call([r' C:\copiedfiles\*.*',
> cmd_out])
> 
> This will wait for execution of  to complete
> prior
> to returning.
> 
> -Larry Bates
> 
> 
> Kilicaslan Fatih wrote:
> > When I push a button to trigger the code:
> > 
> > def run(self, event):
> > cmd_out = self.A_com()
> > if App.runF != "":
> > os.mkdir('C:\copiedFiles')
>
> >   
> > for item in App.runF:
> > App.beCopied = str(item)
> > shutil.copy(App.beCopied, 
> 
> > 'C:\copiedFiles')
> > cmd = ' C:\copiedFiles\*.*' +
> cmd_out
> > os.system(cmd)
> > shutil.rmtree('C:\copiedFiles')
> > else:
> > tkMessageBox.showinfo("Window Text",
> > "Please Firstly Browse and Insert A File")
> > 
> > 
> > I encountered this error:
> > 
> > Traceback (most recent call last):
> >   File "C:\Python24\lib\lib-tk\Tkinter.py", line
> 1345,
> > in __call__
> > return self.func(*args)
> >   File "C:\Python24\TkScripts\RCFolder.py", line
> 61,
> > in run
> > shutil.rmtree('C:\copiedFiles',
> > ignore_errors=False)# OLMADI!!!
> >   File "C:\Python24\lib\shutil.py", line 168, in
> > rmtree
> > onerror(os.remove, fullname, sys.exc_info())
> >   File "C:\Python24\lib\shutil.py", line 166, in
> > rmtree
> > os.remove(fullname)
> > OSError: [Errno 13] Permission denied:
> > 'C:\\copiedFiles\\Analog.c'
> > 
> > 1. What I want to do is to get the list of files I
> > inserted to a Listbox,
> > 2. Creating a folder,(C:\copiedFiles)
> > 3. Copying all of these files to this folder with
> the
> > same names,
> > 4. Running  for all of the files in this
> folder,
> > 5. Than removing this folder.
> > 
> > Can anyone enlighten me on this Error I have got
> and
> > how to solve it?
> > 
> > Regards
> > 
> > 
> > __
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam
> protection around 
> > http://mail.yahoo.com 

Thank you very much for your reply, during my wait for
an answer I changed the code. 

1. First created the folder
2. Then copied all the files in the listbox to the
folder
3. Run 
3. changed the files' permissions in the folder
4. Then try to remove the folder 

def run(self, event):
cmd_out = self.A_com()
if App.runF != "":
print len(App.runF)
os.mkdir('C:\copiedFiles')
  
for item in App.runF:
  
shutil.copy(item, 'C:\copiedFiles')   
  
cmd = ' C:\copiedFiles\*.*' + cmd_out
os.system(cmd)
for root,dir,files in
os.walk("C:\copiedFiles"):
print len(files)
for j in files:
fille = os.path.join(root,j)  
   
os.chmod(fille, 0700)
shutil.rmtree('C:\copiedFiles')
else:
tkMessageBox.showinfo("Window Text",
"Please Firstly Browse and Insert A File")   
  




I got another error this time:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345,
in __call__
return self.func(*args)
  File "C:\Python24\TkScripts\RCFolder.py", line 56,
in run
shutil.copy(item, 'C:\copiedFiles')
  File "C:\Python24\lib\shutil.py", line 81, in copy
copyfile(src, dst)
  File "C:\Python24\lib\shutil.py", line 48, in
copyfile
fdst = open(dst, 'wb')
IOError: [Errno 13] Permission denied:
'C:\\copiedFiles\\Generic_IO.h'

I have more than 200 files in the folder. I will have
nearly 1000 files in each execution. I don't know why
I encountered this error. I am still searching the
reason, and I will check the subprocess module in
anyway.

Regards


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Encode filenames to safe format

2006-07-20 Thread Amit Khemka
On 7/20/06, Dara Durum <[EMAIL PROTECTED]> wrote:
> Hi !
>
> I want to encode filenames to safe format, like in browser url (space ->
> %20, etc.).
> What the module and function name that helps me in this project ?
>

import urllib
urllib.quote('file name')

cheers,
amit

-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
mystilleef wrote:
> Bruno Desthuilliers wrote:
> 
(snip)
>You use accessors when you need to control access to a data attribute.

Indeed. And when you don't need too ? (the second 'o' is not a typo)

>>>
>>>
>>>You make the attribute private/protected.
>>
>>doh :(
>>
>>Let's talk about psychorigid mindset...
>>
> 
> 
> Thanks, I'm insane.

You say so.

(snip)
>>Then why do you advise "(making) all attributes of a class
>>private/protected" and systematically using properties ?
>>
>
>
>Because you don't want third parties illegimately tampering with an
>object's internal data and thus crashing your system?

Let's try again...

point 1 : there's *no* language-inforced access restriction in Python.
Just a *convention*.

>>>
>>>
>>>Huh? What are properties for then?
>>
>>To allow attribute syntax when you really have computation behind. Which
>> 1/ let you start with the simplest case (a simple attribute) and change
>>your mind latter
>>2/ offer the possibility to use an attribute syntax (instead of a method
>>call syntax) when it seems more natural.
>>
> 
> 
> Right, and what I'm I trying to do again?
> 

Write Java in Python.

point 2 : so anyone *can* "illegimately tampering with an object's
internal data" at will.

>>>
>>>And this is robust how?
>>>
>>
>>You can do just the same in Java or C++.
>>
> 
> 
> OMG!

It's common knowledge.

> 
point 3 : anyway it's not *my* system that will then crash - but the
system of the one who "illegimately" played with my package's objects
internals. And as far as I'm concerned, it's none of my problem - they
were marked as implementation, so anyone playing with them is on it's
own. FWIW, I suspect that if someone want to muck with implementation,
he certainly has a good legitimate reason to do so, and will do her best
to not break anything. Else he's a complete idiot and there's no cure
for this.

>>>
>>>
>>>You can't be serious. Please tell me you are joking.
>>
>>I'm deadly serious and definitively not joking. There's no cure for
>>idiocy, and there's definitively nothing like an idiot-proof system.
>> 
> 
> Sure, but calling users idiots for as result of your laziness or poor
> design or lack of robustness is equally idiotic.

Ok, then 99.99% of Python programmers are lazy, have poor design skills
and are unable to write a robust application. So they are idiotic too.

point 4 : since we have computed attributes, turning a "public data
attribute" (to use your idiom) into a "private/protected data attribute
with accessors" *without breaking the interface* is not even a non-brainer.

Now, please, can you explain the difference between :

class Complicated(object):
 def __init__(self, data):
   self.data = data
 def _get_data(self):
   return self._data
 def _set_data(self, data):
   self._data = data

and

class Pragmatic(object):
 def __init__(self, data)
   self.data = data


and find any *valid* reason to use the first solution instead of the
second ? ('that's what the book says' not being a valid reason).

>>>
>>>
>>>I don't know it's your code not mine.
>>
>>IOW : you're unable to find any valid reason to use the second solution
>>instead of the first (of course : there's none), but refuse to admit it.
>> 
> 
> Hey, I didn't write that code. You did! You deal with it. My input on
> __your__ code at this point is irrelevant.

It's totally relevant, and you're still unable to come with any valid
reason to prefer the first solution over the second. I'm totally
confident that if there was *any* defendable reason to favor the first
approach, you'd have chosen to answer instead of playing dumb.

>>>class Robust(object):
>>>
>>> def __init__(self):
>>> # Arbitrarily changing this state to False will crash app or 
>>> will
>>> # corrupt the whole event system.
>>> self.__is_active = True
>>>
>>> def get_is_active(self):
>>> return self.__is_active
>>>
>>> buffer_is_active = property(get_is_active, doc="True if buffer is
>>>editable")
>>>
>>> def monitor_events(self):
>>> # Only methods of this class can change __is_active.
>>> # Add code to change __is_active here.
>>> return
>>
>>Yuck.
>>
>>
>>>See! I'm controlling access.
>>
>>You are not controlling *anything*
>>
>>r = Robust()
>>r._Robust__is_active = True
>>
> 
> 
> *sighs*
> 
> You keep coming up with these unrealistic and impractically delusional
> theories

Pardon ? Which "unrealistic and impractically delusional theories" ?
Please try the code above instead of getting to big words...

> to make yourself feel happy.

yes, of course, I need this to feel happy. Doh :(

> Sure Python lets your do that,
> but that's an implementation detail almost all Python developers could
> give a damn about. How many times do 

Re: text representation of HTML

2006-07-20 Thread garabik-news-2005-05
Ksenia Marasanova <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I am looking for a library that will give me very simple text
> representation of HTML.
> For example
> TitleThis is a test
> 
> will be transformed to:
> 
> Title
> 
> This is a
> test
> 
> 
> i want to send plain text alternative of html email, and would prefer
> to do it automatically from HTML source.

something like this:

import re
text = 'TitleThis is a test'
text = re.sub(r'[\n\ \t]+', ' ', text)
text = re.sub(r'(?i)(\|\|\)', '\n', text)
result = re.sub('<.+?>', '', text)
print result

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: question about what lamda does

2006-07-20 Thread Bruno Desthuilliers
danielx wrote:
(snip)

> Python's lambda really can't be as powerful as Lisp's because Python
> does not have expressions that do case analysis (this is not lambda's
> fault, of course ;). The reason is that you really want to put each
> case on its own set of lines. This enhances readability at the expense
> of terseness. Since Python's statements are terminated by a newline, it
> would be rather awkward to have a kind of expression where good style
> calls for it to be spread out accross multiple lines.
> 
> You can try to simulate these kinds expressions using into a list or
> dictionary, but this becomes rather messy. I think the only way to get
> this done properly is to use eval. For example:
> 
> def recursiveFunction(args):
>   ...  # do stuff...
>   choices = { True:"0", False:"recurisveFunction(newArgs)" }
>   return eval( choices[predicate] )

Why do you want to use eval here ?

> The reason that you need eval is that you want to prevent any cases
> from being executed until you decide which one you want.

What about:

def recursiveFunction(args):
... # do stuff...
... # that defines 'newArgs' and 'predicate' of course ...
return (recursiveFunction, lambda x: 0)[predicate](newArgs)

-- 
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: text representation of HTML

2006-07-20 Thread Duncan Booth
Ksenia Marasanova wrote:

> I am looking for a library that will give me very simple text
> representation of HTML.
> For example
>TitleThis is a test
> 
> will be transformed to:
> 
> Title
> 
> This is a
> test
> 
> 
> i want to send plain text alternative of html email, and would prefer
> to do it automatically from HTML source.
> Any hints?

Use htmllib:

>>> import htmllib, formatter, StringIO
>>> def cleanup(s):
out = StringIO.StringIO()
p = htmllib.HTMLParser(
formatter.AbstractFormatter(formatter.DumbWriter(out)))
p.feed(s)
p.close()
if p.anchorlist:
print >>out
for idx,anchor in enumerate(p.anchorlist):
print >>out, "\n[%d]: %s" % (idx+1,anchor)
return out.getvalue()

>>> print cleanup('''TitleThis is a test''')

Title

This is a
test
>>> print cleanup('''TitleThis is a test with http://python.org";>a link to the Python homepage''')

Title

This is a
test with a link[1] to the Python homepage

[1]: http://python.org


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


Re: range() is not the best way to check range?

2006-07-20 Thread Alex Martelli
Paul Boddie <[EMAIL PROTECTED]> wrote:

> John Machin wrote:
> >
> > range() and xrange() are functions. You are suggesting that 2
> > *functions* should acquire a __contains__ method each? I trust not.
> 
> Well, range is a function in the current implementation, although its
> usage is similar to that one would get if it were a class, particularly
> a subclass of list or one providing a list-style interface. With such a
> class, you could provide a __contains__ method which could answer the
> question of what the range contains based on the semantics guaranteed
> by a range (in contrast to a normal list).

You'd also have to override just about every mutating method to switch
back to a "normal" __contains__ (or change self's type on the fly) -- a
pretty heavy price to pay.

I have often noticed that subclassing list, dict and maybe set has this
kind of issue: the need to track every possible change to the object.

Maybe a good mechanism to have for the purpose would be to add to
mutable types a "hook" method, say __mutator__, which gets called either
right before or right after any mutating method (there are different
tradeoffs for before-calls and after-calls), presumably passing along
the *a and **k for generality (although it might be faster for the base
case to avoid that); the base types would have a no-op implementation,
but subtypes could easily override just the hook to facilitate their
task of maintaining extra state (could be as little as a per-instance
flag recording whether the object is guaranteed to be still "pristine").
At C level, that might be an extra slot tp_mutator, left NULL in base
types to indicate "no mutator-hook method implemented here".

Like any other addition of, or change to, functionality, this would of
course be a proposal for 2.6, since 2.5 is feature-frozen now.


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


Note on PEP 299

2006-07-20 Thread bearophileHUGS
I don't like much the syntax of:
if __name__ == '__main__':

Some time ago I have read this PEP:
http://www.python.org/dev/peps/pep-0299/

And why it was refused:
http://mail.python.org/pipermail/python-dev/2006-March/062955.html

I think the name of the standard main function may be just main(), so
there isn't the problem with the import (and *maybe* the problem with
multiple Python versions can be ignored with Python 3.0).

If a module contains the main(), the main() is executed when the module
is run alone. Otherwise you can import the module, with the main()
function managed as a normal function.

Bye,
bearophile

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


Re: range() is not the best way to check range?

2006-07-20 Thread Paul Boddie
Alex Martelli wrote:
> Paul Boddie <[EMAIL PROTECTED]> wrote:
> >
> > Well, range is a function in the current implementation, although its
> > usage is similar to that one would get if it were a class, particularly
> > a subclass of list or one providing a list-style interface. With such a
> > class, you could provide a __contains__ method which could answer the
> > question of what the range contains based on the semantics guaranteed
> > by a range (in contrast to a normal list).
>
> You'd also have to override just about every mutating method to switch
> back to a "normal" __contains__ (or change self's type on the fly) -- a
> pretty heavy price to pay.

A subclass of list is probably a bad idea in hindsight, due to various
probable requirements of it actually needing to be a list with all its
contents, whereas we wanted to avoid having anything like a list around
until the contents of this "lazy list" were required by the program. If
we really wanted to subclass something, we could consider subclassing
the slice class/type, but that isn't subclassable in today's Python for
some reason, and it doesn't really provide anything substantial,
anyway. However, Python being the language it is, an appropriately
behaving class is quite easily written from scratch.

Paul

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


Re: Python linker

2006-07-20 Thread Alex Martelli
Ben Sizer <[EMAIL PROTECTED]> wrote:

> Sion Arrowsmith wrote:
> > Er, what? How are you generating your standalone executables? What
> > size is "acceptable"? python24.dll is only 1.8M -- surely on any
> > non-embedded platform these days 1.8M isn't worth bothering about.
> > And since you mention wx (all of another 4.8M) I'd guess we're
> > talking about desktop applications. Who's going to notice if your
> > executable is a couple of M slimmer?
> 
> I've considered making a few lightweight GUI apps in the past but you
> just can't do it with wxPython. When you have similar products done in
> Visual C++ weighing in at kilobytes rather than megabytes, it's hard to
> convince people that it's worth downloading your product. Say I wanted

What framework (if any) is your Visual C++ code using?  If it's using
wxWidgets (the framework underlying wxPython) I very much doubt that it
can be a few kilobytes -- unless the wxWidgets DLL is already installed
on the target machines so that it doesn't need to be packaged together
with the application code.


> to develop a simple Notepad clone with 1 or 2 extra features: the MS
> executable is 68Kb, yet to simulate it in wxPython would be over 5MB;
> nobody would want it. I suppose you can use the msvcrt library directly
> and cut out wx from the dependencies, but sadly the Python overhead is
> still a slight deterrent.
> 
> Not that I see an easy solution to this, of course.

The easy solution is to compare apples with apples: if, in your
application space, it is crucial to use only DLLs that are already
installed on the target machines, you can do that from Python (with
ctypes, for example) just as you can from C.  Of course, coding to
(e.g.) the Win32 API directly is not to everybody's tastes, but it's
just about as bad in any language.

Of course, if you believe that the runtime libraries for a given
language (Visual Basic N for some specific value of N, Visual C++ M for
some specific value of M, ...) are going to be already installed on the
target machine, then the hypothetical constraint says that you must use
that specific language and version.  For example, nobody will ever
program applications in VB6, because at some point in time the runtime
libraries for VB5 were widespread and those for VB6 were not, so a
program prepared for VB5 could be distributed as a much-smaller package.

What generally happens in the real world is rather different:
applications get programmed in whatever language and release/version is
handy, and the runtimes are separately offered for download and install
to those users who have not yet installed any previous application using
the same language and release/version.  For example, msvcr80.dll is
indispensable to use programs written with Microsoft Visual Studio 2005,
and you'll find thousands of sites on the web offering it for separate
download and installation; mfc80u.dll, similarly (albeit only at
hundreds of sites;-); and so on, and so forth.

The situation is quite similar for other languages, Python included, and
other frameworks, wxWidgets (and wxPython on top it it) included.


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


Re: Help Needed. Removing a Folder Problem(Problem Solved)

2006-07-20 Thread Kilicaslan Fatih


--- Larry Bates <[EMAIL PROTECTED]> wrote:

> Note the error is permission denied.  I would guess
> that
> either the file has read-only flag set or perhaps
> the
> '' program is still running and has the file
> open
> in a separate thread so you can't delete the
> directory
> until it has completed.  You should take a look at
> the
> subprocess module and use something like (not
> tested):
> 
> retcode = call([r' C:\copiedfiles\*.*',
> cmd_out])
> 
> This will wait for execution of  to complete
> prior
> to returning.
> 
> -Larry Bates
> 
> 
> Kilicaslan Fatih wrote:
> > When I push a button to trigger the code:
> > 
> > def run(self, event):
> > cmd_out = self.A_com()
> > if App.runF != "":
> > os.mkdir('C:\copiedFiles')
>
> >   
> > for item in App.runF:
> > App.beCopied = str(item)
> > shutil.copy(App.beCopied, 
> 
> > 'C:\copiedFiles')
> > cmd = ' C:\copiedFiles\*.*' +
> cmd_out
> > os.system(cmd)
> > shutil.rmtree('C:\copiedFiles')
> > else:
> > tkMessageBox.showinfo("Window Text",
> > "Please Firstly Browse and Insert A File")
> > 
> > 
> > I encountered this error:
> > 
> > Traceback (most recent call last):
> >   File "C:\Python24\lib\lib-tk\Tkinter.py", line
> 1345,
> > in __call__
> > return self.func(*args)
> >   File "C:\Python24\TkScripts\RCFolder.py", line
> 61,
> > in run
> > shutil.rmtree('C:\copiedFiles',
> > ignore_errors=False)# OLMADI!!!
> >   File "C:\Python24\lib\shutil.py", line 168, in
> > rmtree
> > onerror(os.remove, fullname, sys.exc_info())
> >   File "C:\Python24\lib\shutil.py", line 166, in
> > rmtree
> > os.remove(fullname)
> > OSError: [Errno 13] Permission denied:
> > 'C:\\copiedFiles\\Analog.c'
> > 
> > 1. What I want to do is to get the list of files I
> > inserted to a Listbox,
> > 2. Creating a folder,(C:\copiedFiles)
> > 3. Copying all of these files to this folder with
> the
> > same names,
> > 4. Running  for all of the files in this
> folder,
> > 5. Than removing this folder.
> > 
> > Can anyone enlighten me on this Error I have got
> and
> > how to solve it?
> > 
> > Regards
> > 
> > 
> > __
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam
> protection around 
> > http://mail.yahoo.com 

Dear All,

I changed the mode of the files before copying them.
So the problem is solved as follows:

SOLUTION:

def run(self, event):
cmd_out = self.A_com()
if App.runF != "":
os.mkdir('C:\copiedFiles')
  
for item in App.runF:
os.chmod(item, 0700)
shutil.copy(item, 'C:\copiedFiles')   
  
cmd = ' C:\copiedFiles\*.*' + cmd_out
os.system(cmd)
for root,dir,files in
os.walk("C:\copiedFiles"):
  
shutil.rmtree('C:\copiedFiles')
else:
tkMessageBox.showinfo("Window Text",
"Please Firstly Browse and Insert A File")

Thank you very much for your help,
Regards


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Needed. Removing a Folder Problem(Problem Solved)

2006-07-20 Thread Kilicaslan Fatih


--- Larry Bates <[EMAIL PROTECTED]> wrote:

> Note the error is permission denied.  I would guess
> that
> either the file has read-only flag set or perhaps
> the
> '' program is still running and has the file
> open
> in a separate thread so you can't delete the
> directory
> until it has completed.  You should take a look at
> the
> subprocess module and use something like (not
> tested):
> 
> retcode = call([r' C:\copiedfiles\*.*',
> cmd_out])
> 
> This will wait for execution of  to complete
> prior
> to returning.
> 
> -Larry Bates
> 
> 
> Kilicaslan Fatih wrote:
> > When I push a button to trigger the code:
> > 
> > def run(self, event):
> > cmd_out = self.A_com()
> > if App.runF != "":
> > os.mkdir('C:\copiedFiles')
>
> >   
> > for item in App.runF:
> > App.beCopied = str(item)
> > shutil.copy(App.beCopied, 
> 
> > 'C:\copiedFiles')
> > cmd = ' C:\copiedFiles\*.*' +
> cmd_out
> > os.system(cmd)
> > shutil.rmtree('C:\copiedFiles')
> > else:
> > tkMessageBox.showinfo("Window Text",
> > "Please Firstly Browse and Insert A File")
> > 
> > 
> > I encountered this error:
> > 
> > Traceback (most recent call last):
> >   File "C:\Python24\lib\lib-tk\Tkinter.py", line
> 1345,
> > in __call__
> > return self.func(*args)
> >   File "C:\Python24\TkScripts\RCFolder.py", line
> 61,
> > in run
> > shutil.rmtree('C:\copiedFiles',
> > ignore_errors=False)# OLMADI!!!
> >   File "C:\Python24\lib\shutil.py", line 168, in
> > rmtree
> > onerror(os.remove, fullname, sys.exc_info())
> >   File "C:\Python24\lib\shutil.py", line 166, in
> > rmtree
> > os.remove(fullname)
> > OSError: [Errno 13] Permission denied:
> > 'C:\\copiedFiles\\Analog.c'
> > 
> > 1. What I want to do is to get the list of files I
> > inserted to a Listbox,
> > 2. Creating a folder,(C:\copiedFiles)
> > 3. Copying all of these files to this folder with
> the
> > same names,
> > 4. Running  for all of the files in this
> folder,
> > 5. Than removing this folder.
> > 
> > Can anyone enlighten me on this Error I have got
> and
> > how to solve it?
> > 
> > Regards
> > 
> > 
> > __
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam
> protection around 
> > http://mail.yahoo.com 

Dear All,

I changed the mode of the files before copying them.
So the problem is solved as follows:

SOLUTION:

def run(self, event):
cmd_out = self.A_com()
if App.runF != "":
os.mkdir('C:\copiedFiles')
  
for item in App.runF:
os.chmod(item, 0700)
shutil.copy(item, 'C:\copiedFiles')   
  
cmd = ' C:\copiedFiles\*.*' + cmd_out
os.system(cmd)
for root,dir,files in
os.walk("C:\copiedFiles"):
  
shutil.rmtree('C:\copiedFiles')
else:
tkMessageBox.showinfo("Window Text",
"Please Firstly Browse and Insert A File")

Thank you very much for your help,
Regards


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Needed. Removing a Folder Problem(Problem Solved)

2006-07-20 Thread Kilicaslan Fatih


--- Larry Bates <[EMAIL PROTECTED]> wrote:

> Note the error is permission denied.  I would guess
> that
> either the file has read-only flag set or perhaps
> the
> '' program is still running and has the file
> open
> in a separate thread so you can't delete the
> directory
> until it has completed.  You should take a look at
> the
> subprocess module and use something like (not
> tested):
> 
> retcode = call([r' C:\copiedfiles\*.*',
> cmd_out])
> 
> This will wait for execution of  to complete
> prior
> to returning.
> 
> -Larry Bates
> 
> 
> Kilicaslan Fatih wrote:
> > When I push a button to trigger the code:
> > 
> > def run(self, event):
> > cmd_out = self.A_com()
> > if App.runF != "":
> > os.mkdir('C:\copiedFiles')
>
> >   
> > for item in App.runF:
> > App.beCopied = str(item)
> > shutil.copy(App.beCopied, 
> 
> > 'C:\copiedFiles')
> > cmd = ' C:\copiedFiles\*.*' +
> cmd_out
> > os.system(cmd)
> > shutil.rmtree('C:\copiedFiles')
> > else:
> > tkMessageBox.showinfo("Window Text",
> > "Please Firstly Browse and Insert A File")
> > 
> > 
> > I encountered this error:
> > 
> > Traceback (most recent call last):
> >   File "C:\Python24\lib\lib-tk\Tkinter.py", line
> 1345,
> > in __call__
> > return self.func(*args)
> >   File "C:\Python24\TkScripts\RCFolder.py", line
> 61,
> > in run
> > shutil.rmtree('C:\copiedFiles',
> > ignore_errors=False)# OLMADI!!!
> >   File "C:\Python24\lib\shutil.py", line 168, in
> > rmtree
> > onerror(os.remove, fullname, sys.exc_info())
> >   File "C:\Python24\lib\shutil.py", line 166, in
> > rmtree
> > os.remove(fullname)
> > OSError: [Errno 13] Permission denied:
> > 'C:\\copiedFiles\\Analog.c'
> > 
> > 1. What I want to do is to get the list of files I
> > inserted to a Listbox,
> > 2. Creating a folder,(C:\copiedFiles)
> > 3. Copying all of these files to this folder with
> the
> > same names,
> > 4. Running  for all of the files in this
> folder,
> > 5. Than removing this folder.
> > 
> > Can anyone enlighten me on this Error I have got
> and
> > how to solve it?
> > 
> > Regards
> > 
> > 
> > __
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam
> protection around 
> > http://mail.yahoo.com 

Dear All,

I changed the mode of the files before copying them.
So the problem is solved as follows:

SOLUTION:

def run(self, event):
cmd_out = self.A_com()
if App.runF != "":
os.mkdir('C:\copiedFiles')
  
for item in App.runF:
os.chmod(item, 0700)
shutil.copy(item, 'C:\copiedFiles')   
  
cmd = ' C:\copiedFiles\*.*' + cmd_out
os.system(cmd)
for root,dir,files in
os.walk("C:\copiedFiles"):
  
shutil.rmtree('C:\copiedFiles')
else:
tkMessageBox.showinfo("Window Text",
"Please Firstly Browse and Insert A File")

Thank you very much for your help,
Regards


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python linker

2006-07-20 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> I develop shareware applications that need to be extremely slim (less
> than 1 MB is preferable).
> 
> Delphi applications easily meet this requirement and I can expect end
> users to download the .NET framework (if they don't already have it!).
> 
> However, I cannot expect users to download 3.5 MB.
> 
> For corporate clients, size does not matter the least, but for end
> users, anything that is a couple of megs seems "bloated".

So use IronPython -- that's what it's for, after all: letting you write
Python applications for .NET.  See
: it's
now in Beta9 and the final non-beta release should be out soon.


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


Re: range() is not the best way to check range?

2006-07-20 Thread Alex Martelli
Paul Boddie <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > Paul Boddie <[EMAIL PROTECTED]> wrote:
> > >
> > > Well, range is a function in the current implementation, although its
> > > usage is similar to that one would get if it were a class, particularly
> > > a subclass of list or one providing a list-style interface. With such a
> > > class, you could provide a __contains__ method which could answer the
> > > question of what the range contains based on the semantics guaranteed
> > > by a range (in contrast to a normal list).
> >
> > You'd also have to override just about every mutating method to switch
> > back to a "normal" __contains__ (or change self's type on the fly) -- a
> > pretty heavy price to pay.
> 
> A subclass of list is probably a bad idea in hindsight, due to various
> probable requirements of it actually needing to be a list with all its
> contents, whereas we wanted to avoid having anything like a list around
> until the contents of this "lazy list" were required by the program. If
> we really wanted to subclass something, we could consider subclassing
> the slice class/type, but that isn't subclassable in today's Python for
> some reason, and it doesn't really provide anything substantial,
> anyway. However, Python being the language it is, an appropriately
> behaving class is quite easily written from scratch.

Nevertheless, that class will still need to implement every single
method of the list type; making it a subclass of list has some advantage
in that every such implementation of a method can basically fill the
real list, self.__class__=list, and leave all the rest, forevermore
(explicitly here, implicitly in the future), to class list.  Performance
should be much better than by working off semi-deprecated UserList.

A "hook method" __mutator__ (ideally called _before_ in this case), as I
was proposing (for 2.6 or later), would make such approaches way easier
and handier (and would help with most use cases I can think of for
subclassing list, dict or set).


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


Re: Question regarding commit/backout of a message using the pymqi module

2006-07-20 Thread JonS

Andrew Robert wrote:
> Hi everyone,
>
> Could someone help explain what I am doing wrong in
> this code block?
>
> This code block is an excerpt from a larger file that receives
> transmitted files via IBM WebSphere MQSeries an drops it to the local
> file system.
>
> Transmission of the file works as designed but it has a flaw.
>
> If the file cannot be created for whatever reason, the transmitted
> message is lost.
>
> What I am trying to do is ensure that a file transmit is considered
> successful only after the created file's checksum matches.
>
> If not, the code should treat it as an error and roll back the message
> to MQSeries without a commit.
>
> The basis for this should be around the pymqi.QueueManager class which
> is named mq in the block listed below.
>
> pymqi.MQMIError: MQI Error. Comp: 1, Reason 2121: WARNING:
> MQRC_NO_EXTERNAL_PARTICIPANTS
> Do you have any idea why this might be occurring?
>
>   Connect to queue manager
>   """
> try:
>   self.qm = mq.QueueManager(options.qmanager.upper() )
>   self.qm.begin()
>   except mq.PYIFError, err:
> mqevlog.event("error",err)
>   sys.exit(1)
>
>   queue = mq.Queue(self.qm, self.queue_name)
> pmo = mq.pmo(Options = CMQC.MQPMO_SYNCPOINT)
> md = mq.md()
> Any help/insight you can provide on this would be greatly appreciated.
(edited)

Andrew
Don't know if you still need help with the above. I am new to Python
and was searching for MQ interfaces with Python and found your
question. Having some coding (C) experience with MQ Series it appears
that you are performing a local unit of work coodinated by the Queue
Manager only. In this scenario you do not specify the mqbegin as it
implies an external resource manager will be involved. Under your PMOs
you have specified the messages are to be extracted under syncpoint
control which is all you need. The messages should be remain in the
queue if there is an mqback call or the application ends without a
disconnect. In my experience while the messages are preserved in the
queue any partial file write to the OS will be left after the backout
(in the case of space issues). Your code will have to do the
housekeeping. 

best regards,
-JonS

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Diez B. Roggisch
> You mean:
> 
> class Pythonic(object):
> def __init__(self):
>   self._is_active = True
> 
> @apply
> def is_active():
>   def fget(self): return self._is_active
>   def fset(self): raise SomeException('sorry, read-only')
>   return property(**locals())

Neat! That slipped my attention over all this noisy and pointless 
discussion...

Regards,

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Bruno Desthuilliers wrote:
> >
> (snip)
> >You use accessors when you need to control access to a data attribute.
> 
> Indeed. And when you don't need too ? (the second 'o' is not a typo)
> 
> >>>
> >>>
> >>>You make the attribute private/protected.
> >>
> >>doh :(
> >>
> >>Let's talk about psychorigid mindset...
> >>
> >
> >
> > Thanks, I'm insane.
>
> You say so.
>

> (snip)
> >>Then why do you advise "(making) all attributes of a class
> >>private/protected" and systematically using properties ?
> >>
> >
> >
> >Because you don't want third parties illegimately tampering with an
> >object's internal data and thus crashing your system?
> 
> Let's try again...
> 
> point 1 : there's *no* language-inforced access restriction in Python.
> Just a *convention*.
> 
> >>>
> >>>
> >>>Huh? What are properties for then?
> >>
> >>To allow attribute syntax when you really have computation behind. Which
> >> 1/ let you start with the simplest case (a simple attribute) and change
> >>your mind latter
> >>2/ offer the possibility to use an attribute syntax (instead of a method
> >>call syntax) when it seems more natural.
> >>
> >
> >
> > Right, and what I'm I trying to do again?
> >
>
> Write Java in Python.
>

Dude, I haven't written more than "Hello World" programs in Java. I
__don't__ have a strong Java background.

> point 2 : so anyone *can* "illegimately tampering with an object's
> internal data" at will.
> 
> >>>
> >>>And this is robust how?
> >>>
> >>
> >>You can do just the same in Java or C++.
> >>
> >
> >
> > OMG!
>
> It's common knowledge.
>

I ask how your solution is robust, and you go off talking about Java
and C++. Quit turning this into a language pissing contest. The hell I
care what Java or C++ does.

> >
> point 3 : anyway it's not *my* system that will then crash - but the
> system of the one who "illegimately" played with my package's objects
> internals. And as far as I'm concerned, it's none of my problem - they
> were marked as implementation, so anyone playing with them is on it's
> own. FWIW, I suspect that if someone want to muck with implementation,
> he certainly has a good legitimate reason to do so, and will do her best
> to not break anything. Else he's a complete idiot and there's no cure
> for this.
> 
> >>>
> >>>
> >>>You can't be serious. Please tell me you are joking.
> >>
> >>I'm deadly serious and definitively not joking. There's no cure for
> >>idiocy, and there's definitively nothing like an idiot-proof system.
> >>
> >
> > Sure, but calling users idiots for as result of your laziness or poor
> > design or lack of robustness is equally idiotic.
>
> Ok, then 99.99% of Python programmers are lazy, have poor design skills
> and are unable to write a robust application. So they are idiotic too.
>

If you say so.

> point 4 : since we have computed attributes, turning a "public data
> attribute" (to use your idiom) into a "private/protected data attribute
> with accessors" *without breaking the interface* is not even a 
> non-brainer.
> 
> Now, please, can you explain the difference between :
> 
> class Complicated(object):
>  def __init__(self, data):
>    self.data = data
>  def _get_data(self):
>    return self._data
>  def _set_data(self, data):
>    self._data = data
> 
> and
> 
> class Pragmatic(object):
>  def __init__(self, data)
>    self.data = data
> 
> 
> and find any *valid* reason to use the first solution instead of the
> second ? ('that's what the book says' not being a valid reason).
> 
> >>>
> >>>
> >>>I don't know it's your code not mine.
> >>
> >>IOW : you're unable to find any valid reason to use the second solution
> >>instead of the first (of course : there's none), but refuse to admit it.
> >>
> >
> > Hey, I didn't write that code. You did! You deal with it. My input on
> > __your__ code at this point is irrelevant.
>
> It's totally relevant, and you're still unable to come with any valid
> reason to prefer the first solution over the second. I'm totally
> confident that if there was *any* defendable reason to favor the first
> approach, you'd have chosen to answer instead of playing dumb.
>

Chosen what answer? First of all, I have no idea what you are trying to
do.  Secondly, I wouldn't code like that. So asking for my input on
some code that I believe has no purpose is irrelevant. In your class,
Complicated, why are your accessors private? Why is the attribute the
accessors are modifying public? In your second class, can data afford
to be modified by anyone? Does doing that cause any corruption, bugs,
indiscrepancies in the system? You can't just throw code at me, out of
context, and tell me to choose which is better. It's just premature.

> >>>class Robust(object):
> >>>
> >>>   def __init__(

strange error when importing a module

2006-07-20 Thread Robin Becker
I'm trying to understand the following strangeness

C:\code\rlextra\ers>python
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.
 >>> from rlextra.utils.SimpleXMLRPCServer import SimpleXMLRPCServer
Traceback (most recent call last):
   File "", line 1, in ?
   File "c:\code\rlextra\utils\SimpleXMLRPCServer.py", line 148, in ?
 import pydoc
   File "C:\Python\lib\pydoc.py", line 54, in ?
 import sys, imp, os, re, types, inspect, __builtin__
   File "C:\Python\lib\inspect.py", line 31, in ?
 import sys, os, types, string, re, dis, imp, tokenize, linecache
   File "C:\Python\lib\tokenize.py", line 38, in ?
 COMMENT = N_TOKENS
NameError: name 'N_TOKENS' is not defined

SimpleXMLRPCServer.py is a legacy version of the current SimpleXMLRPCserver 
code. I don't think there's anything special about it and as a standalone 
script 
it appears to work fine (ie it seems to compile and run).

Any ideas?
-- 
Robin Becker

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


Re: Depricated String Functions in Python

2006-07-20 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Steve Holden <[EMAIL PROTECTED]> wrote:

> Anoop wrote:
> > Thanks Stefen
> > 
> > let me be more specific how would i have to write the following
> > function in the deprecated format
> > 
> > map(string.lower,list)
> > 
> To avoid the deprecated usage you would use the unbound method of the 
> str type (that's the type of all strings):
> 
>   >>> lst = ['Steve', 'Holden']
>   >>> map(str.lower, lst)
> ['steve', 'holden']

Oh, excellent - the string module is dead, long live
the string module!  I can replace string.join with
str.join, and never have to defile my code with that
' '.join(x) abomination.


   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coding style

2006-07-20 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Antoon Pardon <[EMAIL PROTECTED]> wrote:
> On 2006-07-19, Donn Cave <[EMAIL PROTECTED]> wrote:
...
> > http://groups.google.com/group/comp.lang.python/msg/2de5e1c8384c0360
> >
> > It's lengthy but very readable, and for me it has that quality of
> > exposition where you feel at first reading as though you had
> > already known all that -- even if you really hadn't.
> 
> Well for me it wasn't, I don't agree with it at all.

People sometimes ask, "what does `the exception that proves the rule'
mean?"

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text representation of HTML

2006-07-20 Thread Tim Williams
On 20 Jul 2006 15:12:27 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Ksenia Marasanova wrote:
> > i want to send plain text alternative of html email, and would prefer
> > to do it automatically from HTML source.
> > Any hints?
>
> Use htmllib:
>
> >>> import htmllib, formatter, StringIO
> >>> def cleanup(s):
> out = StringIO.StringIO()
> p = htmllib.HTMLParser(
> formatter.AbstractFormatter(formatter.DumbWriter(out)))
> p.feed(s)
> p.close()
> if p.anchorlist:
> print >>out
> for idx,anchor in enumerate(p.anchorlist):
> print >>out, "\n[%d]: %s" % (idx+1,anchor)
> return out.getvalue()
>
> >>> print cleanup('''TitleThis is a  />test''')
>
> Title
>
> This is a
> test
> >>> print cleanup('''TitleThis is a test with  href="http://python.org";>a link to the Python homepage''')
>
> Title
>
> This is a
> test with a link[1] to the Python homepage
>
> [1]: http://python.org
>

cleanup()  doesn't handle script and styles too well.  html2text will
do a much better job of these and give a more structured output
(compatible with Markdown)

http://www.aaronsw.com/2002/html2text/

>>> import html2text
>>> print html2text.html2text('''TitleThis is a test with http://python.org";>a link to the Python
homepage''')

# Title

This is a
test with [a link][1] to the Python homepage

[1]: http://python.org


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


Re: strange error when importing a module

2006-07-20 Thread Robin Becker
Robin Becker wrote:
> I'm trying to understand the following strangeness
> 
> C:\code\rlextra\ers>python
> 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.
>  >>> from rlextra.utils.SimpleXMLRPCServer import SimpleXMLRPCServer
> Traceback (most recent call last):
>File "", line 1, in ?
>File "c:\code\rlextra\utils\SimpleXMLRPCServer.py", line 148, in ?
>  import pydoc
>File "C:\Python\lib\pydoc.py", line 54, in ?
>  import sys, imp, os, re, types, inspect, __builtin__
>File "C:\Python\lib\inspect.py", line 31, in ?
>  import sys, os, types, string, re, dis, imp, tokenize, linecache
>File "C:\Python\lib\tokenize.py", line 38, in ?
>  COMMENT = N_TOKENS
> NameError: name 'N_TOKENS' is not defined
> 
> SimpleXMLRPCServer.py is a legacy version of the current SimpleXMLRPCserver 
> code. I don't think there's anything special about it and as a standalone 
> script 
> it appears to work fine (ie it seems to compile and run).
> 
> Any ideas?
grrrh I think we have a relative module import of token somewhere

-- 
Robin Becker

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Bruno Desthuilliers
mystilleef wrote:
> Bruno Desthuilliers wrote:

>>point 2 : so anyone *can* "illegimately tampering with an object's
>>internal data" at will.
>>
>
>And this is robust how?
>

You can do just the same in Java or C++.

>>>
>>>
>>>OMG!
>>
>>It's common knowledge.
>>
> I ask how your solution is robust,

This is definitively not a problem with "my solution". Python has *no*
access restriction. Anyone can do what he wants with any attribute of
your Python classes.

> and you go off talking about Java
> and C++. 

Whose access restriction is Joke.

> 
>>point 3 : anyway it's not *my* system that will then crash - but the
>>system of the one who "illegimately" played with my package's objects
>>internals. And as far as I'm concerned, it's none of my problem - they
>>were marked as implementation, so anyone playing with them is on it's
>>own. FWIW, I suspect that if someone want to muck with implementation,
>>he certainly has a good legitimate reason to do so, and will do her best
>>to not break anything. Else he's a complete idiot and there's no cure
>>for this.
>>
>
>
>You can't be serious. Please tell me you are joking.

I'm deadly serious and definitively not joking. There's no cure for
idiocy, and there's definitively nothing like an idiot-proof system.

>>>
>>>Sure, but calling users idiots for as result of your laziness or poor
>>>design or lack of robustness is equally idiotic.
>>
>>Ok, then 99.99% of Python programmers are lazy, have poor design skills
>>and are unable to write a robust application. So they are idiotic too.
>>
> If you say so.

Logical derivation from your above statement.

> 
>>point 4 : since we have computed attributes, turning a "public data
>>attribute" (to use your idiom) into a "private/protected data attribute
>>with accessors" *without breaking the interface* is not even a 
>>non-brainer.
>>
>>Now, please, can you explain the difference between :
>>
>>class Complicated(object):
>>def __init__(self, data):
>>  self.data = data
>>def _get_data(self):
>>  return self._data
>>def _set_data(self, data):
>>  self._data = data
>>
>>and
>>
>>class Pragmatic(object):
>>def __init__(self, data)
>>  self.data = data
>>
>>
>>and find any *valid* reason to use the first solution instead of the
>>second ? ('that's what the book says' not being a valid reason).
>>
>
>
>I don't know it's your code not mine.

IOW : you're unable to find any valid reason to use the second solution
instead of the first (of course : there's none), but refuse to admit it.

>>>
>>>Hey, I didn't write that code. You did! You deal with it. My input on
>>>__your__ code at this point is irrelevant.
>>
>>It's totally relevant, and you're still unable to come with any valid
>>reason to prefer the first solution over the second. I'm totally
>>confident that if there was *any* defendable reason to favor the first
>>approach, you'd have chosen to answer instead of playing dumb.
>>
>  
> Chosen what answer? First of all, I have no idea what you are trying to
> do. 

Make you understand why, in Python, it is *totally* useless to mark an
attribute as implementation and add read/write accessors to it. But it's
obviously hopeless.

> Secondly, I wouldn't code like that. So asking for my input on
> some code that I believe has no purpose is irrelevant. In your class,
> Complicated, why are your accessors private?

They are not "private", they are implementation details - in this case,
support for a property.

> Why is the attribute the
> accessors are modifying public?

It is not public, it is marked as implementation detail - in this case,
support for a property.

> In your second class, can data afford
> to be modified by anyone? 

Obviously - just like in the first example.

>Does doing that cause any corruption, bugs,
> indiscrepancies in the system? You can't just throw code at me, out of
> context, and tell me to choose which is better. It's just premature.

If you are unable to understand such a simple code then you are totally
clueless. Since your are obviously not totally clueless, it's just bad
faith from you. So I'm obviously wasting my time and bandwidth.

(snip)
>See! I'm controlling access.

You are not controlling *anything*

r = Robust()
r._Robust__is_active = True

>>>
>>>
>>>*sighs*
>>>
>>>You keep coming up with these unrealistic and impractically delusional
>>>theories
>>
>>Pardon ? Which "unrealistic and impractically delusional theories" ?
>>Please try the code above instead of getting to big words...
>> 
> 
> Doesn't that fall under the "DO NOT DO THIS AT HOME KIDS" in the FAQ
> section or somewhere?

Nope. It falls under the "dont do this unless you really need to and
know exactly what you are doing and accept all possible consequences -
IOW you're on your 

Re: Accessors in Python (getters and setters)

2006-07-20 Thread Ant
Came across this article this afternoon - thought it may be of interest
to some of those following this thread...

http://www.devx.com/opensource/Article/31593/0/page/2

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread Gerhard Fiedler
On 2006-07-20 09:40:31, Bruno Desthuilliers wrote:

>> I'm not sure, but there's one thing that has a potential to be the real
>> issue: what's the common way to create a property that is read-write
>> for the implementation and "read-only" for the interface? 
> 
> class Foo(object):
>   @apply
>   def _imp():
> def fget(self):
>   # code here
> def fset(self, val):
>   # code here
> return property(**locals())
> 
>   @apply
>   def api():
> def fget(self):
>   return self._imp
> def fset(self, val):
>   raise SomeException('read-only, sorry')
> return property(**locals())

Thanks a lot. This looks similar to what Steve Holden wrote. (And yes,
Steve, you understood exactly what I meant :)

My hunch is that this is what mystilleef might have wanted to say all
along; it looks quite similar to what he seemed to try to express. It's
basically the Python synonym of creating a public accessor (api) for a
private attribute (_imp) -- in this case to make the API read-only while
maintaining the implementation read-write, but I'm sure there are other
uses for such a structure. 


> Note that a read-only property named 'is_active' returning the value of
> an attribute named '_is_active' doesn't prevent direct access to
> '_is_active' attribute, neither from the class nor from the client code.

Right; I already understood that :)

I just thought one part of this whole thread was that accessors are not
necessary in Python. However, it seems that this case -- different
restrictions (or actions) for access from implementation vs through the API
(which is probably one of the most common reasons for using accessors in
other languages) -- in Python also can only be handled by adding a separate
accessor. (This of course in Python is implemented as a computed
attribute.)

The above illustrated technique doesn't look so different from a C++ or
Java code with public set/getApi() accessors acting on a private imp
attribute (or public set/getIsActive() accessors acting on a private
isActive attribute -- to use the other, similar example that operates with
the names this thread likes to use :)

Do I seem to understand this correctly?

Thanks,
Gerhard

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


Using python code from Java?

2006-07-20 Thread fortepianissimo
Is there a solution to enable Java programmers to call functions
written in Python? Any wrapper generator that wraps Python code into
some Java-callable form?

I briefly looked at Jython, but if I understand it right, it didn't
support full power of Python 2.3.x (which I need).

Any suggestion is welcome!

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


Re: Warning when new attributes are added to classes at run time

2006-07-20 Thread Nick Vatamaniuc
Use __slots__ they will simply give you an error. But at the same time
I don't think they are inheritable and in general you should only use
slots for performance reasons (even then test before using).

Or you could also simulate a __slots__ mechanism the way you are doing
i.e. checking the attributes yourself. But I would suggest though that
you create a test case (unittest) and run testing _separately_ from
your code. Your code should do only what it does, too many  "if i
messed: up warn me" or "need to make sure I don't have extra
attributes" checks would make the code itself incomprehnsible over time
as half of it would end up being just checks for exceptional
situations. So spend 5 minutes to look up
http://pyunit.sourceforge.net/ and then in the long run your effort to
implement testing will be rewarded.

Nick V.



Matthew Wilson wrote:
> I sometimes inadvertently create a new attribute on an object rather
> update a value bound to an existing attribute.  For example:
>
> In [5]: class some_class(object):
>...:  def __init__(self, a=None):
>...:  self.a = a
>...:
>
> In [6]: c = some_class(a=1)
>
> In [7]: c.a
> Out[7]: 1
>
> In [8]: c.A = 2
>
> I meant to update c.a but I created a new c.A.  I make this mistake
> probably hourly.
>
> I suspect adding attributes at run time can be a beautiful thing, but in
> this particular instance, I'm only using this feature to hurt myself.
>
> I wrote a simple class that will warn me when I make this mistake in the
> future:
>
> import warnings
>
> class C(object):
>
> warn_on_new_attributes = True
>
> standard_attributes = []
>
> def __setattr__(self, name, value):
>
> if self.warn_on_new_attributes \
> and name is not 'warn_on_new_attributes' \
> and name not in self.standard_attributes:
>
> warnings.warn("%s has no standard attribute %s."
>   % (self.__class__.__name__, name))
>
>
> self.__dict__[name] = value
>
>
> class C1(C):
>
> standard_attributes = ['a1', 'a2']
>
>
> class C2(C):
>
> warn_on_new_attributes = False
>
> # Do some simple testing.
> c11 = C1()
> c11.a1 = 1
> c11.a2 = 2
> c11.a3 = 3
> c11.a4 = 4
>
> # Disable warnings for this instance.
> c12 = C1()
> c12.warn_on_new_attributes = False
> c12.a1 = 1
> c12.a2 = 2
> c12.a3 = 3
> c12.a4 = 4
>
> c11.a5 = 5
>
> # Use an object that has warnings disabled by default.
> c2 = C2()
> c2.a1 = 1
> c2.a2 = 2
> c2.a3 = 3
> c2.a4 = 4
>
> # enable warnings for this object.
> c2.warn_on_new_attributes = True
> c2.a1 = 1
> c2.a5 = 5
>
>
> All comments are welcome.  Is there a better way of implementing the
> above class, OR, is this approach generally wrong-headed?  Am I the only
> one that makes this mistake?
>
> TIA
>
> --
> A better way of running series of SAS programs:
> http://overlook.homelinux.net/wilsonwiki/SasAndMakefiles

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


Re: Using python code from Java?

2006-07-20 Thread Diez B. Roggisch
fortepianissimo schrieb:
> Is there a solution to enable Java programmers to call functions
> written in Python? Any wrapper generator that wraps Python code into
> some Java-callable form?
> 
> I briefly looked at Jython, but if I understand it right, it didn't
> support full power of Python 2.3.x (which I need).
> 
> Any suggestion is welcome!

CORBA or any other RPC mechanism supported by both python & Java springs 
to mind.

Waiting for jython2.3 might be an option, too - things are pretty much 
on the move right now.

Diez

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


ConfigParser: what read('non-existent-filename') returns in 2.3.x?

2006-07-20 Thread Danil Dotsenko
Wrote a little "user-friedly" wrapper for ConfigParser for a KDE's
SuperKaramba widget.
(http://www.kde-look.org/content/show.php?content=32185)

I was using 2.4.x python docs as reference and
ConfigParser.read('non-existent-filename') returns [] in 2.4.x

One user with 2.3.x reported an error stemming from my use of 
len(cfgObject.read('potentially-non-existent-filename'))

File "/home/web/Downloads/afoto-1.5b6.skz/localConf.py", line 53, in load
TypeError: len() of unsized object

Can anyone tell me what cfgObject.read('potentially-non-existent-filename')
returns in 2.3.x?

My output:
>>> import ConfigParser
>>> cfg = ConfigParser.ConfigParser()
>>> a = cfg.read('adsfasfdasfd')
>>> a, len(a), type(a)
([], 0, )

Thx in advance.

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


Re: Using python code from Java?

2006-07-20 Thread fortepianissimo

Diez B. Roggisch wrote:
> fortepianissimo schrieb:
> > Is there a solution to enable Java programmers to call functions
> > written in Python? Any wrapper generator that wraps Python code into
> > some Java-callable form?
> >
> > I briefly looked at Jython, but if I understand it right, it didn't
> > support full power of Python 2.3.x (which I need).
> >
> > Any suggestion is welcome!
>
> CORBA or any other RPC mechanism supported by both python & Java springs
> to mind.

Thanks for the tip - but anything tighter than that? Dealing with
multiple servers within one application is a bit too much for my
project...

> Waiting for jython2.3 might be an option, too - things are pretty much
> on the move right now.

Any idea how soon that will be?

Thanks!

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


Re: using capicom with python

2006-07-20 Thread stéphane bard
thank's for all roger
sorry to answer so late
:-D

Roger Upole a écrit :
> "stéphane bard" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>> Hi all,
>> Has anyone ever used Python to work with Certificate Services in
>> Windows? I'm trying to capicom dll with pywin32.
>>
>>
>> I've found some reference about python and capicom in
>> this mail archive
>> http://mail.python.org/pipermail/python-win32/2006-March.txt
>>
>> but nothing really helpfull.
>> I try to use windll from ctypes module
>>
>>
 windll.load(
>> but don't get access to capicom.
>>
>> any idea ?
> 
> COM dll's usually aren't designed to be used directly.
> You request instances of the interfaces they implement
> by guid or program id.
> 
> import win32com.client
> certstore=win32com.client.Dispatch('capicom.store')
> certstore.Open(StoreName='Root')
> for cert in certstore.Certificates:
> print 'SubjectName:', cert.SubjectName, 'IssuerName:', cert.IssuerName
> 
> Roger
> 
> 
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Needed. Removing a Folder Problem(Problem Solved)

2006-07-20 Thread Steve Holden
Kilicaslan Fatih wrote:
[...]
> Dear All,
> 
> I changed the mode of the files before copying them.
> So the problem is solved as follows:
> 
> SOLUTION:
> 
> def run(self, event):
> cmd_out = self.A_com()
> if App.runF != "":
> os.mkdir('C:\copiedFiles')
>   
> for item in App.runF:
> os.chmod(item, 0700)
> shutil.copy(item, 'C:\copiedFiles')   
>   
> cmd = ' C:\copiedFiles\*.*' + cmd_out
> os.system(cmd)
> for root,dir,files in
> os.walk("C:\copiedFiles"):
>   
> shutil.rmtree('C:\copiedFiles')
> else:
> tkMessageBox.showinfo("Window Text",
> "Please Firstly Browse and Insert A File")
> 
Just be careful with those string constants: you should really be using 
either 'C:\\copiedFiles' or r'C:\copiedFiles'. No problems at the moment 
because "\c" isn't a defined escape sequence, but if your directory name 
had begun with a "t", for example, you'd have got a tab after the colon.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


wx.ListCtrl - I do not see the inserted item

2006-07-20 Thread Laszlo Nagy
This is a ListCtrl descendant:

class MegaListCtrl(wx.ListCtrl):
 

def InsertImageStringItem(self, index, label, imageIndex):
imageIndex = 
self.imagelists[wx.IMAGE_LIST_SMALL].GetIndexByName(imageIndex)
print index,imageIndex,label,imageIndex
super(MegaListCtrl,self).InsertImageStringItem(index, label, 
imageIndex)

 

Here I create the list control instance:

lst = self.lstExtTables = MegaListCtrl(pnl,-1,style=wx.LC_REPORT)
   
info = wx.ListItem()
info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | 
wx.LIST_MASK_FORMAT
info.m_image = -1
info.m_format = 0
info.m_text = _("Table name")
lst.InsertColumnInfo(0, info)  
sizer.Add(lst,proportion=1,flag=wx.EXPAND)

 

Here I try to add some items:

if not extdbdef is None:
for tblref in extdbdef.tables:
tbl = tblref()
if not tbl is None:
print str(tbl.name)
lst.InsertImageStringItem(sys.maxint, 
str(tbl.name), 'table')


This is the output of the program:

C:/Python24/pythonw.exe -u  "T:/Python/Lib/mess/utils/DbSchemaDesigner.py"
client
2147483647 248 client 248
jn_client
2147483647 248 jn_client 248


However, the ListCtrl displays empty. I can see the gray column header, 
but it has not text. The two items are probably added, because 
InsertImageStringItem did not raise an exception, but the items are not 
visible.

Do you have an idea what can be the problem?

Thanks,

Laszlo

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


Re: Depricated String Functions in Python

2006-07-20 Thread Steve Holden
Donn Cave wrote:
[...]
> 
> Oh, excellent - the string module is dead, long live
> the string module!  I can replace string.join with
> str.join, and never have to defile my code with that
> ' '.join(x) abomination.
> 
  >>> lst = ['Steve', 'Holden']
  >>> str.join(' ', lst)
'Steve Holden'
  >>>

Just so long as you don't complain about the arguments being in the 
wrong order ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Using python code from Java?

2006-07-20 Thread Nick Vatamaniuc
I can't think of any project that does that. Calling stuff from Java is
not easy to beging with you have to go through the native interface
(JNI) anyway.

I would suggest instead to create some kind of a protocol and let the
applications talk using an external channel (a FIFO pipe file, a socket
or just any network connection.) Usually when you go back and forth
between languages you don't really need a particular class object
(because class objects are quite different between languages) but what
you need is to have data passed back and forth and have both sides
interpret the data and process it. This sort of sounds like a protocol
and it is. Depending on how easy vs. extensible vs. comprehensible your
project is you  could of course use XML RPC but that could get
complicated.

 If you have extra time and desire you can of course contribute and
help bring Jython to 2.3, they can always use some help...

Nick V.


fortepianissimo wrote:
> Is there a solution to enable Java programmers to call functions
> written in Python? Any wrapper generator that wraps Python code into
> some Java-callable form?
>
> I briefly looked at Jython, but if I understand it right, it didn't
> support full power of Python 2.3.x (which I need).
> 
> Any suggestion is welcome!

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


Re: Accessors in Python (getters and setters)

2006-07-20 Thread mystilleef

Bruno Desthuilliers wrote:
> mystilleef wrote:
> > Bruno Desthuilliers wrote:
>
> >>point 2 : so anyone *can* "illegimately tampering with an object's
> >>internal data" at will.
> >>
> >
> >And this is robust how?
> >
> 
> You can do just the same in Java or C++.
> 
> >>>
> >>>
> >>>OMG!
> >>
> >>It's common knowledge.
> >>
> > I ask how your solution is robust,
>
> This is definitively not a problem with "my solution". Python has *no*
> access restriction. Anyone can do what he wants with any attribute of
> your Python classes.
>
> > and you go off talking about Java
> > and C++.
>
> Whose access restriction is Joke.
>
> >
> >>point 3 : anyway it's not *my* system that will then crash - but the
> >>system of the one who "illegimately" played with my package's objects
> >>internals. And as far as I'm concerned, it's none of my problem - they
> >>were marked as implementation, so anyone playing with them is on it's
> >>own. FWIW, I suspect that if someone want to muck with implementation,
> >>he certainly has a good legitimate reason to do so, and will do her best
> >>to not break anything. Else he's a complete idiot and there's no cure
> >>for this.
> >>
> >
> >
> >You can't be serious. Please tell me you are joking.
> 
> I'm deadly serious and definitively not joking. There's no cure for
> idiocy, and there's definitively nothing like an idiot-proof system.
> 
> >>>
> >>>Sure, but calling users idiots for as result of your laziness or poor
> >>>design or lack of robustness is equally idiotic.
> >>
> >>Ok, then 99.99% of Python programmers are lazy, have poor design skills
> >>and are unable to write a robust application. So they are idiotic too.
> >>
> > If you say so.
>
> Logical derivation from your above statement.
>
> >
> >>point 4 : since we have computed attributes, turning a "public data
> >>attribute" (to use your idiom) into a "private/protected data attribute
> >>with accessors" *without breaking the interface* is not even a 
> >>non-brainer.
> >>
> >>Now, please, can you explain the difference between :
> >>
> >>class Complicated(object):
> >>def __init__(self, data):
> >>  self.data = data
> >>def _get_data(self):
> >>  return self._data
> >>def _set_data(self, data):
> >>  self._data = data
> >>
> >>and
> >>
> >>class Pragmatic(object):
> >>def __init__(self, data)
> >>  self.data = data
> >>
> >>
> >>and find any *valid* reason to use the first solution instead of the
> >>second ? ('that's what the book says' not being a valid reason).
> >>
> >
> >
> >I don't know it's your code not mine.
> 
> IOW : you're unable to find any valid reason to use the second solution
> instead of the first (of course : there's none), but refuse to admit it.
> 
> >>>
> >>>Hey, I didn't write that code. You did! You deal with it. My input on
> >>>__your__ code at this point is irrelevant.
> >>
> >>It's totally relevant, and you're still unable to come with any valid
> >>reason to prefer the first solution over the second. I'm totally
> >>confident that if there was *any* defendable reason to favor the first
> >>approach, you'd have chosen to answer instead of playing dumb.
> >>
> >
> > Chosen what answer? First of all, I have no idea what you are trying to
> > do.
>
> Make you understand why, in Python, it is *totally* useless to mark an
> attribute as implementation and add read/write accessors to it. But it's
> obviously hopeless.
>
> > Secondly, I wouldn't code like that. So asking for my input on
> > some code that I believe has no purpose is irrelevant. In your class,
> > Complicated, why are your accessors private?
>
> They are not "private", they are implementation details - in this case,
> support for a property.
>
> > Why is the attribute the
> > accessors are modifying public?
>
> It is not public, it is marked as implementation detail - in this case,
> support for a property.
>
> > In your second class, can data afford
> > to be modified by anyone?
>
> Obviously - just like in the first example.
>
> >Does doing that cause any corruption, bugs,
> > indiscrepancies in the system? You can't just throw code at me, out of
> > context, and tell me to choose which is better. It's just premature.
>
> If you are unable to understand such a simple code then you are totally
> clueless. Since your are obviously not totally clueless, it's just bad
> faith from you. So I'm obviously wasting my time and bandwidth.
>
> (snip)
> >See! I'm controlling access.
> 
> You are not controlling *anything*
> 
> r = Robust()
> r._Robust__is_active = True
> 
> >>>
> >>>
> >>>*sighs*
> >>>
> >>>You keep coming up with these unrealistic and impractically delusional
> >>>theories
> >>
> >>Pardon ? Which "unrealistic and impractically delusional theories" ?
> >>Please try the code

ImportError: libclntsh.so.10.1: cannot open shared object file: Permission denied

2006-07-20 Thread gmax2006
Hi,

I am using RedHat Linux 4. and I developed an oracle 10g based
application by using cx_Oracle (cx_Oracle-4.1-10g-py23-1.i386.rpm) and
Python 2.3.4.

When I run the application through direct console connection, It works
perfect.

But, when I schedule a crontab job to run the application, It logs this
error:

Traceback (most recent call last):
  File "/home/nsm1/NSM1/NSM1.py", line 5, in ?
import cx_Oracle
ImportError: libclntsh.so.10.1: cannot open shared object file:
Permission denied


How can I fix the problem?

Any help would be appreciated,
Max

BTW:

I have the following settings in my /etc/profile file:

#---
ORACLE_BASE=/home/oracle/oracle/product
ORACLE_HOME=$ORACLE_BASE/10.2.0/db_1
LD_LIBRARY_PATH=$ORACLE_HOME/lib
PATH=$PATH:$ORACLE_HOME/bin
ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data
export ORACLE_BASE ORACLE_HOME ORACLE_SID LD_LIBRARY_PATH PATH
#---

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


Re: using names before they're defined

2006-07-20 Thread davehowey
Hiya

Could you just talk me through this... is it:

> schema = {'turbine1': {'class': 'Turbine',
>'upstream' : ('frobnicator2',),
>'downstream' : () # nothing,
>},
>   'frobnicator2' : {'class' : 'Frobnicator',
> 'upstream' : (),
> 'downstream' : ('frobnicator2',),
>},
>  }
>

ok, so schema is a dictionary of different components, defining what
class they are and what they're connected to.

> def get_class_by_name(name):
>   return globals()[name]

what does this function do exactly?

> def chain_from_schema(schema):
>   objects = {}   # so objects is our list of objects ?
>   for name, desc in schema:   # can you step through a dictionary like this?
>  klass =  get_class_by_name(desc['class'])   # does this create an object 
> called klass?
>  objects[name] = klass()


sorry for being dim..
Dave

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


  1   2   >