Re: Style question: metaclass self vs cls?
The standard is to use `cls`. In the __new__ method you can use `mcl` or `meta`. -- http://mail.python.org/mailman/listinfo/python-list
surprising behaviour of global dictionaries
I have the following module implementing a registry of functions with a decorator: $ cat x.py registry = {} # global dictionary def dec(func): registry[func.__name__] = func print registry, id(registry) return func if __name__ == '__main__': import xlib print registry, id(registry) The library xlib just defines two dummy functions: $ cat xlib.py from x import dec @dec def f1(): pass @dec def f2(): pass Then I get the following output: $ python x.py {'f1': } 27920352 {'f1': , 'f2': } 27920352 {} 27395472 This is surprising since I would expect to have a single global dictionary, not two: how comes the registry inside the ``if __name__ == '__main__'`` block is different from the one seen in the library? This is python 2.7.3 on Ubuntu. -- http://mail.python.org/mailman/listinfo/python-list
Re: surprising behaviour of global dictionaries
On Tuesday, October 9, 2012 5:24:17 PM UTC+2, Peter Otten wrote: > Seriously, you shouldn't use the main script as a library; it is put into > > the sys.modules cache under the "__main__" key. Subsequent imports under its > > real name will not find that name in the cache and import another instance > > of the module, with puzzling effects Actually I usually never use the main script as a library, this is why I never experience this puzzling behavior before. But now it is clear, thanks. -- http://mail.python.org/mailman/listinfo/python-list
Testing against multiple versions of Python
Yesterday I released a new version of the decorator module. It should run under Python 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3. I did not have the will to install on my machine 8 different versions of Python, so I just tested it with Python 2.7 and 3.3. But I do not feel happy with that. Is there any kind of service where a package author can send a pre-release version of her package and have its tests run againsts a set of different Python versions? I seem to remember somebody talking about a service like that years ago but I don't remembers. I do not see anything on PyPI. Any advice is welcome! Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing against multiple versions of Python
ShiningPanda looks really really cool. I need to investigate it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Instrumenting a class to see how it is used
This may get you started (warning: not really tested). $ echo instr.py from warnings import warn oget = object.__getattribute__ tget = type.__getattribute__ class Instr(object): class __metaclass__(type): def __getattribute__(cls, name): clsname = tget(cls, '__name__') warn('accessing %s.%s' % (clsname, name), stacklevel=2) return tget(cls, name) def __getattribute__(self, name): warn('accessing %s.%s' % (self, name), stacklevel=2) return oget(self, name) Then change the base classes of the class you want to instrument, i.e. class MyClass(MyBase) -> class MyClass(MyBase, Instr) and see what happens. It should work in simple cases. It will log a lot, so will have to adapt this. -- http://mail.python.org/mailman/listinfo/python-list
A better contextlib.contextmanager
Python 3.2 enhanced contextlib.contextmanager so that it is possible to use a context manager as a decorator. For instance, given the contextmanager factory below @contextmanager def before_after(): print(before) yield print(after) it is possibile to use it to generate decorators: @before_after() def hello(user): print('hello', user) This is equivalent to the more traditional def hello(user): with before_after(): print('hello', user) but it has the advantage of saving a level of indentation and we all know that flat is better than nested. Cool, but there are three issues: 1. I am using Python 2.7, not Python 3.2, so contextmanager has not such feature 2. The contextmanager decorator is losing the signature of the before_after factory: >>> help(before_after) Help on function before_after in module __main__: before_after(*args, **kwds) 3. before_after() decorators do not preserve the signature of the decorated function either. Since I am the author of the decorator module I have easily found out a recipe to solve both issues. Here it is: from decorator import decorator, FunctionMaker from contextlib import GeneratorContextManager class GeneratorCM(GeneratorContextManager): def __call__(self, func): return FunctionMaker.create( func, "with _cm_: return _func_(%(shortsignature)s)", dict(_cm_=self, _func_=func), __wrapped__=func) @decorator def contextmanager(func, *args, **kwds): return GeneratorCM(func(*args, **kwds)) before_after() objects obtained by using this version of contextmanager become signature-preserving decorators. I am not going to explain how FunctionMaker performs its magic (hint: it uses eval), but I am asking a question instead: should I add this feature to the next release of the decorator module? Do people use the context-manager-as-decorator functionality? It is quite handy in unit tests and actually I think it came from the unittest2 module. But I am reluctant to complicate the API of the module, which currently is really really small and such has been for many years. -- http://mail.python.org/mailman/listinfo/python-list
Re: Argparse, and linking to methods in Subclasses
Here is an example by using my own library plac (http://pypi.python.org/pypi/plac): class Server(): def configure_logging(self, logging_file): pass def check(self): pass def deploy(self): pass def configure(self): pass def __init__(self, hostname): self.hostname = hostname class SpamServer(Server): def check(self): pass class HamServer(Server): def deploy(self): pass def main(classname, hostname, methname): # add error checking at will instance = globals()[classname](hostname) getattr(instance, methname)() if __name__ == '__main__': import plac; plac.call(main) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's super() considered super!
On Friday, May 27, 2011 10:49:52 AM UTC+2, Ben Finney wrote: > The exquisite care that you describe programmers needing to maintain is IMO > just as much a deterrent as the super-is-harmful essay. Worth quoting. Also I think this article may encourage naive programmers along the dark path of cooperative multiple inheritance, when they could instead use better designs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's super() considered super!
The fact that even experienced programmers fail to see that super(type(self),self) in Python 2 is NOT equivalent to super() in Python 3 is telling something. -- http://mail.python.org/mailman/listinfo/python-list
Re: Class decorators might also be super too
He is basically showing that using mixins for implementing logging is not such a good idea, i.e. you can get the same effect in a better way by making use of other Python features. I argued the same thing many times in the past. I even wrote a module once (strait) to reimplement 99% of multiple inheritance without multiple inheritance, just to show that in can be done in few lines of code in a language as powerful as Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: multiprocessing shows no benefit
There is a trick that I use when data transfer is the performance killer. Just save your big array first (for instance on and .hdf5 file) and send to the workers the indices to retrieve the portion of the array you are interested in instead of the actual subarray. Anyway there are cases where multiprocessing will never help, since the operation is too fast with respect to the overhead involved in multiprocessing. In that case just give up and think about ways of changing the original problem. -- https://mail.python.org/mailman/listinfo/python-list
Re: Let's talk about debuggers!
pdb plus plus: https://pypi.python.org/pypi/pdbpp -- https://mail.python.org/mailman/listinfo/python-list
Re: Recommendation for Object-Oriented systems to study
On Sunday, May 29, 2016 at 4:42:17 PM UTC+2, Ankush Thakur wrote: > Hello, > > I'm a self-taught programmer who has managed to claw his way out of Python > basics and even covered the intermediate parts. But I feel I have a ton of > theory in my head and would like to see some smallish applications in action. > More specifically, I'm looking for Object Oriented designs that will help me > cement my knowledge and expose me to best practices that books never cover. I > have half a mind to start reading up the Django or Pandas source code, but I > don't want to overwhelm myself. > > Can somebody recommend smaller and simpler projects I can learn from? And if > I can pick the brains of the creator, bonus points! > > Thanks in advance! > > Ankush Read the source code of the doctest module in the standard library. -- https://mail.python.org/mailman/listinfo/python-list
Re: argparse and subparsers
I did not know about docopt. It is basically the same idea of this recipe I wrote about 12 years ago: https://code.activestate.com/recipes/278844-parsing-the-command-line/?in=user-1122360 Good that it was reinvented :-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Metaclasses, decorators, and synchronization
Michael Ekstrand ha scritto: > One issue remains in this function: my method's signature is lost when > synchronized is applied (at least as somemeth=synchronized(somemeth); > I'm currently in a 2.3 environment that doesn't have the decorator > syntax, but my understanding is that makes no difference). I've been > able to preserve the doc string by setting the __doc__ attribute of the > inner function before returning it, but is there a way to make this > inner function appear to bear the same argument list as the original > method? I've been poking around in new and inspect, but it is not > appearing like an easy task. It is not that easy, but you can leverage on my decorator module which does exactly what you want: http://www.phyast.pitt.edu/~micheles/python/decorator.zip Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 308 accepted - new conditional expressions
Terry Reedy ha scritto: > "Dave Benjamin" <[EMAIL PROTECTED]> > > > Hooray! After years of arguing over which syntax to use, and finally > > giving up since nobody could agree, > > I understand that this has become the local 'politically correct' view, but > as a participant in the discussion, I know it not true and actively > deceptive. The community was prevented from coming to a decision. There > was a 'primary' vote with an incumbent, 15 challengers, and several > write-ins. But there was no runoff. FWIW, I think Terry's recollection is pretty close to the "historical truth". Guido could have decided two years ago, sparing us the PEP 308 ordalia. So, I am happy that at the end we will have a conditional operator, but I am not happy of how the process worked out. It was just an enormous waste of resources that could have been employed much better :-( Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
how to send a SIGINT to a Python process?
Is there a way to send a SIGINT/KeyboardInterrupt to a Python process (knowing the pid) that works both on Unix and Windows? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature Proposal: Sequence .join method
This can be shortened to def interlace(x, i): """interlace(x, i) -> i0, x, i1, x, ..., x, iN """ i = iter(i) i.next() for e in i: yield x yield e I have noticed a while ago that inside generators StopIteration is automatically trapped, i.e. def g(): yield 1 raise StopIteration yield "Never reached" only yields 1. Not sure if this is documented behavior, however, of if it is an implementation accident. Anybody who knows? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recipes: list mixin, improved timeit, etc
Well, suppose you have a class MyObject and you want to add to it some methods to make its instances into a database. You could put these methods into another class called Storable (the mixin class). Then you can mix MyObject with Storable and get what you want, a class StorableObject inheriting both from Storable and MyObject. Of course you can reuse Storable to make storable even other classes, for instance you could define a StorableOtherObject inheriting from OtherObject and Storable. Once in a time, I thought mixins where a good idea; now I don't think so since they are too easily abused (see Zope 2) and as a consequence you get spaghetti-inheritance, where you have objects with methods inherited from everywhere. So be very careful if you want to use mixins; often you can go without them. Just my 2 Euro cents, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python recipes: list mixin, improved timeit, etc
Paul Rubin wrote: > Yeah, I wonder though how much of that is a result of Python's > cavalier approach to multiple inheritance. Does that happen much in > CLOS? In Java because of multiple interfaces? I've studied Flavors a > little and mix-ins were used in some extensive ways, but maybe > programs using them required extra care. I don't think Python approach to multiple inheritance is cavalier (you may want to clarify that statement). In CLOS multiple inheritance is less of a problem since (multi)methods are defined outside classes. One could argue that using classes also as a scope-control mechanism (i.e. doing the job of modules) is an abuse. > The Python tutorial does caution against indiscriminate use of > multiple inheritance. I tried coding something without it, wished > that I'd used it and did so in the next version, but still am not sure > if I gained anything or not. Nowadays I tend to use delegation via __getattr__ instead of multiple inheritance. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't extend function type
If you google a bit on the newsgroup, you should find a message from me asking about the ability to subclass FunctionType, and a reply from Tim Peters saying that the only reason why this was not done is lack of developer time and the fact that this was not considered an important priority. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
users of pycurl here?
I am having a hard time in finding out how to retrieve information about the *size* of files I want to download from an FTP site. Should I send a QUOTE SIZE command to the ftp server or is there an easier way? TIA, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: users of pycurl here?
The Effbot wrote: > here's a robust parser for various LIST output formats: > >http://cr.yp.to/ftpparse.html > > (google for "ftpparse" to find python bindings for that module) Well, I have downloaded the one from your site (ftpparse-1.1-20021124) and I have given a python setup.py install. Now I have a _ftpparse.so which exposes a single function 'parse'. However both the module and the function do not have any docstring, the underscore makes me believe that there should be a ftpparse.py file which is missing, and the README says "for a usage example, see the sanity.py test script" but there is not such a script in the distribution :-( Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: users of pycurl here?
Yes, it works fine, thanks (still I am a bit surprised there is not ftpparse.py but only an _ftpparse.so). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Batteries Included?
Mike Meyer: > After you create a setup.py file for you program, doing > > "python setup.py bdist --formats=wininst" > > should do the trick. > > Of course, I don't own a Windows box, so I can't check it, but when I > ask a setup file for help on formats, it tells me the wininst format > is a windows installer. I can confirm that it works (for pure Python applications), since I did it. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Well written open source Python apps
> Could anyone suggest an open source project that has particularly well > written Python? I am especially looking for code that people would > describe as "very Python-ic". I vote for the "doctest" code in the standard library. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
example of using urllib2 with https urls
Can somebody provide an example of how to retrieve a https url, given username and password? I don't find it in the standard documentation. TIA, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Tom Anderson: >> I have no idea what Scheme is, but I'll cettainly look it up as soon as >> I'm done writing this. > You won't like it. Give yourself another 5-10 years, and you might start > to find it strangely intriguing. +1 ;-) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Alex Martelli wrote: > ... remember Pascal's "Lettres Provinciales", > and the famous apology about "I am sorry that this letter is so long, > but I did not have the time to write a shorter one"!-) This observation applies to code too. I usually spend most of my time in making short programs that would have been long. This means: cutting off non-essential features (and you can discover that a feature is non essential only after having implemented it) and/or rethinking the problem to a superior level of abstraction (only possible after you have implented the lower level of abstraction). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs Ruby
Alex Martelli: > Michele Simionato: >> cutting off non-essential features (and you can discover that a feature >> is non essential only after having implemented it) > This one is difficult if you have RELEASED the program with the feature > you now want to remove, sigh. Yeah, but I used the wrong word "features", which typically means "end user features". Instead, I had in mind "developer features", i.e. core features that will be called later in "client" code (I am in a framework mindset here). Typically I start with a small class, then the class becomes larger as I add features that will be useful for client code, then I discover than the class has become difficult to mantain. So I cut the features and and I implement them outside the class and the class becomes short again. However, I *cannot* know from the beginning what is the minimal set of features needed to make short the client code until I write a lot of client code. I can make things short only after I have made things long. I think this applies to me, to you, to Pascal and to everybody in general. It is impossible to start from the beginning with the short program, unless you already know the solution (that means, you have already written the long version in the past). Still, some naive people think there is a silver bullet or an easy way to avoid the hard work. They are naive ;) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: tool for syntax coloring in html
Gerhard wrote: > http://initd.org/pub/software/pysqlite/doc/usage-guide.html Can I suggest you to use a larger font for the code?It is pretty difficult to parse with my current screen resolution. BTW, pysqlite2 is pretty cool ;) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Web automation with twill
BTW, O'Reilly just published an article of mines on twill: http://www.onlamp.com/pub/a/python/2005/11/03/twill.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Web automation with twill
qwwwee: > By the way, are you aware that C. Titus Brown (twill's author) > tells "peste e corna" of Zope? No, but I am not surprised. I also say "peste e corna" of Zope ;) In general I am an anti-frameworks guy (in good company with many Pythonistas including Guido). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: which feature of python do you like most?
> which feature of python do you like most? It makes easy things easy, while keeping hard things possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing Tkinter on knoppix
sudo apt-get install python2.4-tk -- http://mail.python.org/mailman/listinfo/python-list
Re: web interface
I have been looking for an example like this for a while, so thanks to J.P. Calderone. Unfortunately, this kind of solution is pretty much browser-dependent. For instance, I tried it and it worked with Firefox, but not with MSIE 5.01 and it will not work with any browser if you disable Javascript. So, I don't think there is a real solution for this kind of problem as of today (I would love to be wrong, though). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Tutorials for Python + PostgreSQL
Steve: > I want to learn more about enterprise-level programming using Python > and PostgreSQL. From what I've searched, it seems that psycho is > interesting to improve runtime too. Do you have tutorials, articles and > tips to learn this combination? I've been working with PostgreSQL for 2 > years, and with Python for 6 months. > Thank you, Since Psyco is meant to speedup Python code, whereas the psycopg adapter is C-coded, I strongly doubt you will get any improvement from the combination. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: super() and multiple inheritance
Hermy: > So, for the moment my conclusion is that although Python has some > syntax for multiple inheritance, it doesn't support it very well, and I should > probably stick to single inheritance. This is not much a problem of Python, the problem is that multiple inheritance is intrinsically HARD to support. If you can avoid it, avoid it. This will probably make your application more maintanable. I your case, I would go with the keyword argument suggestion. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite flavor of Linux? (for python or anything else)
I tried Kubuntu and Debian (in the trivial to install version known as Knoppix/Kanotix) and I like Debian more, but this is just me. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)
Just wrote: > In article <[EMAIL PROTECTED]>, > Simo Melenius <[EMAIL PROTECTED]> wrote: > > > I've sometimes replaced sys.stdout (and/or sys.stderr) to > > capture/redirect debugging information in existing code that has > > unwisely just "print"ed error and warning messages, instead of using > > sys.stderr or error logging modules. > > > > py> def with_output_to_string (func): > > ... try: > > ... sys.stdout = StringIO.StringIO () > > ... func () > > ... return sys.stdout.getvalue () > > ... finally: > > ... sys.stdout = sys.__stdout__ > > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. > > Just -- http://mail.python.org/mailman/listinfo/python-list
Re: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!)
(Not sure if my other message arrived) I am guilty of using this idiom, too. The standard library http://www.python.org/dev/doc/devel/lib/module-sys.html#l2h-396 says: """ __stdin__ __stdout__ __stderr__ These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to restore the actual files to known working file objects in case they have been overwritten with a broken object. """ Notice the "during finalization" sentence. Maybe you should change the doc and explain what __stdout__ is intended for? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Frameworks for "Non-Content Oriented Web Apps"
Well, with your first post you managed to get a very unclear picture of what you mean by "non-content oriented Web Application" ;-) Judging from your following posts, you want an easy way to construct Web interfaces, i.e. forms. This can be done with any Web framework, but a typical Web framework provides a lots of content-related functionality you don't want. For instance you could use Plone for your task, but you would waste 99% of its functionality and it would be absolutely overkill. If I had to write a Web application such as Webmin, for instance, i.e. one that use a Web interface to manage other applications, I would use Quixote as my Web framework of choice. Its key points are simplicity and the fact that it provides *very little*. Just the form library would be enough for you. Since the different part of Quixote are well separated, the learning curve is really really small. It also takes a little time to evaluate it. I suggest you to give a look at it. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
Maybe a PSF grant would help? I guess this has been considered ... Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: The Industry choice
But then I have THREE published recipes!! Does that mean that I get three free copies of the cookbook ? ;-) Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)
Holger: > FWIW, i added the recipe back to the online cookbook. It's not perfectly > formatted but still useful, i hope. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 Uhm... on my system I get: >>> german_ae = unicode('\xc3\xa4', 'utf8') >>> print german_ae # dunno if it will appear right on Google groups ä >>> german_ae.decode('latin1') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) ?? What's wrong? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
Aahz: > The first three PSF grants were all in some way not directly related to > changing the core language. One was for a library, one for improving > Jython, and one for improving docs. Giving the PSF more money increases > the chances for additional work. Here is the link you forgot to post ;-) http://www.python.org/psf/grants/ The one about the docs seems more about teaching scientists how to use Python. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)
Yep, I did the same and got confused :-/ Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)
Stephan: > I'd rather use german_ae.encode('latin1') ^^ > which returns '\xe4'. uhm ... then there is a misprint in the discussion of the recipe; BTW what's the difference between .encode and .decode ? (yes, I have been living in happy ASCII-land until now ... ;) I should probably ask for an unicode primer, I have found the one by Marc André Lemburg http://www.reportlab.com/i18n/python_unicode_tutorial.html and I am reading it right now. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
Paul Rubin: > I'm now running the Python > that was included in Fedora Core 3 GNU/Linux, a complete OS distro on > a DVD-ROM, containing about 3 gigabytes not including sources. And > when a user installs 3 gigabytes of software from a DVD, they can > reasonably expect that they've installed a complete system and > shouldn't need to download anything additional to use all the features > of the programs on the DVD. Now the Fedora maintainers aren't Python > gurus--people ask for Python so they did the obvious thing: downloaded > it, ran its installer, put the output into their distro, and said "ok, > Fedora has Python". That's all they should need to do to incorporate > Python into Fedora. So it's up to the Python maintainers, not the > Fedora maintainers or the user, to make sure that the Python distro > has everything that users need, without further downloading. Dunno about Fedora, I stopped using Red Hat just because they were *not* using the standard Python distribution, and the version they shipped was cripped in various ways. There is nothing the Python developers can do if the OS vendors choose to ship modified Python distributions, with missing modules or splitted in n separated packages to download separately. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
John Roth: > The bottom line is that I'm not going to be writing any > extensive pieces of Python documentation. My time > is better spent elsewhere. Well, a couple of years ago I realized that some documentation on the MRO was missing. I wrote a document in reST, posted here, and Guido put it on python.org. It was as easy as it sounds. So I don't see your problem. Dave Kulhman wrote some utility to convert reST in latex using the same style of the standard library docs; I haven't used it myself, but you may check with him: http://www.rexx.com/~dkuhlman/ P.S. since you cite descriptors, what's wrong with Raimond Hetting documentation? http://users.rcn.com/python/download/Descriptor.htm The only problem I see is that it is not integrated with the official docs, but this is a minor issue, I think. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python evolution: Unease
Did you used Tkinter and Tix? Most of my problems were there. Of course, I also got in trouble when upgrading to Python 2.2 from 1.5.2 Finally they switched to Python 2.2, but at that moment Python 2.3 came out and I got tired. I switched to Mandrake 1.5 and I am happy with it. Never had any serious trouble with urpmi and lots of Python packages are available. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python-dev Summary for 2004-11-16 through 2004-11-30
> Would you like the source with your function? Yes, since I asked for this feature something like two years ago ;-) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: parameterized metaclass (or metametaclass)
> I was wondering if there is some simpler way of building parameterized > metaclasses ? Why not just a function returning metaclasses? def metaFactory(*args): dic = return type("somemetaclass", (type,), dic) Alternatively, a metaclass classmethod returning a metaclass, so that you can use something like __metaclass__ = MyMetaclass.with(*args) # classmethod returning a metaclass Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python3: 'where' keyword
> But we're talking about the mythical/hypothetical Python 3, so maybe > there's a chance of fixing the scoping rules, which it seems to me are > currently pretty badly broken. I don't think the current scoping rules will be changed in Python 3.0. I can't give you the link right now, but there are threads about the scope rules in python-dev, with various people protesting and Guido saying that he wants to keep them as they are. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: "A Fundamental Turn Toward Concurrency in Software"
> So I've always had it in > the back of my mind that languages that can easily support massive > (especially automatic) parallelization will have their day in the sun, > at least someday. and the language of the future will be called ... FORTRAN! :-) (joking, but it is the only language I know supporting massive parallelization ...) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Returning same type as self for arithmetic in subclasses
Max. M.: > So I wondered if there was a simlpler way to coerce the result into my > desired types rather than overwriting the __add__, __sub__ etc. methods? Tim Peters: >> Generally speaking, no. But I'm sure someone will torture you with a >> framework that purports to make it easy . I will not dispute the Timbot assessment ;) He is also right that people have already undergone under this level of torture: see http://tinyurl.com/6m373 for instance. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
readline, rlcompleter
This a case where the documentation is lacking. The standard library documentation (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives this example try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") but I don't find a list of recognized key bindings. For instance, can I would like to bind shift-tab to rlcompleter, is that possible? Can I use function keys? I did various attempt, but I did not succed :-( Is there any readline-guru here with some good pointers? Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & unicode
Uhm ... >>> class C(object): ... pass ... >>> setattr(C, "è", "The letter è") >>> getattr(C, "è") 'The letter \xe8' ;-) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Securing a future for anonymous functions in Python
Jacek: > Given a population with previous exposure to computer programming, my > money is on the map-lambda version. But this last point is mostly > irrelevant. The fact is that you cannot program computers without > doing a bit of learning ... and the lambda, map and friends really do > not take any significant learning. This kind of "sociological" study would be pretty interesting to me ;-) Personally, I find out that my mind manage pretty well one-level of indirection at time, not two. Consider for instance def add1(x): return x+1 map(add1, mylist) Here there are *two* levels of indirection: first, I need to define add1; second I need to translate mentally map to a loop. Using lambda does not help: map(lambda x: x+1, mylist) still would require two levels for me, one to recognize the lambda and one to convert map to a loop. This is too much for me, so I just write [x+1 for x in mylist] where everything is explicit (or if you wish, I have just to recognize that there is a loop going on, pretty easy). However, if I can skip a level of indirection (i.e. I do not need to define a function) I just prefer map: map(int, mylist) is simpler for me than [int(x) for x in mylist] since the latter introduces an useless x (which is also polluting my namespace, but this not my point, I could use a generator-expression instead). So, in practice, I only use map with built-in or with predefined functions, i.e. functions which are already there for some other purpose; I do not like to be forced to write a function (or a lambda) for the only purpose of using map (at least in Python). Incidentally, I am not fond of the name "lambda" too. "fn", as Paul Graham says, looks much better. What I would like, in Python, is some facility to manage callbacks in the standard library, then I would live pretty well without lambdas. Just IMHO, YMMV, etc. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & unicode
I forgot to add the following: >>> setattr(C, "è", u"The letter è") >>> getattr(C, "è") u'The letter \xe8' >>> print getattr(C, "è") The letter è Python identifiers can be generic strings, including Latin-1 characters; they cannot be unicode strings, however: >>> setattr(C, u"è", "The letter è") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 0: ordinal not in range(128) So you are right after all, but I though most people didn't know that you can have valid identifiers with accented letters, spaces, and non printable chars. > setattr(C, " ", "this works") > getattr(C, " ") Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
python and macros (again) [Was: python3: 'where' keyword]
Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the output of a macro is ugly or not, > if no human is ever going to look at it? But at least some human eye have to look at it! Did you ever debug a macro? More seriuosly, I have given some thought to the issue, and I am very much against the introduction of macros in Python. Here are a few reasons: 1. I like defmacro in Lisp. Problem is, Lisp is an s-expression based language, Python is not. We cannot implement defmacro in Python and even if we could, if would be too ugly to be used (at least, IMHO). 2. One could proposed hygienic pattern-matching macros in Python, similar to Scheme syntax-rules macros. Again, it is not obvious how to implement pattern-matching in Python in a non-butt-ugly way. Plus, I feel hygienic macros quite limited and not worth the effort. 3. We would add to Python the learning curve of macros and their subtilities and we do not want it. 4. Macros would complicate a lot Python module system. 5. We have Guido providing a good syntax for us all, why we should be fiddling with it? More seriously, if some verbosity is recognized in the language (think to the "raison d'etre" of decorators, for instance) I very much prefer to wait for Guido to take care of that, once and for all, than having 100 different custom made solutions based on macros. I am sure I could find other reasons if I think a bit more, but these should suffice for the moment ;) What I would be interested in is a Lisp/Scheme implementation compiling to Python bytecode, but I am not aware of any project in that direction. Michele Simionato P.S. some pointers for people interested on the topic: http://logix.livelogix.com/ (a Python-like language with macros) https://sourceforge.net/projects/pymac/ (an experimental Dylan-inspired macro system for Python) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & unicode
Kent: > I don't think so. You have hacked an attribute with latin-1 characters in it, but you > haven't actually created an identifier. No, I really created an identifier. For instance I can create a global name in this way: >>> globals()["è"]=1 >>> globals()["è"] 1 > According to the language reference, identifiers can only contain letters a-z and A-Z, > digits 0-9 and underscore. >http://docs.python.org/ref/identifiers.html The parser has this restriction, so it gets confused if it finds "è". But the underlying implementation just works for generic identifiers. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python and macros (again) [Was: python3: 'where' keyword]
Paul Rubin: > [EMAIL PROTECTED] writes: >> > It wasn't obvious how to do it in Scheme either. There was quite > a bit of head scratching and experimental implementation before > there was consensus. Actually I am not convinced there is consensus yet, i.e. there is a non-negligible minority of schemers convinced that original Lisp macros where better, not to talk of common lispers ;) >> 3. We would add to Python the learning curve of macros and their >> subtilities and we do not want it. > I can't imagine how it could be worse than the learning curve of > __metaclass__, which we already have. To me, learning macros *and their subtilities* was much more difficult than learning metaclasses. >> 4. Macros would complicate a lot Python module system. > I don't see how, but maybe I'm missing something. Go to comp.lang.scheme and google for "macros and module system"; you will get everything you want to know and much more! >> 5. We have Guido providing a good syntax for us all, why we should be >> fiddling with it? More seriously, if some verbosity is recognized >> in the language (think to the "raison d'etre" of decorators, for >> instance) I very much prefer to wait for Guido to take care of >> that, once and for all, than having 100 different custom made >> solutions based on macros. > Every time some newbie asks an innocent "how do I ..." question, we > see unbelievably horrid answers from gurus. Just check the FAQ about > conditional expressions, etc. I just don't see Python syntax changes > as forthcoming. Well, I see this as a positive fact. If a syntax is contrived (such as a ternary operator, for instance) it is better *not* to have it than to have one hundred custom made syntaxes. At the end, we are just talking about syntax sugar here, not about lack of functionality. >> What I would be interested in is a Lisp/Scheme implementation >> compiling to Python bytecode, but I am not aware of any project >> in that direction. > But that sounds like a bizarre idea. Python bytecode is just a > CPython artifact, not part of the language. And it's not even that > good an artifact. Good Lisp/Scheme implementations compile to native > code that beats the pants off of CPython bytecode. It would make much > more sense to have a Python implementation that compiles Python to > S-expressions and then lets a high performance Lisp or Scheme system > take care of the rest. This is a bizarre idea if you want to make Python run faster. It is not so bizarre if what you want is to have access to Python from Lisp/Scheme in the same sense Jython has access to Java. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: "private" variables a.k.a. name mangling (WAS: What is print? A function?)
>Name mangling is there to keep you from accidentally hiding such an >attribute in a subclass, but how often is this really a danger? Can >someone give me an example of where __-mangling really solved a problem >for them, where a simple leading underscore wouldn't have solved the >same problem? Look at the "autosuper" implementation on Guido's descrintro paper; there the fact that you user __super instead of _super is essential. However I have written tens of thousands of lines of Python code and never needed __protected variables except in a few experimental scripts for learning purpose. So I agree that the need does not occur often, but it is still an useful thing to have. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
FTP Server
What's the simplest way to write an FTP Server in Python? A short research on the newsgroup and on the Cookbook did not bring out anything relevant (but I hear a little voice in the back of my head saying Twisted, Twisted! ...) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP Server
Do you have a code snippet/pointer so I have an idea of how to use it? M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP Server
> If you're after a simple FTP server, have a look at medusa. Uhm ... Medusa does not seem actively maintained nowadays. M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... Once I opted for C++ in a very small project and > believed everyone will stick with C subset + better type checking > offered through C++ - but I simply could not manage to keep them off > using OO stuff which was just making program more complicated than it > should have been. (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)), so I > prefer preemptively dealing with issue of everyone showing off their OO > design skills) > I think Davor is making an important point here: Python has grown in the last 14 years, and it is no more the simple scripting language it used to be. In particular, it evolved a lot of OOP "cruft" (static/classmethods, properties, the __new__ method, super, the new MRO, descriptors,metaclasses, etc.) and there is more than a learning curve issue coming with the added complexity. Davor is right: even if you do not want to use it, the stuff is *there* and somebody in your team will. So definitely there is an audience of programmers that just do not have an use for all the sophistication and actually are penalized by it. There is not much than can be done at the Python level. But I would see with interest a Python spinoff geared towards simplicity. Few months ago there was the Prothon proposal (by all means a terrible proposal) but the goal that motivated it (simplification, trying to remove classes) was in my opinion worthwhile. Now, *how* to remove (or simplify) classes is not at all clear to me, not I am convinced that prototypes are the right way to go, but still I feel that there is something wrong with inheritance. Maybe protocols are the solution, who knows? But in any case I think it is important to keep searching for semplicity. I do not believe Python is the definitive language, and it is probabily possible to introduce something better. It is just that nothing of the kind appeared until now, but I keep watching at the horizon ;) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
Peter Maas: >[EMAIL PROTECTED] schrieb: >> Davor is right: even if >> you do not want to use it, the stuff is *there* and somebody in your >> team will. So definitely there is an audience of programmers that just >> do not have an use for all the sophistication and actually are >> penalized by it. >No, because Python does not enforce using advanced concepts. You >can write programs that are as simple as in 1991. A group of developers >always has to find some kind of common style with a chance that some >are penalized. This can happen with every language. No. In theory C++ could be kept as simple as C but in practice it is not. >> There is not much than can be done at the Python level. But I would >> see with interest a Python spinoff geared towards simplicity. >I think this would be useless because advanced concepts exist for >a reason. A simplified spin-off would aquire advanced concepts >over time and would just become a clone of Python. And then we will need another simplified spinoff ;) There is always a fight between simplificity and complexity. Some complexity is not needed, and I am sure even in Python something could be dropped. But it is difficult to find what can be removed. Remember that Saint-Exupery quote? Something like "a work of art is finished when there is nothing left to remove?" M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
> "Perfection is achieved, not when there is nothing more to add, but > when there is nothing left to take away." Thanks, that was it! ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: future of computing languages
I found that page very shallow and superficial. What they call "the language of the future" is actually the language of the present. Python (but also, Ruby, Perl, Smalltalk, Lisp, Scheme, ...) have already most of the features they list. Then they claim "the language of the future will be so different from the languages we have now that we cannot imagine how it will be". This is pretty naive. A Lisper would say that nothing new happened in the last 40 years. Actually, I think that something new happened, but not that much. The progress was more in the technology than in the programming paradigms. I mean, OO was already there in Simula. It this very possible that the language of 2045 will not be very different from the current dynamic languages. The all page reminds me of the excitation of 60's about the space program (affirmations such "in the year 2000 we will have colonies on Mars") We all know how it ended :-( Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Popularizing SimpleHTTPServer and CGIHTTPServer
Just submitted a recipe with this goal in mind: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/365606 Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: new style exception handleing
Google is your friend. This has been discussed a lot in the past. For instance, google for the thread, "Exceptions as New Style Classes", there was also a PEP by Steven Taschuk, IIRC. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: advice needed for simple python web app
Dan Perl: > The application is just something I'm playing with to learn a little bit on > web apps. It uses an HTML form to send an email. The form takes inputs > like the From:, To: and Subject: fields and a text field. It is difficult to beat CGI + CGIHTTPServer for conceptual simplificity and easy of use: however, Quixote comes close and it has a *much* better support for forms. Here is an example from the minidemo in the distribution, so you have an idea of how the code looks like: > from quixote.publish import Publisher > from quixote.directory import Directory > class RootDirectory(Directory): >_q_exports = ['', 'hello'] >def _q_index(self): >return ''' >Welcome to the Quixote demo. Here is a >link. > > >''' >def hello(self): >return 'Hello world!' > def create_publisher(): >return Publisher(RootDirectory(), > display_exceptions='plain') > if __name__ == '__main__': >from quixote.server.simple_server import run >print 'creating demo listening on http://localhost:8080/' >run(create_publisher, host='localhost', port=8080) The exported methods of your directory class corresponds to Web pages; _q_index returns the main page, hello an hello word page. This works out of the box with no configuration at all, you don't need to create a cgi-bin directory, nothing. It is trivial to replace simple_server with a more serious server (twisted_server, scgi_server, etc. ) Notice: this example works in Quixote 2.0 which is currently in alpha. Don't let the "alpha" scares you: that means that the documentation is still a bit rough and few things are not fully settled down, but the framework is very much usable. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
making symlinks with distutils
I want to distribute a pure Python package with this structure: >mypackage > __init__.py > module1.py > module2.py > ... > myexecutable.py In particular, myexecutable.py is a script which is intended to be used from the command line via the shebang trick. I want to distribute on Unices. and I want a symlink /usr/bin/myexecutable -> /mypackage/myexecutable.py to be made at installation time, when the user runs "python setup.py install". What is the recommanded way to do that? Do I need a postinstallation script or something like that? I could do that in various way, but I don't see the obvious one, maybe because I am not a Dutch ;) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: making symlinks with distutils
>From what I see in the docs, registering a script just normalize the shebang line, but does not install it in /usr/bin, nor make any symbolic links, so it is not what I am looking for. I guess I need to add a os.link(src, dst) somewhere in the setup.py script or in a postinstallation script but I am not exactly sure where. M.S. -- http://mail.python.org/mailman/listinfo/python-list
Re: making symlinks with distutils
Sylvain Thenault: > Actually it does install it is $PREFIX/bin. Aha! And how do I set $PREFIX? Is it a Unix environment variable or is it a keyword argument in setup? Something like setup( prefix="/usr") ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is there no instancemethod builtin?
In this case I have used hasattr(obj, "__iter__") instead of isinstance(obj, list) (strings are iterable but do not have __iter__ method). I think hasattr is much better since it works for tuples and custom iterables too. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is there no instancemethod builtin?
I think strings do not have __iter__ on purpose, exactly to distinguish them from other iterables, since sometimes it is nice to consider them atomic, but I am not sure of this. You should ask the developers. Anyway, the right definition of iterable is (as I was told) "an object X such that iter(X) does not throw an exception". Objects following the __getitem__ protocol - such as strings -are iterables even if they do not have an __iter__ method. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: "static" data descriptors and possibly spurious calls to __set__?
>...it's this last one that causes the problem. In the real code, the >call to type.__setattr__ referred to above seems to lead to a call to >something like cls.__base__.__dict__[attr].__set__(cls, value). Uhm ... sounds right, but I a bit confused. Could you please give us a doctest showing us what you get and what you would like to get? Michele Simionato Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Create our own python source repository
qwwee: > for a certain argument I'd prefer an application fully >explained (also if not covering all the features) to a more general >tutorial with only brief and unrelated code snippets. >Unfortunately, that's not the way things are normally done, because it >is much harder to build a useful application and fully comment it A part the Cookbook, I know of at least two Python books taking the approach you describe: 1. Dive into Python (Pilgrim) 2. Programming Python (Lutz) Dive into Python is free (and even translated in Italian on www.python.it, IIRC) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Lisp development with macros faster than Python development?..
Fuzzyman: > So Lisp is for really good programmers, and Python is for > mediocre programmers ? Python is *also* for mediocre programmers. I see this as a strength, not as a weakness. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Web-Forms
Use twill:http://www.idyll.org/~t/www-tools/twill.html Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
>I am mostly >using old style (without type unification) init but this motivate the >shift for the new style. Is there somewhere a document about this? Yes, see http://www.python.org/2.3/mro.html by yours truly Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
> http://fuhm.org/super-harmful/ That is a pretty good page; I must say that my position is more radical (i.e. it is not super which is harmful, it is multiple inheritance itself that it is harmful: was I going to design a new language I would implement it *without* multiple inheritance). Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
Sion Arrowsmith > That way lies Java well, no, a dynamic language such as Python with the possibility of adding methods on the fly and metaclasses could live pretty well without multiple inheritance. There would be no real loss of power and hopefully less monstruosities such a Zope 2. But maybe this is just wishful thinking ... Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Block-structured resource handling via decorators
I will shamelessly point out my decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip The documentation is here: http://www.phyast.pitt.edu/~micheles/python/documentation.htm There is an example of redirecting stdout which is relevant to this thread. HTH, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
If I understand correcly you have a situation like this: Base | Parent1 Mixin | | | | Children1 Base | Parent2 Mixin | | | | Children2 Base | Parent3 | | Children3 The Base class is pretty general, Parent1, Parent2 and Parent3 are more specific, Children1 and Children2 requires the Mixin class, but Children3 does not require it. Let me note that this looks like a sensible design and that I agree that in simple situations multiple inheritance could be the simplest solution. Nevertheless 1) I am scared of the case where you have hundreds of methods coming from everywhere (ex. Zope) and 2) even in simple situations a solution without multiple inheritance is not that much worse. Various solutions (using pseudocode): 1. use single inheritance and attach the mixin methods by hand: class Children2(Parent2): pass for methodname, method in methods_of(Mixin): setattr(Children2, methodname, method) if you think this is ugly, use a metaclass to attach the methods for you. This is probably still ugly, since it is akin to reimplementing multiple inheritance by hand. Still, it can be done, if you really want. 2. use single inheritance and delegation. If "mixin" is a proxy to the methods in the mixin (for instance implemented as an attribute descriptor) you could do class Children2(Parent2): mixin = Proxy(Mixin) c2 = Children2() and then c2.mixin.method(args) would actually call Mixin.method(c2, args). I like this solution since it is clear where methods come from and it scales better to complex situations (still if you have only 2 or 3 methods multiple inheritance could be pretty fine). 3. think differently and use multimethods There are implementations of multimethods in Python (for instance in PEAK). This example looks like a good candidate for a multiple dispatch solution. You would use single inheritance and promote the mixin methods to multimethods. BTW, I think multimethods are pretty nifty and I would welcome them in standard Python. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
Mike Meyer: > I think you're replying to me, but you didn't include any indication > so I can't be sure. Oops, sorry, yes, I was replying to you. > These two are cases of what I was talking about when I referred to the > Church-Turing thesis. Well, let me put it in this way. If a language can implement a missing feature easily, then you are not really missing a big thing. And the feature may not be provided by default for sake of semplicity and/or uniformity of style. For instance Python does not have repeat-until loops, case statement, ternary operator, etc. (obviously I am not advocating to remove multiple inheritance now, I am justing speculating, talking about an hypotetic new Python-like language). > Also, I don't see how they make the situation > you are scared of above any better. It would discourage some people from some abuses, in the same sense the absence of repeat-until, case statemente, ternary operator etc are working right now. > > 3. think differently and use multimethods > > I don't see how that would help at all. You haven't done anything > about solving the base problem - that getting the methods into my > classes cleanly needs multiple inheritance. Further, I don't need > methods that are distinguished based on their arguments - they all > take a fixed set of arguments, and operate on them and the state of > the instance. None seem to be candidates for being multimethods. The > mixin methods tend to provide general functionality, and get used in > radically different places by the different child classes. > > You did miss the one alternative I considered: making the methods of > Mixin stand-alone functions, and passing them extra arguments instead > of using attributes of the instance. They would all then look like > mixin_func(self.foo, self.bar, var, value). I decided that this wasn't > as readable as inherting the methods. Uhm? I do not follow you. Multimethods would dispatch according to the type and would act differently on the childrens, dependending on their state. Perhaps I would need more information to understand what you have in mind. But at the end my point is "I would not feel much more constrained in expressivity if I did not have multiple inheritance in Python, and actually I have found out that the more I use OOP, the less I use inheritance". Just curious if others had a similar experience. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
doctest bug with nested triple quotes
I am getting trouble with nested triple quoted strings in doctest. For instance $ cat x.py """ >>> dummy = ''' something here ''' """ import doctest; doctest.testmod() $ python x.py ** File "x.py", line 2, in __main__ Failed example: dummy = ''' Exception raised: Traceback (most recent call last): File "/usr/lib/python2.4/doctest.py", line 1243, in __run compileflags, 1) in test.globs File "", line 1 dummy = ''' ^ SyntaxError: EOF while scanning triple-quoted string ********** Is this a know bug? Any workaround? Thanks for comments, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: doctest bug with nested triple quotes
This is my file $ python -c "print open('x.py').read().encode('base64')" IiIiCj4+PiBkdW1teSA9ICcnJwpzb21ldGhpbmcKaGVyZQonJycKIiIiCmltcG9ydCBkb2N0ZXN0 OyBkb2N0ZXN0LnRlc3Rtb2QoKQo= but anyway I think Peter Otten is right, the problem is with the missing dots. It makes sense, actually, but for some reason I would never have thought of it (I did not expect doctest to be so smart to strip the dots even inside a string). Thanks for the feeback and the quick solution, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
issues with doctest and threads
I am getting a strange error with this script: $ cat doctest-threads.py """ >>> import time, threading >>> def example(): ... thread.out = [] ... while thread.running: ... time.sleep(.01) ... thread.out.append(".") >>> thread = threading.Thread(None, example) >>> thread.running = True; thread.start() >>> time.sleep(.1) >>> thread.running = False >>> print thread.out ['.', '.', '.', '.', '.', '.', '.', '.', '.'] """ if __name__ == "__main__": import doctest; doctest.testmod() $ python doctest-threads.py Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.4/threading.py", line 442, in __bootstrap self.run() File "/usr/lib/python2.4/threading.py", line 422, in run self.__target(*self.__args, **self.__kwargs) File "", line 5, in example NameError: global name 'thread' is not defined I have found out a workaround, putting 'thread' in the main program (i.e. in the globals): $ cat doctest-threads2.py """ >>> thread.running = True >>> thread.start() >>> time.sleep(.1) >>> thread.running = False >>> print thread.out ['.', '.', '.', '.', '.', '.', '.', '.', '.'] """ import time, threading def example(): thread.out = [] while thread.running: time.sleep(.01) thread.out.append(".") thread = threading.Thread(None, example) if __name__ == "__main__": import doctest; doctest.testmod() However this is strange, since replacing in the first script >>> globals()["thread"] = threading.Thread(None, example) does NOT work, so it is not just putting stuff in the globals. Also, it seems that I cannot reproduce the same error in absense of threads. Any idea of what is happening? Thanks for sharing, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: issues with doctest and threads
Thank you for your replies Jeff & Tim. The snippet I submitted is unfortunate, since I was writing an example (for a Python course I am going to give in September) to show that you cannot reliably assume that you will get exactly 9 dots, because of the limitations of 'sleep'. Mindlessly, I have cut & pasted that snippet, but my real question was not "how many dots I get", it was: "why the error message talks about 'thread' not being in the globals?" It's true that I can avoid it with a thread.join() (which I had forgot), but still I really cannot understand the reason for such message. Why it is so misleading? Can something be done about it? TIA, Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: issues with doctest and threads
Tim Peters wrote: > Because the program is buggy: synchronizing threads isn't a "do it if > you feel like it" thing, it's essential to correct threaded behavior. > If you're going to show students bad thread practice, they're going to > get mysteries a lot deeper and more damaging than this one <0.5 wink>. Well, yes, but here I am using bad practices *on purpose*, trying to figure out the most likely mistakes of my students. I want to show them what they should NOT do, and what happens if they do. I personally don't have that much practice with threads (for instance, I knew about .join() but I forgot to use it) so it is also good for me if I do some mistake. Luckily the course is not about threads, but I might cover them as an optional topic. > Properly synchronize the thread, to enforce what the code requires but > cannot hope to obtain by blind luck. All it takes is the > thread.join() I suggested. I don't understand why you're fighting > that, because it's basic proper thread practice -- it's not like I > suggested an obscure expert-level hack here. I am not fighting .join() at all; but I want to know what I should expect in case I do a mistake. This is pretty useful in case I had to debug a threaded program written by my students. > If a student doesn't > know to join() a thread before they rely on that thread being done, > their thread career will be an endless nightmare. This is exactly the reason why I want to show them what happens if they don't use it ;) > All that said, this specific failure would _happen_ to go away too, if > in doctest's DocTestRunner.run(), the final 'test.globs.clear()" were > removed. If you feel it's necessary to let threads spawned by a > doctest run beyond the time doctest completes, you can arrange to > invoke DocTestRunner.run() with clear_globs=False. Perfect, this answers my question and gives me an useful tip about doctest globals. Thanks a lot! Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI tookit for science and education
1. Mateusz Loskot: >I would like to ask some scientists or students >which GUI toolkit they would recommend >to develop scientific prototypes (for education and >testing some theories). My vote is for ipython + matplotlib. Very easy and very powerful. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator and Metaclasses Documentation
There are also my lectures at Oxford: http://www.reportlab.org/~andy/accu2005/pyuk2005_simionato_wondersofpython.zip Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: shelve non-transparency
The option writeback=True seems to work: # put something in the shelve import shelve class C(object): pass s = shelve.open("x.shelve") s["x"] = C() s.close() # read it s = shelve.open("x.shelve", writeback=True) c = s["x"] c.attr = 1 print s["x"].attr # => 1 s.close() Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Setting the encoding in pysqlite2
An easy question, but I don't find the answer in the docs :-( I have a sqlite3 database containing accented characters (latin-1). How do I set the right encoding? For instance if I do this: #-*- encoding: latin-1 -*- from pysqlite2 import dbapi2 as sqlite import os DBFILE="/tmp/example.db" def writedb(conn): c = conn.cursor() c.executescript(""" create table example (word char(20)); insert into example values ("così"); """) c.close() def readdb(conn): c = conn.cursor() c.execute("select * from example;") #print c.fetchall() c.close() if __name__ == "__main__": conn = sqlite.connect(DBFILE) writedb(conn) readdb(conn) conn.close() os.remove(DBFILE) I get UnicodeDecodeError: 'utf8' codec can't decode byte 0xec in position 3: unexpected end of data (notice, even if the 'print' statement is commented. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Externally-defined properties?
Well, I have used factories of properties external to the class many times, and they work pretty well. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list