Re: Overriding a global
Roy Smith wrote: > I've got a code pattern I use a lot. In each module, I create a logger > for the entire module and log to it all over: > > logger = logging.getLogger('my.module.name') > > class Foo: >def function(self): > logger.debug('stuff') > logger.debug('other stuff') > > and so on. This works, but every once in a while I decide that a > particular function needs a more specific logger, so I can adjust the > logging level for that function independent of the rest of the module. > What I really want to do is: > >def function(self): > logger = logger.getChild('function') > logger.debug('stuff') > logger.debug('other stuff') > > which lets me not have to change any lines of code other than inserting > the one to redefine logger. Unfortunately, that's not legal Python (it > leads to "UnboundLocalError: local variable 'logger' referenced before > assignment"). > > Any ideas on the best way to implement this? def function(self, logger=logger.getChild("function")): logger.debug("stuff") But the "best way" is to use another name. -- http://mail.python.org/mailman/listinfo/python-list
Verbose and flexible args and kwargs syntax
Throwing an idea for a PEP out there: It strikes me that the def func(*args, **kwargs) syntax is rather unpytonic. It certainly did not have that 'for line in file' pythonic obviousness for me as a beginner. Plus, asterikses are impossible to google for, so finding out what exactly they do more or less forces you to write a forum post about it. A more readable form occurred to me, which also happens to be more flexible, and which I think is fully compatible with the syntax of the language: def func(parg, list(args), dict(kwargs)) Perhaps this is considered abuse of notation; dict(kwargs) already has a meaning rather different from the one we try to give it here; but then again the context (being inside a function definition) is unique and easily recognizable. An added advantage would be the possibility of using subclasses of dict and list as well; imagine how much more beautiful a lot of code would be if one could say def func(attrdict(kwargs)) Problems im still wrestling with: the same syntax could not be used when calling a function; that lack of symmetry would make things more confusing, not less. Thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On Sun, Dec 11, 2011 at 9:49 PM, Eelco Hoogendoorn wrote: > Problems im still wrestling with: the same syntax could not be used when > calling a function; that lack of symmetry would make things more confusing, > not less. That symmetry is a large factor, IMHO. I can write a wrapper function like this: def fixedargs(x,y,z): return wrappedfunc(x,y,z) Or like this: def anyargs(*args,**kwargs): return wrappedfunc(*args,**kwargs) Either way, it's a perfect parallel, and that's very useful for noticing errors. With a keyworded syntax, that's going to be a lot harder. Another issue: You suggest being able to use "attrdict" or some other dict subclass. This means that, rather than being a language construct, this will involve a name lookup. And what happens if you have a class that subclasses both list and dict? Will it get the positional args, the keyword args, or both? Laudable notion, but I'm not sure that it'll actually work in practice. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get a correct entry in the menu for a Python application on Mac OS X
I got it working by creating a symbolic link to the Python interpreter to be used in my application package and using this symbolic link to start the main Python script. Gregory Ewing wrote: > Detlev Offenbach wrote: >> I am fairly new to Mac OS X and would like to know, what I have to do >> to make my Python application show the correct name in the menu bar. >> What did I do so far. I created an application package containing the >> .plist file with correct entries and a shell script, that starts the >> correct Python interpreter with the the main script. > > I don't think that will work, because the executable that > your shell script is starting is in an app bundle of its > own, and MacOSX will be using the plist from that bundle, > which just has the generic "Python" name in it. > > There are a couple of things you could do: > > 1) Use py2app to create your app bundle. It does the > right things -- not sure exactly what, but it works. > > 2) Hack things at run time. I use the following PyObjC > code in PyGUI to set the application name: > >from Foundation import NSBundle > >ns_bundle = NSBundle.mainBundle() >ns_info = ns_bundle.localizedInfoDictionary() >if not ns_info: > ns_info = ns_bundle.infoDictionary() >ns_info['CFBundleName'] = my_application_name > -- Detlev Offenbach det...@die-offenbachs.de -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
Chris Angelico wrote: > Either way, it's a perfect parallel, and that's very useful for > noticing errors. > > With a keyworded syntax, that's going to be a lot harder. If it used keywords then you could keep symmetry quite easily: def anyargs(arglist args, argdict kwargs): return wrappedfunc(arglist args, argdict kwargs) and you would have the advantage of two new keywords that people could actually search on. > > Another issue: You suggest being able to use "attrdict" or some other > dict subclass. This means that, rather than being a language > construct, this will involve a name lookup. And what happens if you > have a class that subclasses both list and dict? Will it get the > positional args, the keyword args, or both? Irrelevant, you can't subclass both list and dict: >>> class C(list, dict): pass Traceback (most recent call last): File "", line 1, in class C(list, dict): pass TypeError: multiple bases have instance lay-out conflict -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On Sun, Dec 11, 2011 at 11:39 PM, Duncan Booth wrote: > Chris Angelico wrote: > If it used keywords then you could keep symmetry quite easily: > > def anyargs(arglist args, argdict kwargs): > return wrappedfunc(arglist args, argdict kwargs) > > and you would have the advantage of two new keywords that people could > actually search on. Yes, that's just a strict keywordification of the * and ** symbols. The same argument could be made for eliminating the standard algebraic + operator and replacing it with a keyword "__add__". I don't think that's worthwhile. The OP suggested using 'dict' and 'list' themselves as the keywords, thus allowing the use of subclasses. This would make it unsearchable, or else rather verbose: def anyargs(pack list args, pack dict kwargs): return wrappedfunc(pack list args, pack dict kwargs) With this syntax, what happens if you muck up list/dict? Or alternatively, the briefer syntax: def anyargs(pack list args, pack dict kwargs): return wrappedfunc(pack args, pack kwargs) which breaks the symmetry, and doesn't say which one you're doing - for instance, if you only use one out of list and dict args, it would make sense to have a variable "options" or "args" that gets unpacked to the function's arguments - and there's no way to see whether it's going to be keyword or positional. The verbose syntax has a lot going for it, but it's rather verbose. Why say "pack list args" when you can just say "*args"? Compare initializer syntax between Python and PHP: foo = ["asdf", "qwer", {1:2, 3:4}] $foo = array("asdf", "qwer", array(1=>2, 3=>4)) Is it more Pythonic to use explicitly-named types, or to have simple notation that's clear and easy to read? Or is this a matter for personal preference? >> Another issue: You suggest being able to use "attrdict" or some other >> dict subclass. This means that, rather than being a language >> construct, this will involve a name lookup. And what happens if you >> have a class that subclasses both list and dict? Will it get the >> positional args, the keyword args, or both? > > Irrelevant, you can't subclass both list and dict: > TypeError: multiple bases have instance lay-out conflict Ah. Curious. I've not done much with multiple inheritance in Python (come to think of it, I don't recall when I last used MI in _any_ language). In any case, there's still the potential unclarity as to _which_ of dict and list is the one that's been inherited, which requires a run-time lookup to solve. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
Am 11.12.2011 13:39, schrieb Duncan Booth: >> Another issue: You suggest being able to use "attrdict" or some other >> dict subclass. This means that, rather than being a language >> construct, this will involve a name lookup. And what happens if you >> have a class that subclasses both list and dict? Will it get the >> positional args, the keyword args, or both? > > Irrelevant, you can't subclass both list and dict: But you can fake it with __instancecheck__ and __subclasscheck__ methods. Christian -- http://mail.python.org/mailman/listinfo/python-list
Verbose and flexible args and kwargs syntax
Yes, that's just a strict keywordification of the * and ** symbols. The same argument could be made for eliminating the standard algebraic + operator and replacing it with a keyword "__add__". I don't think that's worthwhile. Well, its not quite the same in the sense that algebraic operators are essentially part of 'natural language', or at least extremely widely adopted. They have earned their own special symbols. Argument packing/unpacking is a very specific thing; a small corner of a particular programming language. However, as seen in the light of python 3 head-tail syntax, perhaps the above is not quite true, and one could argue that packing/unpacking of collections is indeed a quite general concept, deserving of its own symbols. Breaking uniformity with that use case would also be a bad thing; ideally, a verbose alternative to all occurances of collection packing/unpacking would be available. That said, a more verbose and flexible syntax would be desirable there too; as of now, the tail is always a list. I havnt read the discussions leading up to those design decisions, but that seems like a compromise to me; something like head,tuple(tail) = someiterable would be preferrable there too, id say -- http://mail.python.org/mailman/listinfo/python-list
Verbose and flexible args and kwargs syntax
As for syntax; what about coopting/integrating with the function annotation syntax? so: def func(args: list, kwargs: attrdict) and correspondingly in the function call? a, b:tuple = someiterable? I guess a rule that interprets every function argument annotated as a subclass of list or dict as a special case would severely restrict its intended use though... -- http://mail.python.org/mailman/listinfo/python-list
Using python on OS X Lion
I have recently upgraded my Snow Leopard to Lion and now I am having all problems with python on my system e.g.: I have install PIL with easy_install but when I do import PIL Python cannot find the pil library. Installing psycopg2 in the same way was successful and I can use psycopg2 without a problem. Further, the new version of Python is 2.7.1 in Lion. But when I just run 'python' it calls up 2.6.5 - even after I have moved the application python2.6 to Trash. I see several guidelines for using python on OS X: some using macports, others homebrew and others 'pip' and 'virtualenv' . I come from a Linux background where a proper packaging system like apt (on Debian) prevent these types of problems. So my question: What is the recommended way of setting up a python environment in OS X? And how do I get rid of legacy python libraries on my system? Regards Johann -- Because experiencing your loyal love is better than life itself, my lips will praise you. (Psalm 63:3) -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Book authoring
Have a look at Markdown + pandoc. Regards Johann -- Because experiencing your loyal love is better than life itself, my lips will praise you. (Psalm 63:3) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using python on OS X Lion
In article , Johann Spies wrote: > I have recently upgraded my Snow Leopard to Lion and now I am having all > problems with python on my system e.g.: > > I have install PIL with easy_install but when I do > > import PIL > > Python cannot find the pil library. Installing psycopg2 in the same way was > successful and I can use psycopg2 without a problem. > > Further, the new version of Python is 2.7.1 in Lion. But when I just run > 'python' it calls up 2.6.5 - even after I have moved the application > python2.6 to Trash. > > I see several guidelines for using python on OS X: some using macports, > others homebrew and others 'pip' and 'virtualenv' . I come from a Linux > background where a proper packaging system like apt (on Debian) prevent > these types of problems. > > So my question: What is the recommended way of setting up a python > environment in OS X? > > And how do I get rid of legacy python libraries on my system? First, determine which python is being loaded. In OS X 10.7 (Lion), Apple ships 2.7.1, 2.6.7, and 2.5.6 version of Python (all in /usr/bin) so the 2.6.5 is coming from elsewhere. If you previously installed a Python from a python.org installer, the framework will be in /Library/Frameworks/Python.framework (and *not* /System/Library/Frameworks, which is where Apple's Pythons are and should not be modified). The python.org installers, by default, may modify your shell profiles (i.e. .bash_profile, .profile, et al) to prepend its framework bin directory to your shell PATH. Look for something like this: # Setting PATH for MacPython 2.6 # The orginal version is saved in .profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}" export PATH There are more details here http://bugs.python.org/issue7107 Also understand that if you use easy_install or pip, each Python instance needs to have its own version of either one. Apple supplies versions of easy_install in /usr/bin for its Pythons. If you install another version of Python, you'll need to install another easy_install and pip for it as well. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
unittest. customizing tstloaders / discover()
Hi, I'd like to have a custom test loder, which will filter out certain tests or which just searches tests in certain directories. I'd like to use regular expresions as include / exclude rules and I would like to have another filter function, which would check for the existence of certain metavariabels in test suite files WHat would be the best starting point for such an example. Thanks a lot in advance for any info / pointer /tutorial . . .. -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On Sun, 11 Dec 2011 11:49:23 +0100, Eelco Hoogendoorn wrote: > Throwing an idea for a PEP out there: > > It strikes me that the def func(*args, **kwargs) syntax is rather > unpytonic. It certainly did not have that 'for line in file' pythonic > obviousness for me as a beginner. Plus, asterikses are impossible to > google for, so finding out what exactly they do more or less forces you > to write a forum post about it. No more so than any other form of punctuation. Plus and minus + - may be so common that just about everyone knows it, but how about | == @ % and even . (dot)? None of these things will be obvious to newbies who have never programmed before. Oh well. Some things you just have to learn. As for impossibility of googling for asterisks, it might help if you spell it correctly http://duckduckgo.com/?q=python+asterisk Fourth hit says: *vargs puts all left-over non-keyword arguments into a tuple called vargs. **kargs puts all left-over keyword arguments into a dictionary called kargs. Even better, this works amazingly well: http://duckduckgo.com/?q=python+* Or you can Read The Fine Manual, which has a section for special symbols: http://docs.python.org/genindex-Symbols.html which is moderately easy to discover from the main page: Main page => Documentation => Browse Current Documentation => General Index => Symbols. Not ideal, but not too bad. > A more readable form occurred to me, which also happens to be more > flexible, and which I think is fully compatible with the syntax of the > language: > > def func(parg, list(args), dict(kwargs)) > > Perhaps this is considered abuse of notation; dict(kwargs) already has a > meaning rather different from the one we try to give it here; but then > again the context (being inside a function definition) is unique and > easily recognizable. I consider that excessively verbose as well as misleading. It is excessively verbose for the same reason as: let y equal x plus 1 would be considered excessively verbose. I'm very fond of some languages with verbose syntax, like Hypertalk and OpenXION where you might say "add 1 to x", but I don't want Python to become them. It's a judgement call as to where a language divides "cryptic punctuation line noise" and "useful short operators", and in my opinion * and ** tuple and dict unpacking fall strongly on the "useful short operators" side. Your opinion may differ, but luckily for me, the BDFL agrees with me :) It is also misleading because args are not collected into a list, but into a tuple. Worse, it suggests that one should be able to generalise to something like this: def func(parg, str(args), int(kwargs), my_func(more_args)): which is incoherent. And lastly, this would require either promoting list and dict to proper keywords, which will not happen, or worse, making them semi-keywords (treated as keywords in some contexts, but not in others), which also will not happen. > Problems im still wrestling with: the same syntax could not be used when > calling a function; that lack of symmetry would make things more > confusing, not less. Precisely. > Thoughts? People learn to spell strings "like this" instead of str(like this), and to use # for comments instead of REMARK or REM. It's not that much of a burden on them to learn to use * and ** -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Documentation for python-evolution - where?
I'm trying to use the python evolution (as in Gnome Evolution) module but I can't find any documetation beyond the odd trivial example and the API documentation at http://doc.conduit-project.org/evolution-python/ (or similar places presumably). The trouble with the API documentation is that it tells me that evolution.ebook has three functions:- get_self_contact(...) list_addressbooks(...) open_addressbook(...) but then there is no documentation at all that I can find which tells me what the functions return and the functions/methods that can be called on the returned data. I know that open_addressbook() returns an address book (surprise!) but then, except for what I can glean from the examples I can find, there doesn't seem to any documentation on what methods I can call on the returned address book to extract data from it. Can anyone point me at anything with a bit of detail about the evolution module? -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On 12/11/2011 5:49 AM, Eelco Hoogendoorn wrote: Plus, asterikses are impossible to google for, so finding out what exactly > they do more or less forces you to write a forum post about it. There are other means of finding information than Google. Really. 1. A couple of years ago, I wrote a very complete list of symbol syntax uses in Python 3. You can get is at https://xploro.googlecode.com/files/PySymbols.html Unfortunately, searching for 'python syntax symbols' does not show this on the first few pages. 2. The python docs have an index. While the Symbols page does not have most of the entries in the above doc, it does have '* in function calls' and '** in function calls'. 3. The meaning of * and ** in function calls is explained, surprise, in the reference manual section (5.3.4 for Py3) on function calls, which is in the chapter on expressions. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest. customizing tstloaders / discover()
Gelonida N writes: > I'd like to use regular expresions as include / exclude rules > and I would like to have another filter function, which would check for > the existence of certain metavariabels in test suite files Did you have a look at nose? I'm using it and it supports include/exclude rules via RE and lets you select directories to run tests from. I'm not sure about the meta-variable thing, but it supports plug ins that could do the trick… -- http://mail.python.org/mailman/listinfo/python-list
Verbose and flexible args and kwargs syntax
No more so than any other form of punctuation. Plus and minus + - may be so common that just about everyone knows it, but how about | == @ % and even . (dot)? None of these things will be obvious to newbies who have never programmed before. Oh well. Some things you just have to learn. Yes, some things you just have to learn. Nonetheless, I strongly prefer explicit logical operators over |, would much rather have 'equals' instead of ==, which is stylistic in line with 'is' and explicitly distinguishes between equality and identity comparisons. As for %; it is entirely unclear to me why that obscure operation ever got its own one-character symbol. Ill take 'mod', or even better, 'modulus' any day of the week. The dot is clearly quantitatively in another realm here. 90% of typical python code is attribute accesses. The dot is entirely unambigious and cannot be mistaken for anything else. It reads like a book. It's a judgement call as to where a language divides "cryptic punctuation line noise" and "useful short operators", and in my opinion * and ** tuple and dict unpacking fall strongly on the "useful short operators" side. Your opinion may differ, but luckily for me, the BDFL agrees with me :) I also agree that it is a value judgement as to which constructs get their own cryptic symbols and which do not, but the are some reasonable guidelines we should be able to agree upon. Obscure operations should not reserve any of the few available characters. Furthermore, the language should not just be formally consistent, but also easy to grasp at a glance, without deciphering subtle semantics of a blurb of weird characters. (some programming languages obviously disagree, but python, as far as I am allowed to speak for it, does not). And most importantly, if you cant come up with a terse syntax that does everything you want to do, the terse syntax should at best be an alternative to the verbose one. It is also misleading because args are not collected into a list, but into a tuple. In case you wanted a tuple youd write tuple(args), obviously. Exactly that added flexibility is half of my case in favor. Why shouldnt it be a list when I want it to? Worse, it suggests that one should be able to generalise to something like this: def func(parg, str(args), int(kwargs), my_func(more_args)): which is incoherent. Sorry, but I dont get this point at all. Does ** suggests one should be able to generalize to ***? The rules are the rules. The real questions, in my mind, are: 1) How useful is this added flexibility? Not insanely, but I can see it making a lot of code significantly more clean. And: 2) How fundamental is collection packing/unpacking? One can easily argue that it is indeed quite fundamental and therefore deserves its own terse symbols, I feel. However, if more flexibility is indeed deemed desirable, such terse syntax quickly gives way to a more verbose one. Can you come up with some terse symbols that will be able to express all of the below and dont make you wish you hadnt rather typed out the names? head, tuple(tail) = iterable head, list(tail) = iterable head, str(tail) = somestring head, generator(tail) = mygenerator And so on. If not, one has to admit that functionality is being sacrificed on the alter of terseness, which seems like a raw deal to me. -- http://mail.python.org/mailman/listinfo/python-list
Verbose and flexible args and kwargs syntax
There are other means of finding information than Google. Really. This is really only a very minor point in my argument, so I dont want to put the focus on this. But really, no. Googling 'myprogramminglanguage conceptimtryingtofigureout' is my first, second and third line of defence. Yes, I could read the reference manual from top to bottom, and if I already knew about the existence of your article then im sure that would be a great help too. But the situation one finds oneself in is seeing two asterikses and not even being aware they are particular to function definitions/invocations. Im fluent in many different languages and well versed in CS concepts and jargon, but I had no idea what to search for when first trying to figure out the meaning of these symbols, and that does not happen often to me. -- http://mail.python.org/mailman/listinfo/python-list
What happened to module.__file__?
I've just started using a Debian system, instead of the usual RedHat based systems I'm used to, and module.__file__ appears to have disappeared for some (but not all) modules. On Fedora: [steve@orac ~]$ python -E Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21) [GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.__file__ '/usr/lib/python2.6/lib-dynload/mathmodule.so' and on Debian squeeze: steve@runes:~$ python -E Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.__file__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__file__' What's going on? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On Mon, Dec 12, 2011 at 10:53 AM, Eelco Hoogendoorn wrote: > Googling 'myprogramminglanguage conceptimtryingtofigureout' is my first, > second and third line of defence. Yes, I could read the reference manual > from top to bottom, and if I already knew about the existence of your > article then im sure that would be a great help too. Python in particular has very poor internal search. I don't recommend searching the Python docs for anything that you can search for externally using Google, duckduckgo, etc, etc. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Documentation for python-evolution - where?
On Mon, Dec 12, 2011 at 9:28 AM, wrote: > I'm trying to use the python evolution (as in Gnome Evolution) module > but I can't find any documetation beyond the odd trivial example and > the API documentation at http://doc.conduit-project.org/evolution-python/ > (or similar places presumably). One of the downsides of software you don't pay money for is that, all too often, there's little or no documentation. One of the upsides of free software is that you can look at the source code. I don't know anything about Python-Evolution, but if you're prepared to do a bit of digging, you can probably find what you want here: http://git.gnome.org/browse/gnome-python-desktop/tree/evolution/ (You probably have a copy of the same content on your own hard disk somewhere, too.) Once you figure out what you wanted, do consider sending a patch to the maintainer(s), improving the docstrings and/or external documentation, so the next person has an easier task. :) Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Verbose and flexible args and kwargs syntax
On Mon, 12 Dec 2011 00:44:38 +0100, Eelco Hoogendoorn wrote: >> No more so than any other form of punctuation. Plus and minus + - may >> be so common that just about everyone knows it, but how about | == @ % >> and even . (dot)? None of these things will be obvious to newbies who >> have never programmed before. Oh well. > >> Some things you just have to learn. > > > Yes, some things you just have to learn. Nonetheless, I strongly prefer > explicit logical operators over |, would much rather have 'equals' > instead of ==, which is stylistic in line with 'is' and explicitly > distinguishes between equality and identity comparisons. No more, or less, explicit than the difference between "==" and "is". > As for %; it is > entirely unclear to me why that obscure operation ever got its own > one-character symbol. Ill take 'mod', or even better, 'modulus' any day > of the week. Modulo is hardly an obscure operation. "What's the remainder...?" is a simple question that people learn about in primary school. And you can blame C for the use of % instead of mod or modulo. > The dot is clearly quantitatively in another realm here. 90% of typical > python code is attribute accesses. I can't imagine what sort of Python code you have seen that you consider 90% attribute access "typical". I've just run the Python tokenizer over my startup.py file, and I get these results: {'COMMENT': 24, 'DEDENT': 29, 'NL': 46, 'NAME': 256, "':'": 30, 'NEWLINE': 83, "'-'": 1, 'NUMBER': 1, "'['": 1, "','": 17, "')'": 37, "'('": 37, "'%'": 2, "'.'": 48, "'=='": 1, "'*'": 1, 'INDENT': 29, "']'": 1, "'='": 28, 'ENDMARKER': 1, 'STRING': 19} That gives attribute access being a little less than 7% of the source code. For the decimal module, the figure is a little less than 5%. > The dot is entirely unambigious and > cannot be mistaken for anything else. It reads like a book. The dot can be easily mistaken for a comma, or for a bit of grit on the monitor, especially at smaller type sizes, or for those with poor eyesight. [...] >> It is also misleading because args are not collected into a list, but >> into a tuple. > > In case you wanted a tuple youd write tuple(args), obviously. Exactly > that added flexibility is half of my case in favor. Why shouldnt it be a > list when I want it to? What sort of list? A built-in list, or whatever sort of object you get when you call the thing currently bound to the name "list"? If you can supply any function at all, what happens if I write this: def func(parg, dict(foo), list(bar)): ... How about this? def func(parg, myfunc(x)): ... What is x now? Should Python try to accumulate arguments by position, or by keyword, or try both and hope one will succeed? Which order should it try first? I believe that your proposal leads to an over-generalisation "call arbitrary functions when handling parameter lists". I don't believe you need this added complication. If you want to your var args as a list, call list(args) inside your function. >> Worse, it suggests that one should be able to generalise to something >> like this: > >> def func(parg, str(args), int(kwargs), my_func(more_args)): > >> which is incoherent. > > Sorry, but I dont get this point at all. Does ** suggests one should be > able to generalize to ***? The rules are the rules. You have missed that the generalization is not just to multiple "chunks" of arguments, but also to arbitrary functions. I thought that both ideas were equally incoherent, but ironically you suggest about that you should be able to call arbitrary functions: tuple, list, attrdict. What else? str? int? > The real questions, in my mind, are: > > 1) How useful is this added flexibility? Not insanely, but I can see it > making a lot of code significantly more clean. I don't. I see it making a small amount of code more verbose and less clean. > And: > > 2) How fundamental is collection packing/unpacking? One can easily argue > that it is indeed quite fundamental and therefore deserves its own terse > symbols, I feel. In Python, tuple unpacking and packing (actually applies to any collection, not just tuples) is *very* fundamental. That's why we can do things like this: a, b, c = my_list x, y = y, x > However, if more flexibility is indeed deemed > desirable, such terse syntax quickly gives way to a more verbose one. > Can you come up with some terse symbols that will be able to express all > of the below and dont make you wish you hadnt rather typed out the > names? > > head, tuple(tail) = iterable In Python 3, that is spelled: head, *tail = iterable tail = tuple(tail) > head, list(tail) = iterable head, *tail = iterable > head, str(tail) = somestring This is ambiguous, I'm not sure what exactly you expect to get as the string. It could arguable be any of: tail = ''.join(map(repr, tail)) tail = ''.join(map(str, tail)) tail = str(tail) or even head, tail = somestring[0], somestring[1:] > head, gene
Re: What happened to module.__file__?
On 12/12/2011 00:21, Steven D'Aprano wrote: I've just started using a Debian system, instead of the usual RedHat based systems I'm used to, and module.__file__ appears to have disappeared for some (but not all) modules. On Fedora: [steve@orac ~]$ python -E Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21) [GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import math math.__file__ '/usr/lib/python2.6/lib-dynload/mathmodule.so' and on Debian squeeze: steve@runes:~$ python -E Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. import math math.__file__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__file__' What's going on? The documentation for __file__ says: """The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.""" Interestingly, none of the versions on Windows that I've tried have that attribute for the math module. Is it platform-dependent? -- http://mail.python.org/mailman/listinfo/python-list
calling python (matplotlib) from c++
Hi all, I want to call python (matplotlib) from C++. I use ubuntu linux and compile with "-lpython2.7". Besides that, I have this line included: #include I can then do something like this: Py_Initialize(); PyRun_SimpleString("print ' '"); PyRun_SimpleString("print ' '"); PyRun_SimpleString("print ' '"); PyRun_SimpleString("print 'PYTHON RUNNING =='"); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); // Py_Main(argc, argv); // start up the python interpreter Py_Finalize(); However - I cannot seem to pass two arrays of data, so I can plot the data using matplotlib... I cannot even start matplotlib... Please help/advice/come up with suggestions, someone who knows what to do :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest. customizing tstloaders / discover()
On 12/12/2011 12:27 AM, Thomas Bach wrote: > Gelonida N writes: > >> I'd like to use regular expresions as include / exclude rules >> and I would like to have another filter function, which would check for >> the existence of certain metavariabels in test suite files > > Did you have a look at nose? I'm using it and it supports > include/exclude rules via RE and lets you select directories to run > tests from. > > I'm not sure about the meta-variable thing, but it supports plug ins > that could do the trick… > I looked at nose very briefly, but too short to form a real opinion and to understand whether nose would have any negative impact on existing unit tests. Do I loose anything if using nose. or example can all unit tests / doc tests still be run from nose? -- http://mail.python.org/mailman/listinfo/python-list
Outputting raw MIDI in realtime on Linux
I'm trying to output raw, realtime MIDI data (as in note on, note off, etc) in Linux from Python, and I want the easiest way to do it. I've been banging my head on the wall about this for quite some time. The reason for this is to reinvent the old vkeybd application, but it's just me screwing around, so not worth the time doing it in C or creating a whole whack of supporting libraries. What I have so far is vkeybd outputting to Qsynth (via an ALSA VirMidi) to pulseaudio, playing some lovely grand piano. I want to replace vkeybd with a Python program of my own design. Using Qsynth's Messages window, I can monitor the rawish MIDI signals flowing. According to http://www.tldp.org/HOWTO/MIDI-HOWTO-10.html , I should be able to just dump MIDI bytes into /dev/snd/midiC3D0. However, this yields nothing: Qsynth does not show receiving it. I even tried this C example from the OSS docs, with the same result: http://manuals.opensound.com/developer/midi.c.html (I updated the /dev line.) What do people use to output live MIDI on Linux, assuming it's possible? Thanks, Nick Irvine -- http://mail.python.org/mailman/listinfo/python-list
Re: Outputting raw MIDI in realtime on Linux
On Dec 12, 12:14 pm, Nick Irvine wrote: > What do people use to output live MIDI on Linux, assuming it's > possible? Hey Nick, I've yet to try this myself although it's long been on my to-do list. There are a couple of packages on PyPI that emit MIDI: http://pypi.python.org/pypi?%3Aaction=search&term=midi There is also an older project that provides a basic midi step sequencer. I can't find a proper package or installer, but you might find something useful in the 'midi_functions.py' file here: http://www.akjmusic.com/software/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic variable creation from string
On Dec 11, 4:42 pm, Nobody wrote: > If just you're trying to avoid getting a repetitive strain injury in your > right-hand little finger from typing all the [''], you could turn > the keys into object attributes, e.g.: > > class DictObject: > def __init__(self, d): > for key, value in d.iteritems(): > setattr(self, key, value) > ... > o = DictObject(D) > # use o.a, o.b, etc I hate this kind of laziness. I'd spend at least 5 minutes trying to work out _why_ someone felt this was necessary and then get annoyed that it was just to avoid typing. -- http://mail.python.org/mailman/listinfo/python-list
db agnostic admin for Flask?
Hi guys Are there any db agnostic admin for Flask/Django? Imagine you need CRUD lots of data from Mongodb, Redis, ini file or even remote sources, if such admin allows aggregate data regardless of DB types or syntax, it would be super useful. Anything like this exists? or should I start build one from scratch? -- http://mail.python.org/mailman/listinfo/python-list
Re: I love the decorator in Python!!!
On Dec 9, 8:08 pm, Robert Kern wrote: > On 12/9/11 5:02 AM, alex23 wrote: > > The 3rd party 'decorator' module takes care of issues like docstrings > > & function signatures. I'd really like to see some of that > > functionality in the stdlib though. > > Much of it is: > > http://docs.python.org/library/functools#functools.update_wrapper Ah, cheers :) Is that a recent addition? The lack of note makes it seem like it was there from the beginning? -- http://mail.python.org/mailman/listinfo/python-list
Working with Descriptors
Hello All, How do I get the __set__ to work here? import random class Die(object): def __init__(self, sides=6): self.sides = sides def __get__(self, instance, owner): return int(random.random() * self.sides) + 1 def __set__(self, instance, value): instance.__dict__[self.side] = value class Game(object): d6 = Die() d10 = Die(sides=10) d20 = Die(sides=20) Game.d3 = 90 (This failed) Regards, Emeka -- *Satajanus Nig. Ltd * -- http://mail.python.org/mailman/listinfo/python-list
subprocess question
Wondering if anyone could shed some light on the subprocess module? I'll admit I'm not that great at the shell. If I was wanting to get the size of the trash (on OS X), I could use: >>> os.system('du -sh ~/.Trash/') 11M/Users/jay/.Trash/ 0 Which gives me what I want. However, I've been reading that it's better to use subprocess. I did a test like so, but is this a good way to do this? >>> import subprocess >>> p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', >>> stdout=subprocess.PIPE) >>> out, err = p.communicate() >>> out ' 11M\t.\n' >>> err >>> And another question - why can't I use the tilde as a shortcut to the home directory? >>> p = subprocess.Popen(['du', '-sh'], cwd='~/.Trash/', >>> stdout=subprocess.PIPE) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 672, in __init__ errread, errwrite) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1202, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory: '~/.Trash/' Thanks for looking at my questions. Jay -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic variable creation from string
alex23 wrote: On Dec 11, 4:42 pm, Nobody wrote: If just you're trying to avoid getting a repetitive strain injury in your right-hand little finger from typing all the [''], you could turn the keys into object attributes, e.g.: class DictObject: def __init__(self, d): for key, value in d.iteritems(): setattr(self, key, value) ... o = DictObject(D) # use o.a, o.b, etc I hate this kind of laziness. I'd spend at least 5 minutes trying to work out _why_ someone felt this was necessary and then get annoyed that it was just to avoid typing. For me, half of it is to avoid the typing, the other half to avoid the reading. ;) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Working with Descriptors
On Sun, Dec 11, 2011 at 9:32 PM, Emeka wrote: > > Hello All, > > How do I get the __set__ to work here? > > import random > > class Die(object): > def __init__(self, sides=6): > self.sides = sides > > def __get__(self, instance, owner): > return int(random.random() * self.sides) + 1 > > def __set__(self, instance, value): > instance.__dict__[self.side] = value > > > > class Game(object): > d6 = Die() > d10 = Die(sides=10) > d20 = Die(sides=20) > > > Game.d3 = 90 (This failed) I'm not sure exactly what it is you're trying to do with this, but there are a couple problems. First of all, at "Game.d3 = 90" you appear to be trying to set the value of a descriptor on a class object. This doesn't work, because __set__ doesn't get called when you try to set the descriptor on the class object directly. It only reassigns the attribute and replaces the descriptor. You need to either create an instance of Game and use the descriptors on that, or put the descriptor in a metaclass. Second, you're assigning to the d3 descriptor, but you never created a descriptor for the d3 attribute. The only descriptors on the Game class are d6, d10, and d20. If you're trying to assign to the descriptor, it would need to exist first. If you're trying to add a new descriptor, you would need to do something like "Game.d3 = Die(sides=3)". -- http://mail.python.org/mailman/listinfo/python-list
Re: I love the decorator in Python!!!
On Monday, December 12, 2011 11:36:07 AM UTC+8, alex23 wrote: > On Dec 9, 8:08 pm, Robert Kern wrote: > > On 12/9/11 5:02 AM, alex23 wrote: > > > The 3rd party 'decorator' module takes care of issues like docstrings > > > & function signatures. I'd really like to see some of that > > > functionality in the stdlib though. > > > > Much of it is: > > > > http://docs.python.org/library/functools#functools.update_wrapper > > Ah, cheers :) Is that a recent addition? The lack of note makes it > seem like it was there from the beginning? To wrap a function properly is different from the 1-line lampda. This is really functional programming. Every function can be decorated to change into a different one easily. There is a method to replace every return action of a python function into an yield action without the source code. -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess question
On 12/11/2011 10:39 PM, jyoun...@kc.rr.com wrote: > And another question - why can't I use the tilde as a shortcut to the home > directory? Because subprocess doesn't use the shell (which is what expands the tilde to the invoking user's home directory). I recommend using os.path.join and os.environ anyway. p = subprocess.Popen(['du', '-sh', os.path.join(os.environ['home'], '.Trash')], stdout=subprocess.PIPE) -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 -- http://mail.python.org/mailman/listinfo/python-list
Re: tracking variable value changes
Andrea Crotti wrote: > Not sure if it's exactly pure python but Traits can actually do > thishttps://github.com/enthought/traits At an attribute level, absolutely, but not at the variable level like the OP is requesting. It's a great package, though :) -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess question
On Sun, Dec 11, 2011 at 8:39 PM, wrote: > Wondering if anyone could shed some light on the subprocess module? I'll > admit I'm not that great at the shell. > > If I was wanting to get the size of the trash (on OS X), I could use: > os.system('du -sh ~/.Trash/') > 11M /Users/jay/.Trash/ > 0 > > Which gives me what I want. However, I've been reading that it's better to > use subprocess. I did a test like so, but is this a good way to do this? > import subprocess p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', stdout=subprocess.PIPE) out, err = p.communicate() out > ' 11M\t.\n' You might prefer to use subprocess.check_output(); it slightly simplifies your code: http://docs.python.org/library/subprocess.html#subprocess.check_output > And another question - why can't I use the tilde as a shortcut to the home > directory? Because ~ is interpolated by the shell and `subprocess` does not use the shell by default for reasons that include efficiency and security. You can expand ~ yourself using os.path.expanduser(): http://docs.python.org/library/os.path.html#os.path.expanduser Alternatively, you can opt to use the shell by passing shell=True as an argument. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: I love the decorator in Python!!!
On Dec 12, 2:51 pm, 8 Dihedral wrote: > To wrap a function properly is different from the 1-line lampda. > > This is really functional programming. > > Every function can be decorated to change into a different one easily. > > There is a method to replace every return action of a python function > into an yield action without the source code. How does this have _anything_ to do with my exchange with Robert? If you're _not_ a markov chainer, you're trying way too hard to show off what you know, and very little of it seems relevant to the thread. -- http://mail.python.org/mailman/listinfo/python-list
Cannot use multiprocessing and zip together on windows
Hi All, I have a file p.zip, there is a __main__.py in it, and the content of __main__.py is: from multiprocessing import Process import os def f(): print 'in f, pid:', os.getpid() if __name__ == '__main__': print 'pid:', os.getpid() p = Process(target=f) p.start() p.join() On linux, I can get expected result for running "python p.zip" But on windows xp, I got: Traceback (most recent call last): File "", line 1, in File "C:\python27\lib\multiprocessing\forking.py", line 346, in main prepare(preparation_data) File "C:\python27\lib\multiprocessing\forking.py", line 454, in prepare assert main_name not in sys.modules, main_name AssertionError: __main__ It seems that the situation described here is similar: http://bugs.python.org/issue10128 But the patch doesn't work for me. Anybody knows how to fix this? Thanks. -- Best Regards, Leo Jay -- http://mail.python.org/mailman/listinfo/python-list
Plot all contents in a two dimension list in a loop?
Hi, say I have two lists a and b, which are both in two dimensions. I wanna to plot all curves by using pylab.plot(a[i],b[i]) in a loop for the range of the length(a). I got quite a lot of figures, but only the first one with the plot i want. how to eliminate those blank figures poping out? Rgds Huisky -- http://mail.python.org/mailman/listinfo/python-list