Re: functions, list, default parameters

2010-11-03 Thread Bruno Desthuilliers

Lawrence D'Oliveiro a écrit :
In message 20101021235138.609fe...@geekmail.invalid, Andreas Waldenburger 
wrote:



While not very commonly needed, why should a shared default argument be
forbidden?


Because it’s safer to disallow it than to allow it.


Then there are quite a few python features (or misfeatures depending on 
your personal tastes and whatnot) that should be disabled too. What 
about rebinding some_object.__class__ ?-)


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


Re: Python documentation too difficult for beginners

2010-11-02 Thread Bruno Desthuilliers

jk a écrit :

Hi,

I've been coding in PHP and Java for years, and their documentation is
concise, well structured and easy to scan.

Others have mentioned this apparently for years (see:
http://stackoverflow.com/questions/4046166/easy-to-navigate-online-python-reference-manual/4070851
and http://www.russellbeattie.com/blog/python-library-docs-still-suck
and http://xahlee.org/perl-python/xlali_skami_cukta.html).


Totally unrelated, but the last example is nothing but a reference - 
xahlee is one of the worst internet troll ever.




Compare for instance the differences in ease of use, and speed of use,
of these:

http://docs.python.org/library/functions.html#open
http://uk.php.net/manual/en/function.fopen.php


Sorry but as far as I'm concerned, PHP doc sucks big time, and I find 
Javadoc-style stuff close to useless.



(snip)


Has anyone else struggled while trying to learn the language?


Not as far as I'm concerned. I found Python the easiest language to 
learn right from the beginning. Not to say the doc couldn't be improved, 
or that alternate documentations could help, but I never had any problem 
with it.



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


Re: singleton problems

2010-10-03 Thread Bruno Desthuilliers
jimgardener a écrit :
 hi Steven,
 can you explain that?I didn't quite get it.
 I have a module say 'managerutils' where I have a class
 MyManager..

What Steven was talking about was to NOT use a class at all. Modules are
objects and have their own namespace. And you can use threading.locals
instead of the module's global namespace if you want to be safe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sequence multiplied by -1

2010-10-03 Thread Bruno Desthuilliers
Stefan Schwarzer a écrit :

 One could argue that using L[::-1] isn't obvious

It *is* obvious - once you've learned slicing. obvious doesn't mean
you shouldn't bother reading the FineManual.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling an arbitrary function with the right arguments

2010-09-27 Thread Bruno Desthuilliers

John O'Hagan a écrit :
How to call a function with the right arguments without knowing in advance 
which function? 


(snip)

For most use case I can think of, I can only second Steven and Chris - 
if your functions are interchangeable then they should have a same API.


Now there's at least one use case I know where you need to dynamically 
select a function then build the right arguments set for it: when 
mapping urls to http request handler functions. There's a good example 
in Django's url to view mapping system.

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


Re: This Is International Don’t-Squawk-Like-A -Parrot Day

2010-09-22 Thread Bruno Desthuilliers

Lawrence D'Oliveiro a écrit :
Next we need an International Surfin’ Bird day, a day to go around and tell 
everybody that the bird bird bird, the bird is the word.


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


Re: newbie: class and __dict__ variable.

2010-09-20 Thread Bruno Desthuilliers

Terry Reedy a écrit :

On 9/19/2010 1:37 PM, mafeu...@gmail.com wrote:


Hallo Group Members. From time to time I see in python code following
notation that (as I believe) extends namespace of MyClass.


No, it does not affect MyClass, just the instance dict.


class MyClass:
 def __init__(self):
 self.__dict__[maci]=45


Have you seen exactly this usage?



myCl2 = MyClass2()
print myCl2.maci


I am guessing that there must be some difference between the one above
and the one below, because otherwise no one would probably use the one
above. Do YOu know that difference?

class MyClass2:
 def __init__(self):
 self.maci=45


If the class has a .__setattr__ method, the first bypasses that method,


It also bypasses object.__setattribute__ and - as a consequence - any 
binding descriptor by the same name as the attribute being set.







myCl = MyClass()
print myCl.maci



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


Re: Learning inheritance

2010-09-20 Thread Bruno Desthuilliers

alex23 a écrit :


Python only actually executes a module the first time it's imported,


Beware of multithreading and modules imported under different names... 
There can be issues with both in some web frameowrks.


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


Re: Learning inheritance

2010-09-20 Thread Bruno Desthuilliers

Niklasro a écrit :

Good to learn what I'm doing :-) since important being able to explain
choices taken farther than doing it because it works.
I understand the concept of modules may not correspond to java
programming where I come from.


Coming from Java - and specially if you only have experience with Java 
-, you'll have to unlearn quite a few things. Python is 100% object - in 
that everything you can bind to a name is an object, including classes, 
functions, methods, and even modules - but it doesn't try to force you 
into using classes when you don't need them.


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


Re: newbie: class and __dict__ variable.

2010-09-20 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Mon, 20 Sep 2010 09:27:25 +0200, Bruno Desthuilliers wrote:


If the class has a .__setattr__ method, the first bypasses that method,

It also bypasses object.__setattribute__ and - as a consequence - any
binding descriptor by the same name as the attribute being set.


__setattribute__ ?



object.__setattribute__

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: type object 'object' has no attribute '__setattribute__'



Duh...
Brain fart, sorry, shouldn't post before I get my dose of coffee :(

Let's do it again:

Terry Reedy a écrit :
 If the class has a .__setattr__ method, the first bypasses that
 method,

All new-style classes have a __setattr__ method - whether inherited from 
object or overridden. object.__setattr__ implements the support for 
binding descriptors, so bypassing it will also bypass all binding 
descriptors.


The right way to avoid infinite recursion when overriding __setattr__ 
is to call on the superclass __setattr__, unless of course you *really* 
know what you're doing...



class BarDescriptor(object):
def __init__(self):
self.val = None

def __set__(self, instance, value):
print stores value elsewhere and trigger some required behaviour
self.val = value * 2

def __get__(self, instance, cls=None):
if instance is None:
return self
print retrieve value from elsewhere and trigger some required 
behaviour

return self.val

# well behaved
class Foo(object):
bar = BarDescriptor()

def __init__(self):
self.bar = 42

def __setattr__(self, name, value):
print override __setattr_ for some reason
super(Foo, self).__setattr__(name, value)


# ugly mess
class Baaz(Foo):
bar = BarDescriptor()

def __init__(self):
self.__dict__['bar'] = 42

def __setattr__(self, name, value):
print override __setattr_ for some reason
self.__dict__[name] == value

 f = Foo()
override __setattr_ for some reason
stores value elsewhere and trigger some required behaviour
 f.bar
retrieve value from elsewhere and trigger some required behaviour
84
 f.__dict__
{}
 f.bar = 33
override __setattr_ for some reason
stores value elsewhere and trigger some required behaviour
 f.bar
retrieve value from elsewhere and trigger some required behaviour
66
 f.__dict__
{}
 b = Baaz()
 b.__dict__
{'bar': 42}
 b.bar
retrieve value from elsewhere and trigger some required behaviour
 b.bar = 33
override __setattr_ for some reason
 b.bar
retrieve value from elsewhere and trigger some required behaviour
 b.__dict__
{'bar': 42}









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


Re: elementwise multiplication of 2 lists of numbers

2010-09-20 Thread Bruno Desthuilliers

harryos a écrit :

hi
I have 2 lists of numbers,say
x=[2,4,3,1]
y=[5,9,10,6]
I need to create another list containing
z=[2*5, 4*9, 3*10, 1*6]  ie =[10,36,30,6]

I did not want to use numpy or any Array types.I tried to implement
this in python .I tried the following

z=[]
for a,b in zip(x,y):
z.append(a*b)
This gives me the correct result.Still,Is this the correct way?


If it gives the expected results then it's at least *a* correct way !-)


Or can this be done in a better way?


A list comp comes to mind, as well as using itertools.izip if your lists 
are a bit on the huge side.


from itertools import izip
z = [a * b for a, b in izip(x, y)]


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


Re: program organization question for web development with python

2010-09-17 Thread Bruno Desthuilliers

Hans a écrit :
(snip)


Maybe I did not make my question clear. I never tried python web
programing before, so I want to start from CGI.


You can indeed learn quite a few things doing raw CGI - the most 
important one being why frameworks are a good idea !-)



I read something about web framework like django, but seems it's a
little bit complicated.


Not that much IMHO, but being an early django user I'm probably a bit 
biased. Now Python is known as the language with more web frameworks 
than keywords, so you could probably check some lighter framework like 
 web.py (http://webpy.org/) or flask (http://flask.pocoo.org/).



my task is actually very simple: get search
string from input, and then search database, print search result. I
thought CGI should be good enough to do this.


CGI is good enough to do any web stuff - just like assembler is good 
enough to write any application !-)



I don't have any idea about how to organize those cgi codes, so what
I'm asking is:

1. do I have to have each single file for each hyper-link? Can I put
them together? how?



2. how can I pass a db_cursor to another file?   can I use db_cursor as
a parameter?


Obviously not. FWIW, both questions show a lack of understanding of the 
HTTP protocol, and you can't hope to do anything good in web programming 
if you don't understand at least the basics of the HTTP protocol, 
specially the request/response cycle.


Now for a couple more practical answers:

There are basically two ways to organize your url = code mapping:
1/ have only one cgi script and use querystring params to tell which 
action should be executed.

2/ have one cgi script per action.

The choice is up to you. For a simple app like yours, the first solution 
is probably the most obvious : always display the seach form, if the 
user submitted the form also display the result list. That's how google 
works (wrt/ user interface I mean).


Now if you still need / want to have distinct scripts and want to factor 
out some common code, you just put the common code in a module that you 
import from each script.

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


Re: help with calling a static method in a private class

2010-09-14 Thread Bruno Desthuilliers

Diez B. Roggisch a écrit :

lallous lall...@lgwm.org writes:


How can I keep the class private and have the following work:

[code]
class __internal_class(object):
@staticmethod
def meth1(s):
print meth1:, s

@staticmethod
def meth2(s):
print meth2:,
__internal_class.meth1(s)

x = __internal_class()

x.meth2('sdf')
[/code]


By not using a double underscore. It is effectless on classes anyway
(they are not hidden because of that).


OP
FWIW, if what you want is to mark the class as being implementation (ie: 
not part of your module's API), just prefix it with a single underscore. 
/OP




And additionally, but simply not using staticmethods at all.


+1

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


Re: Refactoring similar subclasses

2010-09-13 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :
I have some code that currently takes four different classes, A, B, C and 
D, and subclasses each of them in the same way:


class MyA(A):
def method(self, x):
result = super(MyA, self).method(x)
if result == spam:
return spam spam spam
return result
# many more methods overloaded


class MyB(B):
def method(self, x):
result = super(MyB, self).method(x)
if result == spam:
return spam spam spam
return result
# many more methods overloaded



If that's really what your code is doing - I mean, calling the super() 
implementation, checking the result and eventually returning something 
else instead - then a simple decorator might be enough... Could even be 
applied by the metaclass.


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


Re: include a file in a python program

2010-09-10 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Mon, 06 Sep 2010 00:57:30 +0200, bussiere bussiere wrote:


i've got a python.txt that contain python and it must stay as it
(python.txt)


Why? Is it against the law to change it? *wink*
 

how can i include it in my program ?
import python.txt doesn't work



You could write a custom importer to handle it, but I can't help you with 
that. Try Google.



is there a way :
a) to make an include(python.txt)
b) tell him to treat .txt as .py file that i can make an import python ?


fp = open(python.txt)
text = fp.read()
fp.close()
exec(text)


or just:

execfile(python.txt)


But keep in mind that the contents of python.txt will be executed as if 
you had typed it yourself. If you don't trust the source with your life 
(or at least with the contents of your computer), don't execute it.


+10

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


Re: inspect the call stack

2010-09-10 Thread Bruno Desthuilliers

bussiere bussiere a écrit :

i v'e got this :
i've got toto.py :

import titi
def niwhom():
pass

and titi.py :

def nipang():
 pass

how can i know in titi.py that's it's toto.py that is calling titi.py
and the path of toto ?

how can i inspect the call stack or an other way ?


http://www.google.fr/search?q=python+inspect+the+call+stack

First answer should point you to the relevant part of the FineManual(tm):
http://docs.python.org/library/inspect.html

ot
And while we're at it, what about not opening a new thread for a 
question already partially answered ?

/ot

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


Re: accessing a text file

2010-09-08 Thread Bruno Desthuilliers

Baba a écrit :


Dear xyz,
Your question can easily be researched online. We suggest you give it
a try and to look it up yourself. This will be beneficial both to you
and to us. We do encourage to ask questions only when they have been
researched first.


On usenet - as well as on most technical forums / mailing lists / etc -, 
this usually condensed in a well-known four letters acronym : RTFM


Hopefully c.l.py is an unusually friendly and polite place, so we tend 
to say it a bit more elegantly and most of the time we do indeed provide 
a link.


This being said and given your attitude - you may not realize it, but by 
now you would have been flamed to hell and back on quite a few other 
newsgroups -, I'm very tempted to switch to option 2.

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


Re: Help needed - function apparently global cannot be called.

2010-09-07 Thread Bruno Desthuilliers

Ian Hobson a écrit :

Hi all you experts,

This has me beat. Has anyone any ideas about what might be going wrong?

This is code from within a windows service (hence no print statements - 
no sys.stdout to print on!).


I am trying to trace through to find where the code is not working. No 
stdout so I have to log to a file.


Then you'd be better using the logging module from the stdlib. And FWIW, 
 you should try to make you code testable in a non-service context...



I have the following code fragments.

def log(message):
f = open('d:\logfile.txt','a')
f.write(message + \n)
f.close()

from DelNotePrinter import DelNotePrinter


OT
The convention is to use all_lower_names for modules - having modules 
and classes with the same (case-sensitive) name can be very misleading.

/OT


note the order of the above - log is defined before the import.


And ? Do you think it will affect the imported module in any way ? Like, 
say, magically inject your log function in the DelNotePrinter module ?-)




Later in the  source


Where ?


I have

log('disPrint is:'+disPrint)
log('count is:'+count)


Do yourself a favor and learn string formating...


log(repr(DelNotePrinter))
printer = DelNotePrinter(disPrint,int(count))




The DelNotePrinter.py file cannot us log even though it is declared
as global.


In Python, global means module-level, and it's only necessary when 
you want to rebind a module-level name from within a function or method.


 The code is...


# coding=utf8
#DelNotePrinter = code to print delivery notes
  assorted imports removed for space reasons


Some of these imports surely explain why you don't just get a NameError 
when trying to call log() - wild guess : you have some from xxx import 
* statement that does import another callable named 'log'.



class DelNotePrinter(object):
''' Print Delivery Note on A5 in portrait '''
def __init__(self,printer,copies):
''' create printer and painter '''
global font,sm,log
log('DelNotePrinter: starting')




self.printer = QPrinter(QPrinter.HighResolution)


If you want to access a name (function, class, whatever) defined in 
another module, you have to explicitely import it.




The file the log writes contains..
disPrint is:HP Deskjet 6940 series
count is:1
class 'DelNotePrinter.DelNotePrinter'

The  is followed by a newline and end of file! Where is the 
DelNotePrinter: starting message?


We can't tell - but you can get at least some hint, cf below


If I replace the opening of __init__ with
global font,sm,log
f = open('d:\logfile.txt','a')
f.write('DelNotePrinter: starting' + \n)
f.close()
self.printer = QPrinter(QPrinter.HighResolution)

then the message IS written to the log file.


Obviously, yes. Now please add this to your code:

class DelNotePrinter(object):
''' Print Delivery Note on A5 in portrait '''
def __init__(self,printer,copies):
''' create printer and painter '''
global font,sm,log
f = open('d:\logfile.txt','a')
f.write('DelNotePrinter: starting' + \n)

# check what log is bound to in the currrent namespace
f.write(
   DelNotePrinter : log is '%s' from '%s' % (
  log, log.__module__
  ))
f.close()
self.printer = QPrinter(QPrinter.HighResolution)


I have read http://docs.python.org/reference/simple_stmts.html#global 
very carefully and I still don't understand.


The statement definition makes no sense if you don't understand 
namespaces and bindings:


http://docs.python.org/reference/executionmodel.html#naming-and-binding

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


Re: accessing a text file

2010-09-07 Thread Bruno Desthuilliers

Baba a écrit :
(snip)

If i had
received a friendly response from Benjamin (as opposed to Please do
us a favor and at least try to figure things out on your own)


According to usenet standards and given your initial question, this is a 
_very_ friendly answer.

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


Re: mutate dictionary or list

2010-09-07 Thread Bruno Desthuilliers

Baba a écrit :

Hi

I am working on an exercise which requires me to write a funtion that
will check if a given word can be found in a given dictionary (the
hand).

def is_valid_word(word, hand, word_list):

Returns True if word is in the word_list and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or word_list.

I don't understand this part: Does not mutate hand or word_list


Everything in Python is an object. A few objects are immutable (ints, 
strings, tuples...), ie you there's no way to modify the state of the 
object in place. Most objects are mutable, and this obviously includes 
lists and dicts (you can add / remove / replace list or dicts elements).


Now the point is that when passing an object as argument to a function, 
you don't pass a copy of the object but the object itself, so if the 
object is mutable, you can mutate if from within the function.


A simple (and really dumb) example being worth a thousand words:

# mutate.py

def update_dict(dic, key, value):
print in update_dic : dic id is %s % id(dic)
dic[key] = value

def main():
   dic = dict(a=1, b=2)
   lst = [1, 2, 3]

   print in main : dic id is %s % id(dic)
   print dic : %s % dic
   print calling update_dict
   update_dict(dic, c, 3)
   print after update_dict
   print in main : dic id is %s % id(dic)
   print dic : %s % dic

if __name__ == '__main__':
main()




I know that a ditionary is unordered. How Can i however avoid
'acidental' mutation?


This has nothing to do with dicts being ordered or not. And there's NO 
accidental mutation - you have to explicitely call a method or 
operator that mutate the dict.



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


Re: The Samurai Principle

2010-09-07 Thread Bruno Desthuilliers

Phlip a écrit :

How does that compare to, say, the Kamikaze Principle? ;)


Return victorious AND not at all!

(All return values are packed up and thrown...;)


... and then it raises a SystemError !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed - function apparently global cannot be called.

2010-09-07 Thread Bruno Desthuilliers

Ian Hobson a écrit :
(snip)

you may also want to read the recent using modules thread...
--
http://mail.python.org/mailman/listinfo/python-list


Re: knowing the caller of an import exec question

2010-09-07 Thread Bruno Desthuilliers

bussiere bussiere a écrit :

i've got toto.py :

import titi
def niwhom():
 pass

and titi.py :

def nipang():
  pass

how can i know in titi.py that's it's toto.py that is calling titi.py
and the path of toto ?


You'd have to inspect the call stack. Not for the faint at heart...


And

why :

bidule.py :
class bidetmusique:
 pass


OT
The naming convention is to capitalize class names, ie Bidetmusique or 
 BidetMusique

/OT

OT mode=even-more
Heureusement qu'il n'y a pas grand monde ici pour comprendre le 
français, parce que comme nommage, ça bat des records, là !-)

/OT



truc.py :
X = __import__(bidule)

why exec(X.bidetmusique()) return none


exec doesn't return anything - it executes code in a given context, 
eventually modifying the context. Now given your above code, a new 
bidetmusique instance is indeed created, but since it's not bound to 
anything, it's immediatly discarded.



and X.bidetmusique() return an object ?


cf above



How could i do to make this string X.bidetmusique() return an object ?


exec is 99 time out of 10 (nope, not a typo) the wrong solution. You 
already found how to dynamically import a module by name (I mean, name 
given as as string), all you need know is to find out how to dynamically 
retrieve a module attribute given it's name as string. And the answer is 
getattr:



# truc.py :
X = __import__(bidule)
cls = getattr(X, bidetmusique)
obj = cls()
print obj

HTH

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


Re: The Samurai Principle

2010-09-07 Thread Bruno Desthuilliers

Phlip a écrit :

Back to the topic, I tend to do this:

  for record in Model.objects.filter(pk=42):
 return record

  return sentinel


WTF alert here...


Having lots of short methods helps, because return provides both
control-flow and a result value. But it abuses 'for' to mean 'if'. I
feel _rally_ guilty about that!



But I miss this, from (cough) RoR:

  record = Model.find(42) || sentinel

Django should provide this:

  record = Model.objects.get(pk=42, _if_does_not_exist=sentinel)


queryset.get can be used with multiple conditions - it's not necessarily 
 restricted to pk lookups. However you name your _if_does_not_exist 
kwarg, it will be difficult to garantee that there will never be no 
nameclash with any possible valid model lookup argument...


But if you feel like you found the correct name, you can of course 
monkeypatch queryset !-)

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


Re: The Samurai Principle

2010-09-07 Thread Bruno Desthuilliers
Phlip a écrit :
 On Sep 7, 10:12 am, Bruno Desthuilliers bruno.
 42.desthuilli...@websiteburo.invalid wrote:
 Phlip a écrit :

 Back to the topic, I tend to do this:
   for record in Model.objects.filter(pk=42):
  return record
   return sentinel
 WTF alert here...
 
 I don't see how anyone could WTF that. Are you pretending to be a newb
 who doesn't understanding it? F'em.

F'... newbies is definitly not the pythonic mindset. Python's mindset is
about doing the most obvious thing, no trying to be smart. The obvious
code here is:

try:
   return Model.objects.get(pk=42)
except Model.DoesNotExist:
   return sentinel

so yes, your above snippet is bordering on WTF since it's not immediatly
obvious - it takes at least one more second for me to parse, and I'm
definitly not a Python nor Django newbie. That's something I'd
immediatly rewrite if I had to work on this code.

 I would guess that Django provides some basic rules for avoiding name
 collisions.

yes : common sense.

 Nobody should call a field pk__in

Nope, but default - which would be the obvious keyword here - is also
a perfectly legitimate field name.

 But if you feel like you found the correct name, you can of course
 monkeypatch queryset !-)
 
 Know I gotta learn to add a new method to an existing class!

It's as straightforward as possible once you know Python's object model:

def somefunc(self, whatever):
   self.do_something_with(whatever)

import somemodule
somemodule.SomeClass.mymethod = somefunc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Samurai Principle

2010-09-07 Thread Bruno Desthuilliers
Phlip a écrit :
 On Sep 7, 10:36 am, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Tue, Sep 7, 2010 at 10:02 AM, Phlip phlip2...@gmail.com wrote:
 Back to the topic, I tend to do this:
  for record in Model.objects.filter(pk=42):
 return record
  return sentinel
 How is that any better than just catching the exception?

 try:
 return Model.objects.get(pk=42)
 except Model.DoesNotExist:
 return sentinel

 The flow of control is much clearer this way.
 
 It reminds me of Visual Basic.

Strange enough, your own code snippet reminds me of what I used to find
when fixing VB programs some ten years ago.

 And no it's not much clearer.

It is for any Python programmer - it's even TheOneObviousWay.

 Exceptions are for catastrophic errors

Chapter and verse, please ?

Exceptions are for exceptional situations. When you call queryset.get,
you do expect to have one single instance matching the lookup - specialy
when doing a pk lookup.


 AAAND you need to test that the DoesNotExist occurs for the exact
 reason you expect.

Bullshit. The only reason you'd get this exception is because there's no
record matching your where clause.

 Your except is not complete.

Why so ?

 Making it complete is
 very hard, and will break as soon as the model changes.

Why so ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Subclassing by monkey-patching

2010-09-06 Thread Bruno Desthuilliers

Jason a écrit :

On Sep 5, 3:53 pm, Peter Otten __pete...@web.de wrote:

m = gio.File(.).monitor_directory()
C = type(m)


'C' will not necessarily be 'gio.FileMonitor' — I think the internals
of the GIO methods might further subclass it in some way depending
on what underlying monitors are available.


A possible alternative may be a class that wraps a FileMonitor instead of
subclassing it.


I've been avoiding this because it involves a lot of boilerplate: the
signals needs to be replicated and passed through, same for all
GObject properties, same for the usual methods.


Python is not Java !-)
http://docs.python.org/reference/datamodel.html#object.__getattr__


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


Re: Functions continuing to ru after returning something?

2010-08-31 Thread Bruno Desthuilliers

Peter Otten a écrit :


n = 1
def f():

... global n
... try:
... return n
... finally:
... n += 1
...


The same without a global:

def f(_n=[0]):
try:
return _n[0]
finally:
_n[0] += 1


But yeps, using a generator would be better.
--
http://mail.python.org/mailman/listinfo/python-list


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Baba a écrit :

level: beginner

the following code looks ok to me but it doesn't work.


doesn't work is about the most useless description of a problem. 
Please specify what you expected and what actually happens.



I would like
some hints as to where my reasoning / thought goes wrong

def i_palindrome(pal):
 while len(pal)1:
  if pal[0] == pal[-1]:
   pal=pal[1:-1]


Can you explain what happens if pal[0] != pal[-1] ? (answer below)


 return True



print i_palindrome('annab')


And then you go in an infinite loop !-)



my reasoning:
- i check the length of the string: if  1 continue
- i check first and last char: if they are equal continue
- create a new, shorter string starting at index 1 and ending at
second last index (up to but not including index-1
-restart the while loop as long as length of string is  1
- exiting this loop means all compared chars were identical hence it
is a palindrome and i return True


Your problem is that when first and last char are not equal, you don't 
exit the while loop. You need a return False somewhere here, ie:


def is_palindrom(pal):
  while len(pal)1:
# NB : inverted the test here to make exit more obvious
if pal[0] != pal[-1]:
  return False
pal=pal[1:-1]
  return True


Now there is another solution. A palindrom is made of two symetric 
halves, with (odd len) or without (even len) a single char between the 
symetric halves, ie :


* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and 
compare both (case insensitive compare while we're at it). Here's a 
possible (and a bit tricky) Python 2.x implementation:


def is_palindrom(s):
s = s.lower()
slen = len(s)
until = slen / 2 # Python 2x integer division
offset = int(not(slen % 2))
runtil = until - offset
return s[0:until] == s[-1:runtil:-1]


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


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Richard Arts a écrit :

Now there is another solution. A palindrom is made of two symetric halves,
with (odd len) or without (even len) a single char between the symetric
halves, ie :

* odd : ABCBA ('AB' + 'C' + 'BA')
* even : ABCCBA ('ABC' + 'CBA')

So you just have to extract the symetric halves, reverse one, and compare
both (case insensitive compare while we're at it).


Yes, this is a correct observation, but it is not necessary to compare
the halves; Simply compare the complete string with its reverse. If
they match, it is a palindrome.


Duh :(

I kinda feel stupid right now, thanks Richard :-/


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


Re: palindrome iteration

2010-08-27 Thread Bruno Desthuilliers

Dave Angel a écrit :
(snip)


or  (untested)
def is_palindrom(s):
   s = s.lower()
   return s == s[::-1]




Right, go on, make me feel a bit more stupid :-/
Who's next ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Iterative vs. Recursive coding

2010-08-26 Thread Bruno Desthuilliers

BartC a écrit :
Steven D'Aprano st...@remove-this-cybersource.com.au wrote in 
message news:4c6f8edd$0$28653$c3e8...@news.astraweb.com...

On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote:



I onced worked in a shop (Win32 desktop / accouting applications mainly)
where I was the only guy that could actually understand recursion. FWIW,
I also was the only guy around that understood hairy (lol) concepts
like callback functions, FSM, polymorphism, hashtables, linked lists,
ADTs, algorithm complexity etc...



Was there anything they *did* understand, or did they just bang on the
keyboard at random until the code compiled? *wink*


You underestimate how much programming (of applications) can be done 
without needing any of this stuff.


From personal experience : almost nothing worth being maintained. I'm 
talking about complex domain-specific applications here - not shell 
scripts or todo-lists.



Needless to say, I didn't last long !-)


And rightly so :)


I guess they wanted code that could be maintained by anybody.


The code base was an unmaintainable, undecipĥerable mess loaded with 
global state (litteraly *hundreds* of global variables), duplication, 
dead code, and enough WTF to supply thedailywtf.com for years - to make 
a long story short, the perfect BigBallOfMudd. FWIW, the company didn't 
last long neither - they just kept on introducing ten new bugs each time 
they fixed one.


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


Re: Using String Methods In Jump Tables

2010-08-25 Thread Bruno Desthuilliers

Tim Daneliuk a écrit :

On 8/19/2010 7:23 PM, Steven D'Aprano wrote:

On Thu, 19 Aug 2010 18:27:11 -0500, Tim Daneliuk wrote:


Problem:

  Given tuples in the form (key, string), use 'key' to determine what
  string method to apply to the string:

table = {'l': str.lower, 'u': str.upper}
table['u']('hello world')

'HELLO WORLD'




(snip)


Yeah ... those old assembler memories never quite fade do they.
I dunno what you might call this.  A Function Dispatch Table
perhaps?


I usually refers to this idiom as dict-based dispatch. And FWIW, it's 
in fact (part of...) polymorphic dispatch implemention in Python's 
object model:


 str.__dict__['lower']
method 'lower' of 'str' objects
 d = dict(l=lower, u=upper)
 s = aHa
 for k, v in d.items():
... print %s : %s % (k, s.__class__.__dict__[v](s))

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


Re: Iterative vs. Recursive coding

2010-08-24 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Fri, 20 Aug 2010 17:23:23 +0200, Bruno Desthuilliers wrote:


Steven D'Aprano a écrit :

On Thu, 19 Aug 2010 22:00:16 +, Martin Gregorie wrote:


Recursion can be quite a trick to get your mind round at first

Really? Do people actually find the *concept* of recursion to be
tricky?



I onced worked in a shop (Win32 desktop / accouting applications mainly)
where I was the only guy that could actually understand recursion. FWIW,
I also was the only guy around that understood hairy (lol) concepts
like callback functions, FSM, 


FSM? Flying Spaghetti Monster?


Lol. Now this would at least be a pretty good description of the kind of 
code base these guys were used to !-)






polymorphism, hashtables, linked lists,
ADTs, algorithm complexity etc...



Was there anything they *did* understand,


Hmmm good question - but I didn't last long enough to find out.

or did they just bang on the 
keyboard at random until the code compiled? *wink*


Kind of, yes.

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


Re: 79 chars or more?

2010-08-20 Thread Bruno Desthuilliers

Stefan Schwarzer a écrit :

Hi Neil,

On 2010-08-17 14:42, Neil Cerutti wrote:

(snip)

Looking through my code, the split-up lines almost always include
string literals or elimination of meaningless temporary
variables, e.g.:

self.expiration_date = translate_date(find(response,
'MPNExpirationDate').text, '%Y-%m-%d', '%m%d%Y')


I'd probably reformat this to

  self.expiration_date = translate_date(
find(response, 'MPNExpirationDate').text,
'%Y-%m-%d', '%m%d%Y')

or even

  self.expiration_date = translate_date(
find(response, 'MPNExpirationDate').text,
'%Y-%m-%d',
'%m%d%Y')



make this :

   self.expiration_date = translate_date(
   find(response, 'MPNExpirationDate').text,
   '%Y-%m-%d',
   '%m%d%Y'
   )

I just HATE closing parens on the same line when the args don't fit on 
one single line.



Significant indentation only solves one single issue when it comes to 
coding conventions war !-)

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


Re: A question to experienced Pythoneers

2010-08-20 Thread Bruno Desthuilliers

Rony a écrit :

It looks like I forgot to specify that the product is a totaly new
product build from scratch, not an upgrade from an existing product.



Still the advice to first find out what went wrong with the previous 
project is a very sensible one. Technical problems do exist, but from 
experience they rarely are the main source of failure.

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


Re: Iterative vs. Recursive coding

2010-08-20 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :

On Thu, 19 Aug 2010 22:00:16 +, Martin Gregorie wrote:


Recursion can be quite a trick to get your mind round at first


Really? Do people actually find the *concept* of recursion to be tricky?



I onced worked in a shop (Win32 desktop / accouting applications mainly) 
where I was the only guy that could actually understand recursion. FWIW, 
I also was the only guy around that understood hairy (lol) concepts 
like callback functions, FSM, polymorphism, hashtables, linked lists, 
ADTs, algorithm complexity etc...


Needless to say, I didn't last long !-)

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


Re: Iterative vs. Recursive coding

2010-08-20 Thread Bruno Desthuilliers

Michel Claveau - MVP a écrit :
Salut ! 


C'est cela, la solitude du programmeur génial...

@-salutations


Moi aussi je t'aime, Michel !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pop return from stack?

2010-08-19 Thread Bruno Desthuilliers

Steven D'Aprano a écrit :


Oh my ... I've seen people writing Java in Python, C++ in Python, Perl in 
Python, even VB in Python, but this is the first time I've meet some one 
who wants to write assembler in Python :)




+1 QOTW
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing variables as object attributes

2010-08-17 Thread Bruno Desthuilliers

Vikas Mahajan a écrit :

On 16 August 2010 19:23, Nitin Pawar nitinpawar...@gmail.com wrote:

you would need to define a class first with its attiributes and then you may
want to initiate the variables by calling the class initilializer


Actually I have to dynamically add attributes to a object. I am
writing python script for  FreeCAD software. I am using loop to create
multiple cylinders and I am writing following code-:
cyname = Cylinder
FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
FreeCAD.ActiveDocument.cyname.Radius= .5
FreeCAD.ActiveDocument.cyname.Height= 10

And I am getting this error-:
AttributeError: 'App.Document' object has no attribute 'cyname'


Indeed.


But when I use Cylinder in place of cyname, I am not getting any error.


Of course.



Please help.


I don't have FreeCAD installed, I won't install it, and I'm not going to 
read FreeCAD's doc neither, but you may want to check whether 
FreeCAD.ActiveDocument.addObject actually returns the newly created 
objet (which would be a sensible behaviour). If so, you'd just have to 
keep a ref to this object, ie:


cylinder = FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
cylinder.Radius = 0.5
# etc

Else, you can always get this ref using getattr, ie:

FreeCAD.ActiveDocument.addObject(Part::Cylinder,cyname)
cylinder = getattr(FreeCAD.ActiveDocument, cyname)
cylinder.Radius = 0.5
# etc

And while you're at it, you could save on both typing and execution time 
by keepin a ref to the document object itself:


doc = FreeCAD.ActiveDocument

for cyname in (cylinder1, cylinder2, cylinderN):
doc.addObject(Part::Cylinder,cyname)
cylinder = getattr(doc, cyname)
cylinder.Radius = 0.5
# etc

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


Re: How do I get number of files in a particular directory.

2010-08-13 Thread Bruno Desthuilliers

blur959 a écrit :

Hi, all, Is there a way to get a number of files in a particular
directory? I tried using os.walk, os.listdir but they are return me
with a list, tuple of the files, etc. But I want it to return a
number. Is it possible?


len(any_sequence)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone use Quixote for web developing?

2010-08-12 Thread Bruno Desthuilliers

ph4nut a écrit :

Hi all,I am learning Quixote a few days ago,,,and i have no idea about
whether there is any Google Group talking about Quixote,so i post this
post to check that is Quixote been talking in this group before or can
i ask question about Quixote here!


From the project's home page:


There is a mailing list for discussing Quixote and you should look there 
for information about obtaining the current release:


* quixote-users



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


Re: python ide for ubuntu

2010-08-12 Thread Bruno Desthuilliers

geremy condra a écrit :

(about eclipse+pydev)


Or you could use a text editor and a terminal and spare yourself the
agony of dealing with 600MB of Java of questionable quality ;).


+1 QOTW

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


Re: easy question on parsing python: is not None

2010-08-09 Thread Bruno Desthuilliers

Gregory Ewing a écrit :

Ethan Furman wrote:

Instead of using 'is' use '=='.  Maybe not as cute, but definitely 
more robust!


It's also just as efficient if you use strings that
resemble identifiers, because they will be interned,


Remember : this IS an implementation detail.

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


Re: Using dicts and lists as default arguments of functions

2010-08-09 Thread Bruno Desthuilliers

Johan a écrit :

Dear all,

Considering this test program:

def tst(a={}):


Stop here, we already know what will follow !-)

And yes, it's one of Python's most (in)famous gotchas : default 
arguments values are computed only once, at function definition time 
(that is, when the def statement is executed).


The correct way to write a function with mutable default arguments is:

def func(arg=None):
   if arg is None:
   arg = []
   # then proceed

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


Re: easy question on parsing python: is not None

2010-08-06 Thread Bruno Desthuilliers

Roald de Vries a écrit :


'not None' first casts None to a bool, and then applies 'not', so 'x is 
not None' means 'x is True'.


Obviously plain wrong :

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type help, copyright, credits or license for more information.
 42 is not None
True
 42 is True
False


Please check your facts before posting !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: assigning variables from list data

2010-08-06 Thread Bruno Desthuilliers

Chris Hare a écrit :

I have a database query result (see code below).  In PHP, I would have said

list(var1,var2,var) = $result


Other already answered on the Python equivalent. But there's an IMHO 
better way, which is to use (if the DB-API connector provides it) a 
DictCursor, that yields dicts instead of tuples.




import sqlite3 as sqlite

try:
print connecting to disk db ...
conn = sqlite.connect(netcomm.db)
except:
print oops



OT, but do yourself a favor and remove this try/except. Sorry to have to 
say but it's about the most stupidiest error handling scheme you could 
think of. Seriously.


Ask yourself : what will happens if sqlite.connect raises AND you don't 
catch the exception ? Yes, the script will stop right here - which is 
what you want anyway - AND you will have an error message giving you 
informations about what went wrong, and a full traceback. IOW, you'll 
have as much helpful debugging infos as possible at this point.


Now what will happen with your current code ? Instead of an informative 
error message, you have a oops. Well, really helps. Then your script 
will go on, print retrieving data, and you can bet your ass it'll 
crash on the next line - cursor = conn.cursor(), that is - with a very 
less informative error message, and you'll wonder why.


Also, be warned that SysExit and KeyboardInterrupt are also exceptions. 
The one you may NOT want to catch and dismiss.


To make a long story short:

1/ only catch exceptions you can *and* want to handle
2/ never assume anything about what caused the exception
3/ not exception handling is better than a wrong exception handling.

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


Re: easy question on parsing python: is not None

2010-08-06 Thread Bruno Desthuilliers

Richard D. Moores a écrit :

On Thu, Aug 5, 2010 at 16:15, Rhodri James rho...@wildebst.demon.co.uk wrote:

On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks
wherespythonmo...@gmail.com wrote:



You're not testing for equivalence there, you're testing for identity.  is
and is not test whether the two objects concerned are (or are not) the
same object.  Two objects can have the same value, but be different objects.
 The interpreter can fool you by caching and reusing objects which have the
same value when it happens to know about it, in particular for small
integers, but this is just a happy accident of the implementation and in no
way guaranteed by the language.  For example:


spam, eggs, chips and spam is spam, eggs, chips and spam

True

a = spam, eggs, chips and spam
b = spam, eggs, chips and spam
a is b

False

a == b

True



I'm wondering if there isn't considerable predictability to that
happy accident.


There is, indeed, but that's really implementation details.


Note how 1 'word' is treated versus 2:


x = 
'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
y = 
'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
x is y

True

x = 'alksjdhflkajshdflkajhdflkjahsdflkj 
hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
y = 'alksjdhflkajshdflkajhdflkjahsdflkj 
hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
x is y

False



CPython caches strings that happen to be valid Python identifiers. But 
once again, this is an implementation-specific optimization.


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


Re: The untimely dimise of a weak-reference

2010-08-02 Thread Bruno Desthuilliers

Gregory Ewing a écrit :
(snip)


import weakref

class weakmethod(object):

  def __init__(self, bm):
self.ref = weakref.ref(bm.im_self)
self.func = bm.im_func

  def __call__(self, *args, **kwds):
obj = self.ref()
if obj is None:
  raise ValueError(Calling dead weak method)
self.func(obj, *args, **kwds)


Would be better with :

  return self.func(obj, *args, *kwds)

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


Re: hasattr + __getattr__: I think this is Python bug

2010-07-28 Thread Bruno Desthuilliers

Ethan Furman a écrit :

Bruno Desthuilliers wrote:

Bruno Desthuilliers a écrit :

Ethan Furman a écrit :

Bruno Desthuilliers wrote:

Duncan Booth a écrit :

(snip)

Or you could create the default as a class attribute 


from the OP:

I have a class (FuncDesigner oofun) that has no attribute size, but
it is overloaded in __getattr__, so if someone invokes
myObject.size, it is generated (as another oofun) and connected to
myObject as attribute.


so this solution won't obviously work in this case !-)

Also and FWIW, I wouldn't advocate this solution if the default 
class attribute is of a mutable type.


Well, it is Monday, so I may be missing something obvious, but what 
is the effective difference between these two solutions?




If you meant what is the difference between creating the whatever 
attribute with a default value in the initializer and creating it on 
demand in the __getattr__ hook, the main difference is that in the 
first case, the instance is garanteed to have this attribute, so you 
get rid of hasattr checks (and the unwanted side effects) or, worse, 
direct check of the instance __dict__. Except for a couple of corner 
case, client code shouldn't have to worry about this kind of things - 
this breaks encapsulation.


Yay Tuesday!  :D

What I meant was what is the difference between:

[Bruno Desthuilliers]
  DEFAULT_WHATEVER = Whathever()
  class MyClass(object):
   def __init__(self, x, y):
   self.size = DEFAULT_WHATEVER

and

[Duncan Booth]
  class MyClass(object):
  size = Whatever()
  def __init__(self, x, y):
  ...

in both cases the object ends up with a size attribute and no further 
need of __getattr__. Of course, the warning about having a mutable 
object as a class attribute stands.


Indeed.

To phrase it another way, why does your solution (Bruno) work, but 
Duncan's obviously won't?


As it is written (and assuming the name Whatever is bound to a 
callable !-)), Duncan's code would work, even if it might not be the 
safest solution in the case of a mutable type.


The problem here is that the OP stated that the size attribute was to 
be of the same type as the host class, so the code would look something 
like:


class MyClass(object):
size = MyClass()

which will raise a NameError, since MyClass is not yet defined when 
size=MyClass() is executed.

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


Re: Nice way to cast a homogeneous tuple

2010-07-28 Thread Bruno Desthuilliers

wheres pythonmonks a écrit :

Thanks ... I thought int was a type-cast (like in C++) so I assumed I
couldn't reference it.


Python has no C/C++ like type-cast. int is the builtin integer type, 
and instanciating an object in Python is done by calling it's type. 
Remember that in Python, everything (at least everything you can bind to 
a name) is an object (including functions, types etc), and that 
functions are just one kind of callable objects (types - aka classes 
-, methods and a few other builtin objects are callable too, and you can 
of course define your own callable type).


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


Re: python terminology on classes

2010-07-27 Thread Bruno Desthuilliers

Peng Yu a écrit :

Hi

I'm still kind of confused about the terminology on classes in python.

Could you please let me know what the equivalent terms for the
following C++ terms?


C++ and Python having very different semantics and object models, 
there's not necessarily a straight one to one mapping.




constructor


Python uses a smalltalk-like 2 phases instanciation / initialisation 
scheme. First the proper construction (__new__) is called with the 
class object as first argument, and it must return an unintialised 
instance of the class. Then the initialiser (__init__) is called on this 
instance.


Now one usually only implements the initialiser, as the default 
object.__new__ method does what you would expect, so you'll often see 
people qualifying __init__ as the constructor.



destructor


Python has no real destructor. You can implement a __del__ method that 
will _eventually_ be called before the instance gets garbage-collected, 
but you'd rather not rely on it. Also, implementing this method will 
prevent cycle detection.



member function


= method.

Note that Python's methods are really thin wrappers around function 
objects that are attributes of the class object. You'll find more on 
this here:


http://wiki.python.org/moin/FromFunctionToMethod


member variable


= Attribute


virtual member function


All Python's methods are virtual.


function


= function !-)

Note that in Python, functions and classes are objects.


I think that C++ function is equivalent to python function and C++
member function is equivalent to python method. But I couldn't
locate where the original definitions of the corresponding python
terms in the manual as these term appear many times. Could you please
point me where to look for the definition of these python
corresponding terms?


You just cannot directly translate C++ into Python, and while there are 
similarities trying to write C++ in Python will not get you very far.


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


Re: hasattr + __getattr__: I think this is Python bug

2010-07-27 Thread Bruno Desthuilliers

Ethan Furman a écrit :

Bruno Desthuilliers wrote:

Duncan Booth a écrit :

(snip)

Or you could create the default as a class attribute 


from the OP:

I have a class (FuncDesigner oofun) that has no attribute size, but
it is overloaded in __getattr__, so if someone invokes
myObject.size, it is generated (as another oofun) and connected to
myObject as attribute.


so this solution won't obviously work in this case !-)

Also and FWIW, I wouldn't advocate this solution if the default 
class attribute is of a mutable type.


Well, it is Monday, so I may be missing something obvious, but what is 
the effective difference between these two solutions?



Now it's Tuesday !-)


Ok, let's see:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type help, copyright, credits or license for more information.
 class Foo(object):
... whatever = Foo()
...
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 2, in Foo
NameError: name 'Foo' is not defined

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


Re: hasattr + __getattr__: I think this is Python bug

2010-07-27 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :

Ethan Furman a écrit :

Bruno Desthuilliers wrote:

Duncan Booth a écrit :

(snip)

Or you could create the default as a class attribute 


from the OP:

I have a class (FuncDesigner oofun) that has no attribute size, but
it is overloaded in __getattr__, so if someone invokes
myObject.size, it is generated (as another oofun) and connected to
myObject as attribute.


so this solution won't obviously work in this case !-)

Also and FWIW, I wouldn't advocate this solution if the default 
class attribute is of a mutable type.


Well, it is Monday, so I may be missing something obvious, but what is 
the effective difference between these two solutions?




If you meant what is the difference between creating the whatever 
attribute with a default value in the initializer and creating it on 
demand in the __getattr__ hook, the main difference is that in the 
first case, the instance is garanteed to have this attribute, so you get 
rid of hasattr checks (and the unwanted side effects) or, worse, 
direct check of the instance __dict__. Except for a couple of corner 
case, client code shouldn't have to worry about this kind of things - 
this breaks encapsulation.





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


Re: Why is there no platform independent way of clearing a terminal?

2010-07-27 Thread Bruno Desthuilliers

Daniel Fetchinson a écrit :

Hi folks,

If I'm only interested in linux and windows I know I can do


import os
import platform

if platform.system( ) == 'Linux':
clear = 'clear'
else:
clear = 'cls'

os.system( clear )


or something equivalent using os.name and friends, but was wondering
why there is no platform independent way (i.e. the platform dependence
is taken care of by the python stdlib) of clearing a terminal. Sure,
there are many different terminals and many different operating
systems but in many areas python managed to hide all these
complexities behind a well defined API.

Why was clearing a terminal left out?



What you're talking about is a shell, not a terminal (a terminal is a 
physical device). And the shell is not necessarily part of the OS itself 
(there's no shortage of shells for unices / linux systems), so it 
doesn't belong to the os or platform modules.


FWIW, I can't tell for sure since I never used any other shell than 
bash, but I'm not sure your above code is garanteed to work on each and 
any possible unix shell.

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


Re: Why is there no platform independent way of clearing a terminal?

2010-07-27 Thread Bruno Desthuilliers

Grant Edwards a écrit :

On 2010-07-27, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid 
wrote:

Daniel Fetchinson a ?crit :

(snip)

Why was clearing a terminal left out?

What you're talking about is a shell, not a terminal (a terminal is a 
physical device).


No, what he's talking about is clearing a terminal (or a terminal
emulator).  They both work the same, the only difference is whether
the terminal software is running on dedicated hardware or on
general-purpose hardware.


(snip)

I stand corrected.
--
http://mail.python.org/mailman/listinfo/python-list


Re: hasattr + __getattr__: I think this is Python bug

2010-07-26 Thread Bruno Desthuilliers

dmitrey a écrit :
(snip)


This doesn't stack with the following issue: sometimes user can write
in code myObject.size = (some integer value) and then it will be
involved in future calculations as ordinary fixed value; if user
doesn't supply it, but myObject.size is involved in calculations, then
the oofun is created to behave like similar numpy.array attribute.


IOW, you want a default value for the size if it has not been specified 
by the user, so you can safely use this attribute in computations. The 
more straightforward solution is to define this attribute (with the 
default value) in the initialiser, ie:



class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.size = Whatever()


If you don't want to create as many Whatever instances as MyClass 
instances, you can create a single Whatever instance before defining 
your class:


DEFAULT_WHATEVER = Whathever()

class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
self.size = DEFAULT_WHATEVER


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


Re: hasattr + __getattr__: I think this is Python bug

2010-07-26 Thread Bruno Desthuilliers

Duncan Booth a écrit :

Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote:

If you don't want to create as many Whatever instances as MyClass 
instances, you can create a single Whatever instance before defining 
your class:


DEFAULT_WHATEVER = Whathever()

class MyClass(object):
 def __init__(self, x, y):
 self.x = x
 self.y = y
 self.size = DEFAULT_WHATEVER




Or you could create the default as a class attribute 


from the OP:

I have a class (FuncDesigner oofun) that has no attribute size, but
it is overloaded in __getattr__, so if someone invokes
myObject.size, it is generated (as another oofun) and connected to
myObject as attribute.


so this solution won't obviously work in this case !-)

Also and FWIW, I wouldn't advocate this solution if the default class 
attribute is of a mutable type.

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


Re: why is this group being spammed?

2010-07-26 Thread Bruno Desthuilliers

be.krul a écrit :


Why not moderate this group?


This is a hi-traffic group, so it would require a huge team of moderators.
--
http://mail.python.org/mailman/listinfo/python-list


Re: any issues with long running python apps?

2010-07-10 Thread Bruno Desthuilliers
Les Schaffer a écrit :
 i have been asked to guarantee that a proposed Python application will
 run continuously under MS Windows for two months time. And i am looking
 to know what i don't know.

(snip)

 but none of this has anything to do with Python itself. i am sure python
 servers have been running reliably for long periods of time, but i've
 never had to deal with a two-month guarantee before.  is there something
 else i am missing here that i should be concerned about on the
 pure-Python side of things? something under the hood of the python
 interpreter that could be problematic when run for a long time?

Zope is (rightly) considered as a memory/resources hog, and I have a
Zope instance hosting two apps on a cheap dedicated server that has not
been restarted for the past 2 or 3 years. So as long as your code is
clean you should not have much problem with the Python runtime itself,
at least on a a linux box. Can't tell how it would work on Windows.

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


Re: Only one forum app in Python?

2010-07-10 Thread Bruno Desthuilliers
Gilles Ganault a écrit :
 Hello
 
 I'd like to write a small web app in Python which must include a
 forum.
 
 So I checked the relevant article in Wikipedia, which says that only
 one forum app is available for Python:
 
 http://en.wikipedia.org/wiki/Comparison_of_internet_forum_software_(other)
 
 Is Pocoo really the only solution available out there?

There are almost a dozen of Python forum apps for Django alone, and
Python is known as the language with more web frameworks than keywords.

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


Re: delegation pattern via descriptor

2010-07-08 Thread Bruno Desthuilliers

kedra marbun a écrit :

On Jul 7, 2:46 am, Bruno Desthuilliers
bdesth.quelquech...@free.quelquepart.fr wrote:

Gregory Ewing a écrit :


Bruno Desthuilliers wrote:

kedra marbun a écrit :

if we limit our discussion to py:
why __{get|set|delete}__ don't receive the 'name'  'class' from
__{getattribute|{set|del}attr}__
'name' is the name that is searched

While it would have been technically possible, I fail to imagine any use
case for this.

I think he wants to have generic descriptors that are
shared between multiple attributes, but have them do
different things based on the attribute name.

I already understood this, but thanks !-)

What I dont understand is what problem it could solve that couldn't be
solved more simply using the either _getattr__ hook or hand-coded
delegation, since such a descriptor would be so tightly coupled to the
host class that it just doesn't make sense writing a descriptor for this.


yeah, i finally can agree descriptor isn't supposed to be used as
delegation in general, it should be the job of __getattr__

however i still think passing name would open up some other
possibilities of use


Nothing prevents you to pass a name to the descriptor instance when 
instanciating it, ie:


class Desc(object):
def __init__(self, name):
self.name = name
   def __get__(self, inst, cls):
   # ...
   def __set__(self, inst, value):
   # ...


class Foo(object):
bar = Desc(bar)
baaz = Desc(baaz)

Ok, this is not necessarily what you were looking for, but it's IMHO 
less brittle than relying on which attribute name was looked up (which 
is something the descriptor shouldn't have to care about).




btw, is there a common approach to let the interface of a class that
uses __getattr__, to include names that are delegated?


In Python 2.x, not that I know (but it may have passed under my radar). 
If what you want it to automate delegation of a set of methods without 
too much manual coding, you can use a custom metaclass that will add the 
relevant methods to the class, based on (ie) a list (or mapping) of 
methods names. But that might be a bit overkill.



class A:
def do_this(self): ...

class B:
a = A()


I don't see the point of using delegation on a class attribute. That's 
typically what inheritance is for.



def do_that(self): ...

def __getattr__(self, name):
try:
return types.MethodType(getattr(self.a, name), self)


Err... Did you try the simple way ?
return getattr(self.a, name)

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


Re: delegation pattern via descriptor

2010-07-06 Thread Bruno Desthuilliers

kedra marbun a écrit :

On Jul 5, 3:42 pm, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:

kedra marbun a écrit :




i'm confused which part that doesn't make sense?
this is my 2nd attempt to py, the 1st was on april this year, it was
just a month, i'm afraid i haven't got the fundamentals right yet. so
i'm gonna lay out how i got to this conclusion, CMIIW
**explanation of feeling (0) on my 1st post**
to me, descriptor is a particular kind of delegation, it takes the job
of coding the delegation by having a contract with programmers that
the tree meta operations (get, set, del) on attr are delegated to the
obj that is bound to the attr
are we agree that descriptor is a kind of delegation?
the mechanism that makes descriptor works is in __getattribute__,
__setattr__, __delattr__ of 'object'  'type'
now, if i want a single descriptor obj to be delegated to multiple
tasks, i can't do it since __get__ doesn't get info that can be used
to determine which task to do
i must have diff descriptor obj for each task
class Helper:
   def __init__(self, name):
   self.name = name
   def __get__(self, ins, cls):
   if self.name == 'task0': ...
   elif self.name == 'task1': ...
   else: ...

Replacing such big switch code with polymorphic dispatch is one of the
  goals (and feature) of OO. This should be:

class Task0(object):
 def __get__(self, obj, cls):
 # code here

class Task1(object):
 def __get__(self, obj, cls):
 # code here

class A(object):
 task0 = Task0()
 task1 = Task1()

If you have common code to share between TaskO and Task1 then factor it
out into a base class.


if __get__ receives the name, then i could do
class Helper:
   def __get__(self, ins, cls, name):
   ...
class a:
   task0 = task1 = Helper()

Yuck.


what's so 'Yuck' about it? ;)


It's an implicit, obfuscated and overcomplicated way to do a very simple 
thing. To be true, I just don't see the point of this pattern - Python 
has better solutions for delegation (cf the __getattr__ method), and 
that's not what descriptors are for.




i guess i need a strong stmt: is descriptor a kind of delegation? or
is it not?


The descriptor protocol is the primary support for computed attributes. 
As such it can be used as a support for delegation, but it's not a kind 
of delegation by itself.



* if it is a kind of delegation, then the code that you labeled as
'Yuck' is just a result of applying delegation
what's wrong with delegating multiple tasks to a single obj?


Nothing wrong with delegating multiple tasks to a single object - but 
not that way. If you want to use descriptors to specify which tasks 
should be delegated, you'd be better doing it more explicitely - that 
is, only use the descriptor as a gateway, and use one descriptor per task.


Else just use __getattr__ !-)

Sorry, I don't have much time to elaborate on this now.


that code is similar to this

class Helper:
def do_this(self, ins): ...
def do_that(self, ins): ...

class a:
delegate = Helper()
def task0(self): self.delegate.do_that(self)
def task1(self): self.delegate.do_this(self)



It's not similar. This second example is explicit, and doesn't couple 
Helper to a.



My 2 cents.
--
http://mail.python.org/mailman/listinfo/python-list


Re: delegation pattern via descriptor

2010-07-06 Thread Bruno Desthuilliers
Gregory Ewing a écrit :
 Bruno Desthuilliers wrote:
 kedra marbun a écrit :

 if we limit our discussion to py:
 why __{get|set|delete}__ don't receive the 'name'  'class' from
 __{getattribute|{set|del}attr}__
 'name' is the name that is searched


 While it would have been technically possible, I fail to imagine any use
 case for this.
 
 I think he wants to have generic descriptors that are
 shared between multiple attributes, but have them do
 different things based on the attribute name.

I already understood this, but thanks !-)

What I dont understand is what problem it could solve that couldn't be
solved more simply using the either _getattr__ hook or hand-coded
delegation, since such a descriptor would be so tightly coupled to the
host class that it just doesn't make sense writing a descriptor for this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: delegation pattern via descriptor

2010-07-05 Thread Bruno Desthuilliers

kedra marbun a écrit :

i'm confused which part that doesn't make sense?
this is my 2nd attempt to py, the 1st was on april this year, it was
just a month, i'm afraid i haven't got the fundamentals right yet. so
i'm gonna lay out how i got to this conclusion, CMIIW

**explanation of feeling (0) on my 1st post**
to me, descriptor is a particular kind of delegation, it takes the job
of coding the delegation by having a contract with programmers that
the tree meta operations (get, set, del) on attr are delegated to the
obj that is bound to the attr
are we agree that descriptor is a kind of delegation?

the mechanism that makes descriptor works is in __getattribute__,
__setattr__, __delattr__ of 'object'  'type'

now, if i want a single descriptor obj to be delegated to multiple
tasks, i can't do it since __get__ doesn't get info that can be used
to determine which task to do
i must have diff descriptor obj for each task

class Helper:
def __init__(self, name):
self.name = name
def __get__(self, ins, cls):
if self.name == 'task0': ...
elif self.name == 'task1': ...
else: ...



Replacing such big switch code with polymorphic dispatch is one of the 
 goals (and feature) of OO. This should be:



class Task0(object):
def __get__(self, obj, cls):
# code here


class Task1(object):
def __get__(self, obj, cls):
# code here


class A(object):
task0 = Task0()
task1 = Task1()


If you have common code to share between TaskO and Task1 then factor it 
out into a base class.




if __get__ receives the name, then i could do

class Helper:
def __get__(self, ins, cls, name):
...

class a:
task0 = task1 = Helper()



Yuck.

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


Re: loading configuration files that are themselves python

2010-07-03 Thread Bruno Desthuilliers
Matthew Vernon a écrit :
 Hi,
 
 Is there a more idiomatic way of loading in a configuration file
 that's python code than:
 
 _temp=__import__(path,fromlist='cachestrs')
 cachestrs=_temp.cachestrs
 
 ? I mean, that's pretty ugly...Plain import doesn't work in this
 case because 'path' is a variable defined elsewhere

At least you have a way to do it, so you should be happy !-)

Another solution would be to add the path to sys.path, but it wouldn't
necessarily be the best thing to do here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: delegation pattern via descriptor

2010-07-03 Thread Bruno Desthuilliers
kedra marbun a écrit :
 if we limit our discussion to py:
 why __{get|set|delete}__ don't receive the 'name'  'class' from
 __{getattribute|{set|del}attr}__
 'name' is the name that is searched

While it would have been technically possible, I fail to imagine any use
case for this.

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


Re: Python dynamic attribute creation

2010-07-02 Thread Bruno Desthuilliers

WANG Cong a écrit :

On 07/01/10 23:19, Stephen Hansen me+list/pyt...@ixokai.io wrote:


As long as setattr() exists in Python, that will be not so ordinary. :)

setattr is perfectly ordinary.


If you think setattr() is as ordinary as a trivial assignment, 


setattr IS a trivial assignment.



However, I think setattr() is a builtin function, using it exposes the
*magic* of metaprogramming (or class-programming, if more correct) at a
first glance.


No magic and no metawhatever involved. setattr is as simple as:

def setattr(obj, name, value):
obj.__setattribute__(name, value)

which is *exactly* what gets called when you use the binding statement 
form ie obj.someattr = value which FWIW is just syntactic sugar for 
the former (just like the 'class' statement is just syntactic sugar for 
a call to type, etc).


I fail to understand why you insist on seeing something as trivial as 
magic, metaprogramming or whatever.


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


Re: Python dynamic attribute creation

2010-07-02 Thread Bruno Desthuilliers

WANG Cong a écrit :

On 06/30/10 01:25, Ethan Furman et...@stoneleaf.us wrote:


But if so why setattr() still exists? What is it for if we can do the
same thing via assignments? Also, in order to be perfect, Python should
accept to add dynamic attributes dynamically, something like PEP
363. That doesn't happen.

Setattr and friends exist to work with dynamic attributes.



Yeah, my point is why setattr() for dynamic attributes while assignments
for static attributes? Why not unify them?


What is a dynamic and what is a static attribute 


Agreed, but at least, the reason why I am being against so many people
here is also trying to make Python be more perfect with my
understanding.


Please start with learning Python's execution model (what exactly 
happens at runtime, what most statement are syntactic sugar for etc) and 
Python's object model (how are Python objects, classes, methods etc 
implemented, attributes lookup rules, metaclasses, descriptors etc).


Then PERHAPS you MIGHT have a chance to help making Python more perfect.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ignorance and Google Groups (again)

2010-07-01 Thread Bruno Desthuilliers

D'Arcy J.M. Cain a écrit :

On Wed, 30 Jun 2010 14:06:05 -0700
Stephen Hansen me+list/pyt...@ixokai.io wrote:
Gmail and Google Groups are not one and the same. There's a number of 
people who subscribe to the list directly, use Gmail, and don't go 
anywhere near Google Groups.


I know that.  My filter doesn't catch them.


If anyone is interested in the procmail recipe I will be using, here it
is in all it's glory.

:0: Hir
* ^List-Id:.*python-list.python.org
* ^From:@gmail.com
* ^Newsgroups:
/dev/null


As you can see, to be caught in the filter you need to have a gmail
address and be sending through the news gateway.


which doesn't mean they use Google groups...


 People sending from
gmail.com directly to the mailing list don't get picked up.  I'm pretty
sure that that defines everyone using Google Groups only.


And AFAICT you're wrong. I read and post to c.l.py using my newsreader 
(so NOT going thru GG), and my personal address is @gmail.com.

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


Re: List-type attributes and name strings

2010-07-01 Thread Bruno Desthuilliers

egbert a écrit :

Normally you use setattr() if the name of the attribute is in a
namestring: 

setattr(self, namestring, value)

But my attributes are lists or dictionaries, and I don't seem to be
able to use setattr anymore.


Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type help, copyright, credits or license for more information.
 class Foo(object):
...   def __init__(self):
... self.attr1 = {}
... self.attr2 = []
...
 attr1 = dict((x, x) for x in 'abc')
 attr2  = range(5)
 f = Foo()
 setattr(f, attr1, attr1)
 setattr(f, attr2, attr2)
 f.attr1
{'a': 'a', 'c': 'c', 'b': 'b'}
 f.attr2
[0, 1, 2, 3, 4]



Either I failed to understand you or you overlooked some other problem 
in you code and jumped to the wrong conclusions.




Now I use for a list something like:

self.__dict__[namestring].append(value)

and for a dictionary:

self.__dict__[namestring][keystring]=value


Duh. You're confusing *setting* an attribute and *getting it then 
mutating it*.


Can you get the difference between:

 f.attr2.append(42)

and

 f.attr2 = [7, 87, 98]

?

If you don't, then you're in for serious trouble :-/



But I have the impression that I am cheating, because users should not
operate on __dict__ directly.


Client code shouldn't mess with implementation attribute, for sure. This 
bypasses all the lookup rules, and can break computed attributes (ie 
properties or other custom descriptors). At least use getattr() and then 
appropriate call or operator, ie:


 getattr(f, attr1)[w] = w
 getattr(f, attr2).append(42)


FWIW, it's usually better to hide the mere fact that f.attr1 is a list 
and f.attr2 a dict. Here a clean solution would be to make attr1 and 
attr2 implementation attributes and provide an API over it, but it might 
be overkill.


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


Re: Python dynamic attribute creation

2010-07-01 Thread Bruno Desthuilliers

Stephen Hansen a écrit :

On 6/30/10 10:37 PM, Aahz wrote:

In article4c29ad38$0$26210$426a7...@news.free.fr,
Bruno Desthuilliersbruno.42.desthuilli...@websiteburo.invalid  wrote:

Aahz a écrit :

In article4c285e7c$0$17371$426a7...@news.free.fr,
Bruno Desthuilliersbruno.42.desthuilli...@websiteburo.invalid  wrote:

Aahz a écrit :

In article4c2747c1$0$4545$426a7...@news.free.fr,
Bruno Desthuilliersbdesth.quelquech...@free.quelquepart.fr  wrote:


Python has no pretention at elegance.
That's not true at all.  More precisely, I would agree with you if 
the

emphasis is on pretention but not if the emphasis is on elegance;

Python Zen, #9 (or #8 if you're a TrueHacker !-))


...and this implies that Python has no focus on elegance because...?


Nope, that was an answer about where the emphasis was in my previous
statement. I don't mean Python don't care about or is devoid of
elegance, just that it's not the primary concern - hence the has no
pretention at part.


It may not be the primary concern, but elegance certainly is *a*
primary concern.


I concur.

Its not explicitly stated, but it is the Zen 0. This is further 
supported by its implied presence in many of the Axioms and Truths of 
the Bots.


Beautiful is better then ugly; and then the praise of the explicit, of 
simplicity, of readability.


Elegance is a prime concern of Python, as it is the natural result of 
the Doctrines of Pythonicity. It may not be stated as a rule, but it a 
the reward that we are given for following the path of enlightenment.




Elegance (just like beauty) is in the eyes of the beholder.

Explicitness, simplicity and readability are indeed primary concerns in 
Python's design, but elegance is not. Now you'll of course find Python 
mostly elegant  *if* you value expliciteness, simplicity and 
readability, but that's only because your definition of elegant 
happens to match Guido's.


But please gentlemen, let's not fight on this. This no religion, there's 
no dogma here, and no heretic to burn.



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


Re: Ignorance and Google Groups (again)

2010-07-01 Thread Bruno Desthuilliers

D'Arcy J.M. Cain a écrit :

On Thu, 01 Jul 2010 14:07:27 +0200
Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote:
And AFAICT you're wrong. I read and post to c.l.py using my newsreader 
(so NOT going thru GG), and my personal address is @gmail.com.


But...


From: Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid




Sorry, there's a missing sometimes between I and read !-)
Posting from office now.

... Thinking again : I'm not sure the account I use to access usenet 
from home is a @gmail.com one neither. I'll check this out.

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


Re: Python dynamic attribute creation

2010-06-29 Thread Bruno Desthuilliers

Aahz a écrit :

In article 4c285e7c$0$17371$426a7...@news.free.fr,
Bruno Desthuilliers  bruno.42.desthuilli...@websiteburo.invalid wrote:

Aahz a écrit :

In article 4c2747c1$0$4545$426a7...@news.free.fr,
Bruno Desthuilliers  bdesth.quelquech...@free.quelquepart.fr wrote:
Python has no pretention at elegance. 

That's not true at all.  More precisely, I would agree with you if the
emphasis is on pretention but not if the emphasis is on elegance;

Python Zen, #9 (or #8 if you're a TrueHacker !-))


...and this implies that Python has no focus on elegance because...?


Nope, that was an answer about where the emphasis was in my previous 
statement. I don't mean Python don't care about or is devoid of 
elegance, just that it's not the primary concern - hence the has no 
pretention at part.

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


Re: Python dynamic attribute creation

2010-06-28 Thread Bruno Desthuilliers

Aahz a écrit :

In article 4c2747c1$0$4545$426a7...@news.free.fr,
Bruno Desthuilliers  bdesth.quelquech...@free.quelquepart.fr wrote:
Python has no pretention at elegance. 


That's not true at all.  More precisely, I would agree with you if the
emphasis is on pretention but not if the emphasis is on elegance;


Python Zen, #9 (or #8 if you're a TrueHacker !-))
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python dynamic attribute creation

2010-06-28 Thread Bruno Desthuilliers

Carl Banks a écrit :

On Jun 27, 3:49 am, Bruno Desthuilliers
bdesth.quelquech...@free.quelquepart.fr wrote:

WANG Cong a écrit :


On 06/26/10 00:11, Neil Hodgson nyamatongwe+thun...@gmail.com wrote:

WANG Cong:

4) Also, this will _somewhat_ violate the OOP princples, in OOP,
this is and should be implemented by inherence.

   Most object oriented programming languages starting with Smalltalk
have allowed adding attributes (addInstVarName) to classes at runtime.

Thanks, I have to admit that I know nothing about Smalltalk.

Then you really don't know much about OO.


I don't really know much about Smalltalk either.



Duh. I cancelled this totally stupid and useless post a couple seconds 
after hitting the send button, but still too late :(


So first let me present my apologies to WANG Cong and everyone else, 
this was a crude, arrogant and totally stupid thing to say, and I should 
know better. Sorry.


Now on why I first wrote this (warning : personal opinions ahead):

object started with Simula, but objects in Simula are mostly glorified 
ADTs with type-based polymorphic dispatch. Smalltalk (and all it's 
environment) got _way_ further  by turning this into a coherent whole by 
introducing messages (which are more than just type-based polymorphic 
dispatch - Smalltalk's messages are objects themselves) and code 
blocks - as the only mean to control flow. I believe that Smalltalk 
is (so far) the only OO language that was innovative enough to really 
escape from good old procedural programming, and as such possibly the 
only True OOPL.


Now for various reasons (including implementation issues and 
conservatism), it happened that the Simula approach to OO became the 
mainstream with languages like C++ then Java, and that most of OO 
litterature - OOP principles, golden rules etc - is about this somehow 
very restricted approach, so people being taught OO that way have a 
very restricted - and incomplete - vision of what OO is really about. 
That was how I was taught OO, and I always felt that there was something 
wrong, inconsistant or missing.


Studying Smalltalk (however briefly) was for me a real AHA, 
mind-opening moment - suddenly OO made sense as this coherent, 
comprehensive and innovative approach to programming I so far failed to 
find in Java or C++.


Now I don't mean one has to master Smalltalk to be allowed to talk about 
OO, nor that OO can't exist outside Smalltak (Python being IMHO another 
exemple of an interesting and mostly coherent object system, even if 
doesn't go as far as Smalltalk do), but - pardon me if this seems 
arrogant (and please correct me if it really is) - I can't help thinking 
that one cannot really understand OO whithout at least a brief study of 
Smalltalk (and - once again - a full Smalltalk environment, as Smalltalk 
the language is only one part of the 'full' object system).


Hope this will at least help those I may have offended understand my 
point, however stupidly I expressed it :(


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


Re: Python dynamic attribute creation

2010-06-28 Thread Bruno Desthuilliers

Alexander Kapps a écrit :
(snip)
While I personally don't agree with this proposal (but I understand why 
some people might want it), I can see a reason.


When disallowing direct attribute creation, those typos that seem to 
catch newcommers won't happen anymore. What I mean is this:


class Foo(object):
def __init__(self):
self.somearg = 0

f = Foo()
f.soemarg = 42

---^ There, typo, but still working

It's something like a custom __setattr__ that errors out when trying to 
assign to an attribute that doesn't exists,


Chicken and egg problem, really :  f.__dict__['somearg'] doesn't exists 
until self.somearg = 0 is executed.


The problem is that Python's methods are only thin wrapper around 
functions (cf http://wiki.python.org/moin/FromFunctionToMethod) so 
there's no difference between self.somearg = 0 in Foo.__init__ and 
f.somearg = 42.


IOW, there's no way to implement this proposal without completely 
changing Python's object model.

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


Re: Python dynamic attribute creation

2010-06-27 Thread Bruno Desthuilliers
WANG Cong a écrit :
 On 06/25/10 15:34, Bruno Desthuilliers 
 bruno.42.desthuilli...@websiteburo.invalid wrote:
 
 WANG Cong a écrit :
 Hi, list!

 I have a doubt about the design of dynamic attribute creation by
 assignments in Python.

 As we know, in Python, we are able to create a new attribute of
 a class dynamically by an assignment:

 class test: pass
 ... 
 test.a = hello
 test.a
 'hello'

 However, I still don't get the points why Python designs it like this.

 My points are:

 (snip)

 Python's classes are plain objects, and like any other object are
 created at runtime. Having to special-case them would break the
 simplicity and uniformity of Python for no good reason. Just like
 there's no good reason to make setattr() working differently for class
 and non-class objects.

 
 For implementaiton, perhaps, but not for the language design, how could
 a language design be perfect if we can use setattr() like assignments
 while use other things, e.g. delattr(), not? Is there any way to express
 delattr() as simple as expressing setattr() with assignments? I doubt...

cf Ethan's answer on this.

 Using assignments to create an attribute hides metaprogramming
 while using delattr() exposes it.

Once again : in Python, none of this is metaprogramming - just plain
ordinary programming. So called metaprogramming is just an artefact of
static languages where datastructures are created at compile time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python dynamic attribute creation

2010-06-27 Thread Bruno Desthuilliers
WANG Cong a écrit :
(snip)
 
 The point is why making metaprogramming easy is wonderful?

Because it makes life easier ?-)

 AND, even if
 it were wonderful, why only this one, i.e. creating attributes by
 assignments, not other things?

Like :

class Test(object):
a = 1

del Test.a

?-)

 2) Metaprogramming should be distinguished with non-meta programming,
 like templates in C++, it is obvious to see if you are using template
 metaprogramming in C++.
 Why should it be?
 
 
 It is, if you consider other things of metaprogramming in Python. For
 example, deleting an attribute.

cf above.


 3) Thus, allowing dynamic attribute creation by assignment _by default_
 is not a good design for me. It is not obvious at all to see if I am
 doing metaprogramming at a first glance.
 Why do you care if you are doing metaprogramming? Perhaps other languages 
 make it seem difficult and scary, but in Python it is not. It is simple 
 and easy.

 
 
 I do care, programming for a class is quite different from programming
 for a non-class,

Not when a class is just another ordinary object.

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


Re: Python dynamic attribute creation

2010-06-27 Thread Bruno Desthuilliers
WANG Cong a écrit :
 On 06/25/10 17:25, Steven D'Aprano st...@remove-this-cybersource.com.au 
 wrote:
 
 On Fri, 25 Jun 2010 14:15:12 +0100, WANG Cong wrote:

(snip)
 4) Also, this will _somewhat_ violate the OOP princples, in OOP, this is
 and should be implemented by inherence.
 Perhaps, and perhaps not. But Python has never pretended to slavishly 
 follow OOP principles. Python does what works, not necessarily what is 
 a pure design. Python has functional programming, procedural 
 programming, and OO programming, and happily mixes them all together.

 
 Happily mixes them all together doesn't mean it is elegant. :)

Python has no pretention at elegance. It's a _very_ practical
language. It's designed to help you get the job done, period.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python dynamic attribute creation

2010-06-27 Thread Bruno Desthuilliers
WANG Cong a écrit :
 On 06/26/10 00:11, Neil Hodgson nyamatongwe+thun...@gmail.com wrote:
 
 WANG Cong:

 4) Also, this will _somewhat_ violate the OOP princples, in OOP,
 this is and should be implemented by inherence.
Most object oriented programming languages starting with Smalltalk
 have allowed adding attributes (addInstVarName) to classes at runtime.
 
 
 Thanks, I have to admit that I know nothing about Smalltalk.
 

Then you really don't know much about OO.

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


Re: django csrf

2010-06-25 Thread Bruno Desthuilliers
Li Hui a écrit :
 When I add enctype=text/plain to a post form like form action=/auth
 method=post enctype=text/plain, there is a CSRF verification
 failed. error.
 But when I remove it, all is right.
 Who can tell me why?
 

http://groups.google.com/group/django-users
http://catb.org/esr/faqs/smart-questions.html#forum


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


Re: Python dynamic attribute creation

2010-06-25 Thread Bruno Desthuilliers

WANG Cong a écrit :

Hi, list!

I have a doubt about the design of dynamic attribute creation by
assignments in Python.

As we know, in Python, we are able to create a new attribute of
a class dynamically by an assignment:


class test: pass
... 

test.a = hello
test.a

'hello'

However, I still don't get the points why Python designs it like this.

My points are:


(snip)

Python's classes are plain objects, and like any other object are 
created at runtime. Having to special-case them would break the 
simplicity and uniformity of Python for no good reason. Just like 
there's no good reason to make setattr() working differently for class 
and non-class objects.


FWIW, what you call metaprogramming is just ordinary programming - at 
least in Python. All your fears and concerns about Python's dynamism are 
just a priori learned from the mainstream BD culture. From 
experience, these are non-issues - unless of course misused by some 
fool, but then there's no way to prevent stupids from doing stupid 
things. So, yes, Python rely quite a lot on programmer's common sense 
and discipline. Now the good news is that is JustWork(tm).






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


Re: modifying standard library functionality (difflib)

2010-06-24 Thread Bruno Desthuilliers

Vlastimil Brom a écrit :

Hi all,
I'd like to ask about the most reasonable/recommended/... way to
modify the functionality of the standard library module (if it is
recommended at all).


(snip)

However, I'd like to ask, how to best maintain this modified
functionality in the sourcecode.
I tried some possibilities, which seem to work, but I'd appreciate
suggestions on the preferred way in such cases.
- It is simply possibly to have a modified sourcefile difflib.py in
the script directory.


You'd better do real fork then and rename the damn thing to avoid 
confusions and name shadowing.




- Furthermore one can subclass difflib.SequenceMatcher an overide its
__chain_b function (however the name doesn't look like a public
function ...


It's indeed a very private one. Beware of name mangling here, can lead 
to surprising results !-)


Also, overriding an implementation method, your code might break with 
each new release, so it kind of tie you to a specific version (or set 
of...). The odds depend on difflib's source code stability.



- I guess, it wouldn't be recommended to directly replace
difflib.SequenceMatcher._SequenceMatcher__chain_b ...


For which definition of directly replace ? If you mean patching the 
standardlib's source code inplace, then it's definitly not something i'd 
do.  Monkeypatching OTHO is sometimes the simplest solution, specially 
for temporary fixes or evolutions.


Anyway - which solution (forking, subclassing or monkeypatching) is the 
most appropriate really depends on the context so only you can decide. 
If it's for personal use only and not mission-critical, go for the 
simplest working solution. If it's going to be publicly released, you 
may want to consider contacting the difflib maintainer and submit a 
patch, and rely on a monkeypatch in the meantime. If you think you'll 
have a need for more modifications / specialisations / evolution to 
difflib, then just fork.


My 2 cents.
--
http://mail.python.org/mailman/listinfo/python-list


Re: the bugerrd code

2010-06-24 Thread Bruno Desthuilliers

Victoria Hernandez a écrit :

The new mision I herits the buggered code (i do not the bugger). How
do debugger him? Tahnk you very much. Vikhy :)


http://docs.python.org/library/pdb.html#module-pdb
http://docs.python.org/library/unittest.html#module-unittest
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple list problem that's defeating me!

2010-06-24 Thread Bruno Desthuilliers

Neil Webster a écrit :

Thanks for the help so far.

The background to the problem is that the lists come from reading a
dbf file.  The code that I am trying to write is to merge lines of the
dbf based on the first column.  So in my example there would be three
lines:
a 2 3 4
b 10 11 12
a 2 3 4

The expected output from the above example lines would be:
a 4 6 8
b 10 11 12

 ... and the lines are read as: [[a,2,3,4],[b,10,11,12], [a,2,3,4]]



If you don't care about the original ordering, the following code should 
do.


# 8

def merge_rows(rows):
merged = dict()
for row in rows:
key, values = row[0], row[1:]
sums = merged.setdefault(key, [0, 0, 0])
for i, v in enumerate(values):
sums[i] += v

return [key] + value for key, value in merged.iteritems()]

import sys
def print_rows(rows, out=sys.stdout):
for row in rows:
print  .join(map(str, row))

if __name__ == '__main__':
inputs = [['a',2,3,4],['b',10,11,12], ['a',2,3,4]]
expected = [['a',4,6,8],['b',10,11,12]]
print inputs : 
print_rows(inputs)

outputs = merge_rows(inputs)
outputs.sort() # so we can do a simple equality test
assert outputs == expected, Expected %s, got %s % (
   expected, outputs
   )

print outputs :
print_rows(outputs)

# 8



In response to not posting working code or actual inputs, ummm, that's
why I am asking the question here.


In this context, working code means minimal code that a) can be 
executed and b) exhibits the problem you have, whatever the problem is. 
This code should include or be shipped with example input data and 
corresponding expected output data - as I did in the above code.



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


Re: Using Classes

2010-06-24 Thread Bruno Desthuilliers

Mag Gam a écrit :

I have been using python for about 1 year now and I really like the
language. Obviously there was a learning curve but I have a programing
background which made it an easy transition. I picked up some good
habits such as automatic code indenting :-), and making my programs
more modular by having functions.

I know that Python is very OOP friendly, but I could not figure out
why and when to use Classes in it.


If you have some more or less formal data type defined by ie dicts 
with some particular keys in them or tuples with a known structure, and 
a few fonctions working on these dicts or tuples, then you have a 
perfect use case for OO.


For other use case, have a look at the csv module or the various XML / 
SGML / HTML parsers in the stdlib. There's a pretty interesting paper 
from Alex Martelli here:


http://www.aleax.it/Python/os03_template_dp.pdf



I mostly use it for simple text
parsing  I suppose when a program gets complicated I should start
using Classes.


Not necessarily. OO is one way to organize code and data, but there are 
other ways that work as well, depending on the problem at hand and how 
your brain is connected.



Are there any tips or tricks people use to force them
into the OOP mentality? I would like to force myself to learn the
Python way but so far I could not figure out WHY I would need a class
for this...


Not going into OO when you don't need it IS actually the Python way !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to increment an IntVar?

2010-06-24 Thread Bruno Desthuilliers

Dennis Lee Bieber a écrit :
(snip - about Tkinter IntVar type)


It is NOT a numeric variable in Python realms.

So var+=increment can't be used because Python would rebind the name
var to a new object -- but Tkinter would still be hooked to the original
object and never see the change.


 foo = []
 bar = foo
 foo += [1]
 foo
[1]
 bar
[1]
 bar is foo
True
 foo.__iadd__([2])
[1, 2]
 _ is foo
True


IOW : __iadd__ doesn't necessarily returns a new object !-)



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


Re: modifying standard library functionality (difflib)

2010-06-24 Thread Bruno Desthuilliers

Vlastimil Brom a écrit :


Many thanks for your insights!
Just now, I am the almost the only user of this script, hence the
consequences of version mismatches etc. shouldn't (directly) affect
anyone else, fortunately.


So far so good.


However, I'd like to ask for some clarification about monkeypatching -
With directly replace I  meant something like the following scenario:

import difflib

def tweaked__chain_b(self):
# modified code of the function __chain_b copy from Lib\difflib.py
...

difflib.SequenceMatcher._SequenceMatcher__chain_b = tweaked__chain_b

I thought, this would qualify as monkeypatching,


It does, indeed


but I am apparently
missing some distinction between patching the ... code inplace  and
monkeypatching.


patching source code canonically means physically modifying the 
original source file. Monkeypatching - which can only be done in some 
dynamic languages - is what you're doing above, ie dynamically replacing 
a given feature at runtime.



By subclassing (which I am using just now in the code)


If it already works and you don't have to care too much about possible 
compat issues with different difflib versions, then look no further.


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


Re: From Dict to Classes yes or no and how

2010-06-22 Thread Bruno Desthuilliers

Jerry Rocteur a écrit :
(snip)

As part of learning Python, I'm also learning OOP! That is why I want to know 
if this is doable using classes.



The input is not important, I end up with the dictionary as described in the 
question and as I asked in the question,
I'd like to access the dictionary as a class


I assume you mean as an object (or as an instance of a class - which 
is exactly the same thing). If you don't understand what this means, 
then you should first learn the difference between a class and an 
instance !-)



and I don't know how or if it is possible.


Well, Python being 100% object, your dict is already an object (an 
instance of the builtin 'dict' class).



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


Re: Simple list problem that's defeating me!

2010-06-22 Thread Bruno Desthuilliers

Neil Webster a écrit :

Hi all,

I've got a simple problem but it's defeated me and I was wondering if
somebody could point out where I'm going wrong


1/ not posting working code (got a NameError)
2/ not posting the expected output
3/ not posting the actual output


or offer an alternative
solution to the problem?


When you'll have fixed the 3 problems listed above !-)

(snip broken code)
--
http://mail.python.org/mailman/listinfo/python-list


Re: setup server from scratch (with or without apache?)

2010-06-21 Thread Bruno Desthuilliers

News123 a écrit :

Hi,


So far I never really had to ask this question and this is also, why I
am stil a little shaky on this topic:

So far the typical LAMP server existed already and contained already a
lot of existing PHP web applications, which I couldn't remove.
Therefore I just used mod_python to implement some minor functionality
next to it.

Now I have the opportunity to setup a server from scratch.
90% of the content will be non visual content over https with client AND
server certificates.
Access privileges will depend on the client certificate.

I will only have one IP address and only port 443.

1.) What alternatives would exist compared to apache / mod_python


wsgi + any wsgi-compatible web server.


2.) What disadvantage would I have using apache and mod_python compared
to other solutions


Err... I guess you already got the most important answer on this !-)


3.) What's the stability / security aspect of other solutions,
especially concerning client / server certificates


Can't tell, sorry.


4.) How could I prepare for the case, that customer might lateron
require PHP? (not very probably, but who knows.


Just make sure you can run PHP with the web server you choose.

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


Re: variable variables

2010-06-18 Thread Bruno Desthuilliers

someone a écrit :

On Jun 18, 12:49 pm, James Mills prolo...@shortcircuit.net.au wrote:

On Fri, Jun 18, 2010 at 8:31 PM, someone petshm...@googlemail.com wrote:

I was looking for a short way to do it because I have a lot
some_object.attr.attr or some_object.other_attr.attr in code. it
looks like I cannot replace attr with just other variable and must
type some_object.other_attr.attr or your solution which is however
longer to type :)

It would actually help to see some code.



here it is, In Foo I'd like to have instead of A self.type and the
same in class B

from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
some_object.A.B
some_object.A.C
some_object.A.D
some_object.A.E
some_object.A.F
some_object.A.G

class Bar:
def __init__(self):
self.type = 'B'

def printAttr(self):
some_object.B.B
some_object.B.C
some_object.B.D
some_object.B.E
some_object.B.F
some_object.B.G




from some_module import some_object

def print_attributes(obj, *attribs):
  for attr in attribs:
print getattr(obj, attr, None)

class Foo(object):
  type = 'A'

  def print_attr(self):
print_attributes(getattr(someobject, self.type), *BCDEFG)

class Bar(Foo)
  type = 'B'


Still has a code smell thing to me, but hard to say not knowing the 
real code and context.

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


Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Christoph Groth a écrit :

Dear all,

sometimes it is handy to have a function which can take as argument
anything which can be converted into something, e.g.

def foo(arg):
arg = float(arg)
# ...

I would like to mimic this behavior of float for a user-defined type,
e.g. 


def bar(arg):
arg = My_type(arg)
# ...

Now I wonder what is the most pythonic way to write the __init__ method
of My_type?  The following comes to my mind:

class My_type:
def __init__(self, other):
if isinstance(other, type(self)):
self.a = other.a
self.b = other.b
return
# initialize self in some other way

It seems to me that in this way I might get problems when I pass an
instance of Derived_from_my_type to bar, as it will become an instance
of My_type.


The instance you pass to bar won't become anything else. You create a 
new My_type instance from the Derived_from_my_type one's values, and 
rebinding the _local_ name 'arg' only affects the local namespace.


OT
BTW, the convention in Python is to use TitleCase for class names 
(except - for historical reasons - for most builtin types which are 
lowercase).

/OT


What is a good way to express this?


Depends on what are the possible initializers / arguments for My_type. 
There are a few possible solutions but which one is best depends on the 
concrete case and personal tastes.


 In C++ 


Forget about C++ - Python is a different beast !-)


(which I know better than
python) I would make bar accept a const reference to My_type.  Then I
could use it directly with instances of My_type, Derived_from_my_type
and other types which can be converted into My_type.


If you only worry about being able to use any My_type like object - 
that is, any object implementing a given subset of My_type's interface, 
then just document your expectations in the function's docstring and use 
whatever object is passed in as if it was a My_type instance. Period. As 
long as you document what your function expects, it's the caller's 
responsaibility to make sure it provides something compatible. If he 
don't, well he'll get a nice traceback.


I know this might look very freestyle and a bit frightening when coming 
from one of these BD languages, but that's really the Python way, and 
from experience, it JustWork(tm).

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


Re: variable variables

2010-06-18 Thread Bruno Desthuilliers

someone a écrit :

On Jun 18, 2:05 pm, Bruno Desthuilliers bruno.
42.desthuilli...@websiteburo.invalid wrote:

(snip)


Still has a code smell thing to me, but hard to say not knowing the
real code and context.


sorry, code is not about printing variables rather accessing, it's
just example.


Yeps, this I understood - hence the  but... part of the sentence. What 
I dislike the most here is the obj.otherobj.yetanother.attrib stuff - 
might be ok in this case but it's an obvious violation of the law of 
Demeter (= AKA: only talk to your neighbour).


But anyway - if Foo only needs to know about someobject.A and Bar only 
needs to know about someobject.B, then resolve them once:



from some_module import some_object

class Foo:
def __init__(self):
self.type = 'A'

def printAttr(self):
target = getattr(someobject, self.type)
target.B
target.C
target.D
# etc...


This will also save a couple useless lookups. In fact, aliasing a 
commonly accessed attribute (or method) to a local name is an old time 
Python micro-optimization.


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


Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Christoph Groth a écrit :

Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid writes:


It seems to me that in this way I might get problems when I pass an
instance of Derived_from_my_type to bar, as it will become an
instance of My_type.

The instance you pass to bar won't become anything else. You create
a new My_type instance from the Derived_from_my_type one's values, and
rebinding the _local_ name 'arg' only affects the local namespace.


I understand that it won't become an instance of My_type globally.  But
it will become locally and this breaks polymorphism.


Then don't do it !-)


 (See code example
I provide at the end)


 In C++

Forget about C++ - Python is a different beast !-)


Still, it is useful and interesting to compare languages.


Indeed. But you have to understand enough of a language to compare it 
with another one. The old I can write C in any language syndrom...




(which I know better than python) I would make bar accept a const
reference to My_type.  Then I could use it directly with instances of
My_type, Derived_from_my_type and other types which can be converted
into My_type.

If you only worry about being able to use any My_type like object -
that is, any object implementing a given subset of My_type's
interface, then just document your expectations in the function's
docstring and use whatever object is passed in as if it was a My_type
instance. Period. As long as you document what your function expects,
it's the caller's responsaibility to make sure it provides something
compatible. If he don't, well he'll get a nice traceback.


This is not what I am worrying about.  I will try to be more explicit.


Ok.


I would like to have a class for a special matrix.  This is an
ordinary 2n by 2n matrix which can be thought of as consisting of four n
by n sized blocks.


Right.


At this moment, I just use normal numpy arrays (or anything which
behaves like them).  But I have very good reasons to actually have a
class for these special matrices.  Still, I would like to be able to
call functions which work with special matrices with plain numpy
arrays as arguments.  In that case, the arguments which are plain
matrices should be converted to special ones such that the main part
of the function can assume to always work with special matrices.


Ok. So you want to build a special matrice like object from the numpy 
array.



The code attached in the end (which is a complete runnable script)
should illustrate what I mean.

This example works as I want except that when bar is called with a an
argument of type Derived, it behaves as Base.


Ok.


 Also, I am not sure
whether there is a nicer way to achieve the following functionality for
Base.__init__:

If other is of type Base already, just pass it on.  Otherwise,
construct an instance of Base from it.


You can't do this in the initializer, you have to use either a factory 
function or the proper constructor (or an alternate constructor).




import numpy as np

class Base:


If you're using Python 2.x, make this:

class Base(object):


def __init__(self, other):
if isinstance(other, type(self)):
self = other


'self' is a local name. Rebinding a local name only impact the local 
namespace.



return
n = other.shape[0]
assert n == other.shape[1]
assert n % 2 == 0
n //= 2
self.a = other[0 : n, 0 : n]
self.b = other[n : 2*n, 0 : n]
self.c = other[0 : n, n : 2*n]
self.d = other[n : 2*n, n : 2*n]



Question : is there any case where you may want to instanciate this 
class with explicit values for a, b, c and d ?



Anyway: the simplest solution here is to replace the call to your Base 
class with a call to a factory function. I'd probably go for something 
like (QD untested code and other usual warnings) :


class Base(object):
def __init__(self, a, b, c, d):
self.a = a
self.b = b
self.c = c
self.d = d

   @classmethod
   def from_array(cls, arr):
alternate constructor from a numpy array 
   n = arr.shape[0]
   assert n == arr.shape[1]
   assert n % 2 == 0
   n //= 2
   return cls(
  arr[0 : n, 0 : n],
  arr[n : 2*n, 0 : n],
  arr[0 : n, n : 2*n],
  arr[n : 2*n, n : 2*n]
  )


def hello(self):
print 'hello from Base'


class Derived(Base):
def hello(self):
print 'hello from Derived'

def coerce(obj, cls=Base):
if isinstance(obj, cls):
return obj
else:
return cls.from_array(obj)


def bar(arg):
arg = coerce(arg)
# Do something useful with arg.{a..d}
arg.hello()

# This works.
a = np.identity(4)
bar(a)

# And this also.
a = Base.from_array(np.identity(4))
bar(a)

# And now this should work too
a = Derived.from_array(np.identity(4))
bar(a)



Does it solve your problem ?-)


Note that if using a plain

Re: constructing an object from another instance of the same class

2010-06-18 Thread Bruno Desthuilliers

Bruno Desthuilliers a écrit :

Christoph Groth a écrit :

Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid writes:


(snip)

 In C++

Forget about C++ - Python is a different beast !-)


Still, it is useful and interesting to compare languages.


Indeed. But you have to understand enough of a language to compare it 
with another one. The old I can write C in any language syndrom...


Re-reading this it might looks a bit patronizing. Sorry, was not my 
intention at all - it was just a general consideration (I mean mostly 
useless blah).


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


Re: Serializing functions

2010-06-17 Thread Bruno Desthuilliers

Matteo Landi a écrit :

Some weeks ago, here on the mailing list I read about picloud[1], a
python library used for cloud-computing; I was impressed by its
simplicity, here is an example:


import cloud
def square(x):

...  return x * x

cloud.call(square, 10)
cloud.result()

100

So, I tried to figure out how to achieve the same result, i.e. define a
local generic function and send it somewhere for remote execution, and
the get the result back.
So I thought about serialization (pickle): I made a few tries and it
seemed to work.. but I was wrong, because I never tried to load pickled
data from another session different from the one used to pickle data
itself. If you try and pickle a function, it is not pickled as a whole,
indeed, once you unpickle it, it will raise an exception telling you
that the target function was not found in the current module.

So I'm here, with nothing in my hands; how would you implement this?


Hint found on picloud's website:


PiCloud's programming library, cloud, automatically transfers the 
necessary source code, byte code, execution state, and data to run your 
function on our cluster.



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


Re: gui doubt

2010-06-17 Thread Bruno Desthuilliers

Andreas Tawn a écrit :

On 06/17/2010 01:04 AM, Stephen Hansen wrote:

On 6/16/10 10:40 PM, madhuri vio wrote:

if i want to create a button
which performs the transcription of dna to rna


(snip the GUI part)



Seems like a simple problem... or am I missing something?

def translate():
   return dna.replace(d, r)



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


Re: C interpreter in Lisp/scheme/python

2010-06-14 Thread Bruno Desthuilliers

answering the OP - didn't show up on c.l.py


On Sun, Jun 13, 2010 at 4:07 PM, bolega gnuist...@gmail.com wrote:

I am trying to compare LISP/Scheme/Python for their expressiveness.


Scheme is actually a lisp, isn't it ?


For this, I propose a vanilla C interpreter. I have seen a book which
writes C interpreter in C. 
The criteria would be the small size and high readability of the code.




Readability is partly function of the reader, so I fail to see how you 
define any objective metrics here.


Also, small size and high readability can easily conflict with each 
other. I pretty often rewrite (my own) one-liners to as many lines as 
necessary to make the code more readable / maintainable.



How would a gury approach such a project ?


Can't tell. Maybe you should ask one ?

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


  1   2   3   4   5   6   7   8   9   10   >