Keyboard Layout: Dvorak vs Colemak: is it Worthwhile to Improve the Dvorak Layout?
(a lil weekend distraction from comp lang!) in recent years, there came this Colemak layout. The guy who created it, Colemak, has a site, and aggressively market his layout. It's in linuxes distro by default, and has become somewhat popular. I remember first discovering it perhaps in 2007. Me, being a Dvorak typist since 1994, am curious on what he has to say about comparison. I recall, i was offended seeing how he paints a bias in peddling his creation. So, here, let me repaint his bias. Here it is, and judge for yourself. 〈Keyboard Layout: Dvorak vs Colemak: is it Worthwhile to Improve the Dvorak Layout?〉 http://xahlee.org/kbd/dvorak_vs_colemak.html here's a interesting excerpt: Just How Much Do You Type? Many programers all claim to type 8 or 10 hours a day. They may be sitting in front of the computer all day, but the time their fingers actually dance on keyboard is probably less than 1 hour per day. Contrast data-entry clerks. They are the real typists. Their fingers actually type, continuously, for perhaps 6 hours per day. It is important get a sense of how much you actually type. This you can do by logging you keystrokes using a software. Let's assume a pro typist sustain at 60 wpm. 60 wpm is 300 strokes per min, or 18k per hour. Suppose she works 8 hours a day, and assume just 3 hours actually typing. 18k × 3 = 54k chars per day. With this figure, you can get a sense of how many “hours” you actually type per day. I sit in front of computer on average 13 hours per day for the past several years. I program and write several blogs. My actual typing is probably double or triple of average day-job programers. From my emacs command frequency log for 6 months in 2008, it seems i only type 17k strokes per day. That's 31% of the data-entry clerk scenario above. Or, i only type ONE hour a day! I was quite surprised how low my own figure is. But thinking about it… it make sense. Even we sit in front of computer all day, but the actual typing is probably some miniscule percentage of that. Most of the time, you have to chat, lunch, run errands, browse web, read docs, run to the bathroom. Perhaps only half of your work time is active coding or writing (emails; docs). Of that duration, perhaps majority of time you are digesting the info on screen. Your whole day's typing probably can be done in less than 20 minutes if you just type continuously. If your typing doesn't come anywhere close to a data-entry clerk, then any layout “more efficient” than Dvorak is practically meaningless. Xah -- http://mail.python.org/mailman/listinfo/python-list
Re: (*args **kwargs) how do I use' em?
A good tutorial will surely help : http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/ The idea between *args and *kwargs is to create function (callables) which accepts an arbitrary number of anonymous and/or keyword arguments. It's useful when you want to create a function that will call an another one (inheritances or decorators). Hope this helps, -- Envoyé avec Sparrow (http://www.sparrowmailapp.com/?sig) Le samedi 11 juin 2011 à 07:01, TheSaint a écrit : > Hello, > I'm seldomly writng python code, nothing but a beginner code. > > I wrote these lines >> > > = > _log_in= mhandler.ConnectHandler(lmbox, _logger, accs) > multhr= sttng['multithread'] > if multhr: > _log_in= mhandler.mThreadSession(lmbox, _logger, accs) > > for svr in servrs: > nmsvr, user, pwd, ptcl = servrs[svr] > al, dn= sttng['Cfilter']; er= sttng['filter'] > try: > rx.append( _log_in.connect((nmsvr, user, pwd, ptcl, (al, dn, er > except ProtocolError: > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > if multhr: > for s in rx: > try: s.start() > except (ProtocolError, AttributeError): > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > for s in rx: > try: s.join() # waiting all threads to finish > except (ProtocolError, AttributeError): > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > > = > > Surely ugly and I believe that would be a better way to pass the arguments > as I mention on the subject. > Then it should give a dictionary of keywords and some function or a > callable. I don't know how to put down these code lines. > I think I should restructure many points of my data. > > Any suggestion will make me happier :) > > > -- > goto /dev/null > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: (*args **kwargs) how do I use' em?
On 11 juin, 07:01, TheSaint wrote: > Hello, > I'm seldomly writng python code, nothing but a beginner code. > > I wrote these lines >> > > = > _log_in= mhandler.ConnectHandler(lmbox, _logger, accs) > multhr= sttng['multithread'] > if multhr: > _log_in= mhandler.mThreadSession(lmbox, _logger, accs) > > for svr in servrs: > nmsvr, user, pwd, ptcl = servrs[svr] > al, dn= sttng['Cfilter']; er= sttng['filter'] > try: > rx.append( _log_in.connect((nmsvr, user, pwd, ptcl, (al, dn, er > except ProtocolError: > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > if multhr: > for s in rx: > try: s.start() > except (ProtocolError, AttributeError): > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > for s in rx: > try: s.join() # waiting all threads to finish > except (ProtocolError, AttributeError): > print(svr+ errors['SerProb']) > except KeyboardInterrupt: > raise SystemExit(errors['YouStop']) > > = > > Surely ugly and I believe that would be a better way to pass the arguments > as I mention on the subject. > Then it should give a dictionary of keywords and some function or a > callable. I don't know how to put down these code lines. > I think I should restructure many points of my data. > > Any suggestion will make me happier :) > > -- > goto /dev/null could you check the Alex Martelli comments here ? maybe some clarification about kwargs... http://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-python OliDa -- http://mail.python.org/mailman/listinfo/python-list
Square bracket and dot notations?
Hi all, I am beginner in Python. What is interesting for me is that Python interpreter treats in different way dot and square bracket notations. I am coming from JavaScript where both notations lead prototype chain lookup. In Python it seems square bracket and dot notations lead lookup in different "store". Simple example with dict object: d = {"key" : "value"} print d["key"] #value print d.key #AttributeError I found an implementation of dict which uses both notations for its keys lookup, which I think is stupid idea when obviously both notations lead different lookup. It will confuse me as a reader of the code. Anyway, I would like to know more about the lookup for key of dict and lookup for property of any object with dot notation. Any materials and explanations are highly appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Overcharged
I mad a call last night and never even talked to anybody, I knew I was being charged to just look and I'm ok with that amount u was charged. There was another charge though of I think 26 dollers witch I was not told or warned about at all, I need to know who I can call and talk to about this Sent from my Samsung Epic™ 4G -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
On 2011.06.11 04:41 AM, Asen Bozhilov wrote: > Hi all, > I am beginner in Python. What is interesting for me is that Python > interpreter treats in different way dot and square bracket notations. > I am coming from JavaScript where both notations lead prototype chain > lookup. > > In Python it seems square bracket and dot notations lead lookup in > different "store". > > Simple example with dict object: > > d = {"key" : "value"} > > print d["key"] #value > > print d.key #AttributeError d is this case is a dictionary object, and therefore has keys you can look up (with square brackets). The same is true with lists and tuples (which have integers as "keys"). An arbitrary object can have arbitrary values in arbitrary variables in its namespace (accessed with dots). Objects can have a __dict__ variable that stores the variables in their namespace as a dictionary (not entirely sure how this works; I'm sure someone can expand on it). With: class simpleObject(): pass a = simpleObject() This: a.key = 'value' a.otherkey = 'othervalue' I simpler than: a.props = {} a.props['key'] = 'value' a.props['otherkey'] = 'othervalue' However, if you want your object to hold several different sets of keys and respective values, dictionaries (or lists/tuples) make more sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
Asen Bozhilov writes: > I am beginner in Python. What is interesting for me is that Python > interpreter treats in different way dot and square bracket notations. > I am coming from JavaScript where both notations lead prototype chain > lookup. Run, don't walk, to the Python Tutorial. Work through each section, do the examples, experiement to get an understanding of the examples, and then continue. http://docs.python.org/tutorial/> > In Python it seems square bracket and dot notations lead lookup in > different "store". That's right. Square bracket syntax accesses an object's items, dot syntax accesses an object's attributes. > Anyway, I would like to know more about the lookup for key of dict and > lookup for property of any object with dot notation. Any materials and > explanations are highly appreciated. Work through the tutorial from beginning to end to get a good grounding in this and other fundamentals. Welcome to the language, and enjoy your learning! -- \“Most people, I think, don't even know what a rootkit is, so | `\ why should they care about it?” —Thomas Hesse, Sony BMG, 2006 | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Overcharged
Ethan writes: > I mad a call last night and never even talked to anybody, > Sent from my Samsung Epic™ 4G Your Epic 4G must not have been programmed in Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
On 11 Giu, 11:41, Asen Bozhilov wrote: > Hi all, > I am beginner in Python. What is interesting for me is that Python > interpreter treats in different way dot and square bracket notations. > I am coming from JavaScript where both notations lead prototype chain > lookup. > > In Python it seems square bracket and dot notations lead lookup in > different "store". > > Simple example with dict object: > > d = {"key" : "value"} > > print d["key"] #value > > print d.key #AttributeError > > I found an implementation of dict which uses both notations for its > keys lookup, which I think is stupid idea when obviously both > notations lead different lookup. It will confuse me as a reader of the > code. > > Anyway, I would like to know more about the lookup for key of dict and > lookup for property of any object with dot notation. Any materials and > explanations are highly appreciated. Since python is not javascript ( duh :-), [] and . notations are used for different purposes and, although they share some commonalities as I try to show later in this post, they should not be intermixed without a very good reeason ( and "it's cool" is not a good reason IMO). Broadly speaking, square brackets are used to access element in array, dict, tuples and sequences. The dot nootation is used to get the attributes and methods of instances. User classes - that is the ones you define with the class statement - can implement support for the squared bracket and dot notations: - the expression myinstance[index] is sort of translated into of myinstance.__getitem__(index) - the expression myinstance.myattribute is sort of translated of myinstance.__getattr__("myattribute") Classes also exposes a __dict__ attributes that allows to access to instance attributes and methods using dictionary semantics. That is, myistance.__dict__["myattribute"] should give the same result as myinstance.myattribute. I believe this is because in the beginning class instances actually had a dictionary storing the instance attributes. Nowadays it is more complex than that, I think, but the interface is kept to allow dynamic access to instance contents, although the reccomended way to do it this is getattr(myinstance, "myattribute"). Of course it is only useful to use __dict__ or getattr when the parameter is not a constant string but a variable referring to a string computed at run time ( this is what I mean for 'dynamic access' ). HTH. Ciao FB -- http://mail.python.org/mailman/listinfo/python-list
Re: (*args **kwargs) how do I use' em?
OliDa wrote: > maybe some clarification about kwargs... > > http://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in- python Great point. Now it's clearer :) I think I'll share the dictionary which contains the configuration loaded form a file. -- goto /dev/null -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursion error in metaclass
On Sat, 11 Jun 2011 01:33:25 -0400, Terry Reedy wrote: > On 6/10/2011 11:34 PM, Steven D'Aprano wrote: >> I have a metaclass in Python 3.1: >> >> class MC1(type): >> @staticmethod >> def get_mro(bases): >> print('get_mro called') >> return type('K', bases, {}).__mro__[1:] > > The call to type figures out the proper metaclass from bases and > forwards the call to that (or to its __new__ method). [...] > Since uou do not pass dict to get_mro. it passes {} to type and MC1 and > the test for docstring fails and the loop is broken and the empty class > is discarded after getting its mro. Thanks for the explanation. You confused me for a while talking about MC1, because that's the metaclass that *doesn't* raise an exception, but I think I see the issue now. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: uhmm... your chance to spit on me
On Jun 11, 5:36 am, Jim Burton wrote: > Xah Lee writes: > > Dear lisp comrades, it's Friday! > > The answers to your question give poor coverage of the possible > responses to your writing. I myself enjoy reading what you write, most > of the time, but become bored +1 on the 'poor coverage' -- eg I find your unicode pages useful. As to the form of your writings -- I am one of those who finds a RTFM answer less rude and more helpful than no answer (as long as a FM is also indicated). As to you as a person, I guess depression is an epidemic among computer geekers. For me the magic medicine is to see and soak in the sun in the morning. Try it for 5 days and see if your outlook on life does not sweeten up. -- http://mail.python.org/mailman/listinfo/python-list
Python Card alternatives?
Desktop apps don't seem to be the wave of the future, but they still serve a useful purpose today. They can be ideal for a quick database table management screen, or a data entry front end for a program with a bunch of parameters. It's not easy enough to build a quick utility with a GUI front end, though. Wax and PythonCard (and maybe others) tried to hit that niche, but development on both is spotty at best. Some claim that Dabo's gui builder is a good one for this purpose, and maybe it can be. Are there any other, better solutions? I've been looking at Rebol lately, and it has some points of interest. I much prefer Python as a language, but Rebol View's layout specifications are wonderfully concise, and the support code seems to be fairly straightforward as well. Has anyone tried to mimic their approach in Python? -- rzed -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
Francesco Bochicchio wrote: > User classes - that is the ones you define with the class statement - > can implement support for the squared bracket and > dot notations: > - the expression myinstance[index] is sort of translated into of > myinstance.__getitem__(index) > - the expression myinstance.myattribute is sort of translated of > myinstance.__getattr__("myattribute") It is exactly what I wanted to know. Thank you. I have not examined classes in Python yet, but when I do it I will understand some new things. One of the most interesting is, can an object inherit items trough the parent class? By items I mean items which are accessible trough square bracket notation. I really like Pythonic way here. Square bracket and dot notations allow me to create an object which can be "true" hash map and meanwhile to support independent methods from its keys. I could have an item and a property with same names and they won't interfere each other. > Classes also exposes a __dict__ attributes that allows to access to > instance attributes and methods using dictionary > semantics. That is, myistance.__dict__["myattribute"] should give the > same result as myinstance.myattribute. > I believe this is because in the beginning class instances actually > had a dictionary storing the instance attributes. > Nowadays it is more complex than that, I think, but the interface is > kept to allow dynamic access to instance contents, > although the reccomended way to do it this is getattr(myinstance, > "myattribute"). Of course it is only useful to use __dict__ > or getattr when the parameter is not a constant string but a variable > referring to a string computed at run time ( this is > what I mean for 'dynamic access' ). Yeah, I agree with that. For example in JS exactly square bracket notation has been invented to dynamic property access. The biggest question here is why do you need dynamic property access? In language as JavaScript which is strongly bounded to browser environment, you could use: function getForm(formName) { return document.forms[formName]; } Another use case is to call a method of object and kept the proper `this' value. E.g. obj.x = 10; obj.method = function () { return this.x; }; function callMethod(obj, method) { return obj[method](); } callMethod(obj, 'method'); //10 Of course it could be achieved in different ways and with dot notation of course. Thank you very much for the answer. -- http://mail.python.org/mailman/listinfo/python-list
Re: parallel computations: subprocess.Popen(...).communicate()[0] does not work with multiprocessing.Pool
Greetings, >cmd1 = "/usr/local/bin/matlab ... myMatlab.1.m" >subprocess.Popen([cmd1], shell=True, > stdout=subprocess.PIPE).communicate()[0] Try a list of arguments as the command to run. subprocess.Popen(["/usr/local/bin/matlab", ... "myMatlab.l.m"] ...) If you can switch to 2.7, you'll be to use check_output (http://docs.python.org/library/subprocess.html#subprocess.check_output) HTH -- Miki Tebeka http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Card alternatives?
As you said, desktop apps are losing appeal. I suggest looking for a web based solution. Perhaps python + silverlight? (I haven't tried it though). Unfortunately, the client-side (browser) is the domain of javascript. What I'm doing is polishing my html/css skills coupled with jquery. I have lost faith in a python solution for these tasks. Although there's something close enough that can make your experience totally different: Coffeescript. This is an enhanced syntax layer on top of javascript, inspired in python and ruby, which feels like a breath of fresh air to any python or ruby programmer. It plays very well with jquery and gives you all the pythonic goodies you are used to, like list comprehensions (called array and object comprehensions), slicing, ranges, etc. Coffeescript pre compiles your code to pure javascript so there's no performance degradation at all. If it does not convince you and you still prefer a python solution, you may want to check pyjamas (a port of GWT to python). There are also some experiments such as Skulp to have python running in the browser, although this approach implies a serious performance hit, since it's a full python implementation in javascript. regards, Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Card alternatives?
Luis, Not the OP, but thank you for passing on the CoffeeScript recommendation - looks very interesting!! http://jashkenas.github.com/coffee-script/ Regards, Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Card alternatives?
* rzed [110611 05:14]: > Desktop apps don't seem to be the wave of the future, but they still > serve a useful purpose today. They can be ideal for a quick database > table management screen, or a data entry front end for a program with > a bunch of parameters. It's not easy enough to build a quick utility > with a GUI front end, though. Wax and PythonCard (and maybe others) > tried to hit that niche, but development on both is spotty at best. > Some claim that Dabo's gui builder is a good one for this purpose, and > maybe it can be. Are there any other, better solutions? > > I've been looking at Rebol lately, and it has some points of interest. > I much prefer Python as a language, but Rebol View's layout > specifications are wonderfully concise, and the support code seems to > be fairly straightforward as well. Has anyone tried to mimic their > approach in Python? I've used rebol for over 11 years. Longer than I have used python. I've not used rebol/view however, since my meal-ticket is console and web progamming. I'm guessing that you are going to find that difficult to do, but my suggestion would be: 1)Get into one of the rebol communities - probably thru altme. 2)You will find that most rebol programmers work in other languages also, and quite a few (like me) in python. 3)You are likely to get a lot of ideas there. cheers -- Tim tim at johnsons-web dot com or akwebsoft dot com http://www.akwebsoft.com -- http://mail.python.org/mailman/listinfo/python-list
How to avoid "()" when writing a decorator accepting optional arguments?
I've written this decorator to deprecate a function and (optionally) provide a callable as replacement def deprecated(repfun=None): """A decorator which can be used to mark functions as deprecated. Optional repfun is a callable that will be called with the same args as the decorated function. """ def outer(fun): def inner(*args, **kwargs): msg = "%s is deprecated" % fun.__name__ if repfun is not None: msg += "; use %s instead" % (repfun.__name__) warnings.warn(msg, category=DeprecationWarning, stacklevel=2) if repfun is not None: return repfun(*args, **kwargs) else: return fun(*args, **kwargs) return inner return outer Now, I can use my decorator as such: @deprecated() def foo(): return 0 ...or provide an optional argument: @deprecated(some_function) def foo(): return 0 ...but I don't know how to modify it so that I can omit parentheses: @deprecated def foo(): return 0 Any hint? --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursion error in metaclass
On 6/11/2011 7:38 AM, Steven D'Aprano wrote: On Sat, 11 Jun 2011 01:33:25 -0400, Terry Reedy wrote: On 6/10/2011 11:34 PM, Steven D'Aprano wrote: I have a metaclass in Python 3.1: class MC1(type): @staticmethod def get_mro(bases): print('get_mro called') return type('K', bases, {}).__mro__[1:] The call to type figures out the proper metaclass from bases and forwards the call to that (or to its __new__ method). [...] Since uou do not pass dict to get_mro. it passes {} to type and MC1 and the test for docstring fails and the loop is broken and the empty class is discarded after getting its mro. Thanks for the explanation. You confused me for a while talking about MC1, because that's the metaclass that *doesn't* raise an exception, but Sorry, you probably changed that to MC2 for the second example and I did not notice. The point is that when either version calls get_mro and type, types calls back to the same metaclass, so that unguarding the call to get_mro results in looping. I think I see the issue now. What may not be obvious from the docs is that the metaclass calculation described in the doc section on class statements is carried out within type.__new__ (or after a possible patch, called from within that), so that type calls are really "a dynamic form of the class statement" even when another another metaclass is specified or implied. "Return a new type object." includes instances of type subclasses. I am not sure what happens with metaclasses that are not type subclasses. There is at least one bug report about the metaclass calculation, which is why I happen to have read the typeobject.__new__ code. But I have not read the build-class code and all the details of class creation. So I may have some of the details above wrong. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
On 6/11/2011 10:40 AM, Asen Bozhilov wrote: It is exactly what I wanted to know. Thank you. I have not examined classes in Python yet, but when I do it I will understand some new things. One of the most interesting is, can an object inherit items trough the parent class? By items I mean items which are accessible trough square bracket notation. .attributes are inherited. [index-or-key] items are not. I really like Pythonic way here. Square bracket and dot notations allow me to create an object which can be "true" hash map and meanwhile to support independent methods from its keys. I could have an item and a property with same names and they won't interfere each other. Right. d.items is a dict method. d['items'] is whatever you assign. Named tuples in the collections modules, which allow access to fields through .name as well as [index], have the name class problem. All the methods are therefore given leading underscore names to avoid this. [But there still could be a clash if someone used field names with leading underscores!] Python reserves and uses __xxx__ for system names just to avoid clashes. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid "()" when writing a decorator accepting optional arguments?
On Sat, Jun 11, 2011 at 1:27 PM, Giampaolo Rodolà wrote: > @deprecated() > def foo(): > return 0 This is equivalent to: foo = deprecated()(foo) > @deprecated(some_function) > def foo(): > return 0 foo = deprecated(some_function)(foo) > @deprecated > def foo(): > return 0 foo = deprecated(foo) You want to make the third case be equivalent to the first case. The problem is that there is no way to distinguish between "deprecated(foo)" (in the third case) and "deprecated(some_function)" in the second case. Both are receiving a single argument that is a function, but the latter needs to return a decorator while the former needs to return a decorated function. Since there is no way to distinguish the two cases by the arguments, you would need a separate decorator. You could do something like this: deprecated_default = deprecated() @deprecated_default def foo(): return 0 But this hardly seems worthwhile to me just to avoid typing an extra couple of parentheses. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: How to avoid "()" when writing a decorator accepting optional arguments?
On 6/11/2011 3:27 PM, Giampaolo Rodolà wrote: I've written this decorator to deprecate a function and (optionally) provide a callable as replacement def deprecated(repfun=None): """A decorator which can be used to mark functions as deprecated. Optional repfun is a callable that will be called with the same args as the decorated function. """ def outer(fun): def inner(*args, **kwargs): msg = "%s is deprecated" % fun.__name__ if repfun is not None: msg += "; use %s instead" % (repfun.__name__) warnings.warn(msg, category=DeprecationWarning, stacklevel=2) if repfun is not None: return repfun(*args, **kwargs) else: return fun(*args, **kwargs) return inner return outer Now, I can use my decorator as such: @deprecated() def foo(): return 0 ...or provide an optional argument: @deprecated(some_function) def foo(): return 0 ...but I don't know how to modify it so that I can omit parentheses: @deprecated def foo(): return 0 These are fundamentally different beasts. One makes a call to create the decorator. The other is the decorator. Write two decorators. The unparameterized version is trivial. def outer(fun): def inner(*args, **kwargs): msg = "%s is deprecated" % fun.__name__ warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return fun(*args, **kwargs) rturn inner The parameterized version will be simpler also (with None possibility deleted). -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Emacs Python indention
Hi Emacs / Python coders, moving a region of python code for more than one indention in Emacs is quite annoying, cause the python-shift-left and -right functions always loose the mark and one has to reactivate it with \C-x \C-x or guess how many indentions one want to make and do a \C-u \C-c > That were the only solutions I found on the net and well both are not very comfortable so here's a fix for that. With the following code you can use \C-c left and right to move your Python code to the left and to the right :) HF Basti (defun balle-python-shift-left () (interactive) (let (start end bds) (if (and transient-mark-mode mark-active) (setq start (region-beginning) end (region-end)) (progn (setq bds (bounds-of-thing-at-point 'line)) (setq start (car bds) end (cdr bds (python-shift-left start end)) (setq deactivate-mark nil) ) (defun balle-python-shift-right () (interactive) (let (start end bds) (if (and transient-mark-mode mark-active) (setq start (region-beginning) end (region-end)) (progn (setq bds (bounds-of-thing-at-point 'line)) (setq start (car bds) end (cdr bds (python-shift-right start end)) (setq deactivate-mark nil) ) (add-hook 'python-mode-hook (lambda () (define-key python-mode-map (kbd "C-c ") 'balle-python-shift-right) (define-key python-mode-map (kbd "C-c ") 'balle-python-shift-left) ) ) signature.asc Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Square bracket and dot notations?
Terry Reedy wrote: > Right. d.items is a dict method. d['items'] is whatever you assign. > Named tuples in the collections modules, which allow access to fields > through .name as well as [index], have the name class problem. All the > methods are therefore given leading underscore names to avoid this. [But > there still could be a clash if someone used field names with leading > underscores!] Scripting languages as JavaScript, Python and other so dynamic languages allow user to shoot in his feet. I think the developer should learning the curves of the language before start writing complex applications. That was the goal of this thread. -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursion error in metaclass
On Sat, Jun 11, 2011 at 21:39, Terry Reedy wrote: > What may not be obvious from the docs is that the metaclass calculation > described in the doc section on class statements is carried out within > type.__new__ (or after a possible patch, called from within that), so that > type calls are really "a dynamic form of the class statement" even when > another another metaclass is specified or implied. "Return a new type > object." includes instances of type subclasses. I am not sure what happens > with metaclasses that are not type subclasses. There is at least one bug > report about the metaclass calculation, which is why I happen to have read > the typeobject.__new__ code. But I have not read the build-class code and > all the details of class creation. So I may have some of the details above > wrong. Just for the record, I think this is the mentioned bug: http://bugs.python.org/issue1294232 Daniel -- http://mail.python.org/mailman/listinfo/python-list
__dict__ is neato torpedo!
I'm pretty happy that I can copy variables and their value from one object's namespace to another object's namespace with the same variable names automatically: class simpleObject(): pass a = simpleObject() b = simpleObject() a.val1 = 1 a.val2 = 2 b.__dict__.update(a.__dict__) a.val1 = 'a' >>> a.val1 'a' >>> a.val2 2 >>> b.val1 1 >>> b.val2 2 The reason I'm posting this is to ask what to watch out for when doing this. I've seen vague warnings that I don't really understand, and I'm hoping someone can enlighten me. -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On 6/11/2011 9:32 PM, Andrew Berg wrote: I'm pretty happy that I can copy variables and their value from one You are copying names and their associations, but not the objects or thier values. object's namespace to another object's namespace with the same variable names automatically: class simpleObject(): pass a = simpleObject() b = simpleObject() a.val1 = 1 a.val2 = 2 b.__dict__.update(a.__dict__) a.val1 = 'a' a.val1 'a' a.val2 2 b.val1 1 b.val2 2 -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On Sat, 11 Jun 2011 20:32:37 -0500, Andrew Berg wrote: > I'm pretty happy that I can copy variables and their value from one > object's namespace to another object's namespace with the same variable > names automatically: > > class simpleObject(): > pass > > a = simpleObject() > b = simpleObject() > > a.val1 = 1 > a.val2 = 2 > b.__dict__.update(a.__dict__) [...] > The reason I'm posting this is to ask what to watch out for when doing > this. I've seen vague warnings that I don't really understand, and I'm > hoping someone can enlighten me. You are injecting data and code from one object to another. If you don't know what you're injecting, bad things could happen. Just like in real life :) The update method unconditionally replaces any item in the first object that matches an item in the second. If it has things you don't want, too bad, you'll get them: >>> class K(object): ... data = "things" ... status = "working hard for a living" ... >>> a = K() >>> b = K() >>> b.data = "stuff and things" # what you want >>> b.status = "leaching off dear old granny" # but not this one >>> >>> a.__dict__.update(b.__dict__) >>> print(a.status) leaching off dear old granny So never update from a random object you don't know well. A second, more subtle risk: not all objects have a __dict__. But if you obey the rule about never updating from arbitrary objects you don't know, then you won't be surprised by an object with no __dict__. Other than that, using update is a good trick to have in your toolbox. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On 2011.06.11 09:12 PM, Terry Reedy wrote: > On 6/11/2011 9:32 PM, Andrew Berg wrote: > > I'm pretty happy that I can copy variables and their value from one > > You are copying names and their associations, but not the objects or > thier values. Associations? The update() method copies the values; a.val1 and b.val1 point to two different places in memory. -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On 2011.06.11 09:13 PM, Steven D'Aprano wrote: > So never update from a random object you don't know well. Of course. In the project I'm working on, this will be used in the __init__() method of a class that accepts a pair of dictionaries or possibly **kwargs (for flexibility and to avoid the very problem of an object without a __dict__). > A second, more subtle risk: not all objects have a __dict__. But if you > obey the rule about never updating from arbitrary objects you don't know, > then you won't be surprised by an object with no __dict__. What objects don't (other than the obvious ones like strings, dictionaries, ints and lists)? -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On Sat, Jun 11, 2011 at 8:21 PM, Andrew Berg wrote: > On 2011.06.11 09:12 PM, Terry Reedy wrote: >> On 6/11/2011 9:32 PM, Andrew Berg wrote: >> > I'm pretty happy that I can copy variables and their value from one >> >> You are copying names and their associations, but not the objects or >> thier values. > Associations? The update() method copies the values; a.val1 and b.val1 > point to two different places in memory. Incorrect. The names in b will be bound to the same objects as the names in a, not to copies of them. For immutable objects such as ints, this doesn't matter. For mutable objects such as lists, it can: >>> class X(object): ... pass ... >>> a = X() >>> b = X() >>> a.foo = ['apples'] >>> b.__dict__.update(a.__dict__) >>> a.foo ['apples'] >>> b.foo ['apples'] >>> a.foo.append('oranges') >>> a.foo ['apples', 'oranges'] >>> b.foo ['apples', 'oranges'] Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On 2011.06.11 10:08 PM, Ian Kelly wrote: > For immutable objects such as > ints, this doesn't matter. For mutable objects such as lists, it can: Well, that's confusing. How would I make actual copies? -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
Andrew Berg writes: > On 2011.06.11 10:08 PM, Ian Kelly wrote: > > For immutable objects such as ints, this doesn't matter. For mutable > > objects such as lists, it can: > Well, that's confusing. It's exactly the same as with an ordinary assignment (‘a = b’) in Python. You will likely want to work through the Python Tutorial http://docs.python.org/tutorial/> and experiment with the samples as you go, in order to ground the Python data model in your mind. > How would I make actual copies? At what level? You can create a new dict or a new list by feeding the esiting one to the constructor for the type. Or you can use the various methods in the ‘copy’ module depending on what you want. Be aware, though, that most Python code gets by just fine without explicitly making copies, and I hardly ever see the ‘copy’ module actually used. Work through the tutorial, understand the data model, and work with it to get better results. -- \ “Give a man a fish, and you'll feed him for a day; give him a | `\religion, and he'll starve to death while praying for a fish.” | _o__) —Anonymous | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
which threading libraries to use?
Hi, Are there any reasons besides personal preference to use one particular threading library over the other? Eventlet, Twisted, and Python's native Threading class, or are there even others? Are there any licensing or redistribution restrictions that I should be worried about? Which ones do you consider best documented? Most thread-safe? Efficient? Ultimately this will be used for asynchronous SNMP, HTTP, and WMI. I don't think this will need to evolve into a multi-process project, unless of course that is much easier to do than multi-threading? Thanks, Dennis O. -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On 2011.06.11 10:40 PM, Ben Finney wrote: > It's exactly the same as with an ordinary assignment (‘a = b’) in > Python. Fair enough. > > How would I make actual copies? > At what level? Level? I just want to be able to create an object b with values from dictionary a, and not have changes to a reflect b and vice-versa once b is created. > You can create a new dict or a new list by feeding the > esiting one to the constructor for the type. Not sure what you mean here. I thought you meant it copies a dictionary when used as input in an __init__() method, but I tried that in the interpreter and a still affects b: >>> class testObj(): ... def __init__(self,input): ... self.__dict__.update(input) ... >>> a = dict(list=['one', 'two'], str='hello') >>> b = testObj(a) >>> a['list'].append('three') >>> a {'list': ['one', 'two', 'three'], 'str': 'hello'} >>> b.list ['one', 'two', 'three'] > Or you can use the various > methods in the ‘copy’ module depending on what you want. copy.deepcopy() looks appealing, but I don't know what the docs mean by "administrative data structures". > Be aware, though, that most Python code gets by just fine without > explicitly making copies, and I hardly ever see the ‘copy’ module > actually used. Now that I think about it, I could probably restrict myself to immutable types inside the dictionary without much problem. Was that your point, or did you mean something else? -- http://mail.python.org/mailman/listinfo/python-list
Re: which threading libraries to use?
On Sun, Jun 12, 2011 at 2:10 PM, Dennis wrote: > Hi, > > Are there any reasons besides personal preference to use one > particular threading library over the other? Eventlet, Twisted, and > Python's native Threading class, or are there even others? Are there > any licensing or redistribution restrictions that I should be worried > about? Which ones do you consider best documented? Most thread-safe? > Efficient? I use the native Threading class, myself, largely because it's so easy to switch to multiprocessing if the GIL starts to get in the way. YMMV if you don't use CPython. > Ultimately this will be used for asynchronous SNMP, HTTP, and WMI. I > don't think this will need to evolve into a multi-process project, > unless of course that is much easier to do than multi-threading? In all probability, your threads will spend 99% of their time waiting for the network. This makes threads very effective, and largely eliminates the GIL issues (if they occasionally have to take turns, it's not going to affect things much). Pick whichever threading library suits your coding style; they'll all work, most likely. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: __dict__ is neato torpedo!
On Sat, Jun 11, 2011 at 10:32 PM, Andrew Berg wrote: > On 2011.06.11 10:40 PM, Ben Finney wrote: >> It's exactly the same as with an ordinary assignment (‘a = b’) in >> Python. > Fair enough. >> > How would I make actual copies? >> At what level? > Level? I just want to be able to create an object b with values from > dictionary a, and not have changes to a reflect b and vice-versa once b > is created. It sounds like the copy.deepcopy function is what you want: >>> from copy import deepcopy >>> class X(object): pass ... >>> a = X() >>> a.fruit = ['apples'] >>> b = deepcopy(a) >>> a.fruit ['apples'] >>> b.fruit ['apples'] >>> a.fruit.append('oranges') >>> a.fruit ['apples', 'oranges'] >>> b.fruit ['apples'] >> Or you can use the various >> methods in the ‘copy’ module depending on what you want. > copy.deepcopy() looks appealing, but I don't know what the docs mean by > "administrative data structures". It just means that you don't always want absolutely everything copied. For example: >>> class World(object): pass ... >>> class Actor(object): ... def __init__(self, world): ... self.world = world ... >>> class Action(object): ... def __init__(self, actor): ... self.actor = actor ... >>> a = Action(Actor(World())) >>> b = deepcopy(a) >>> a.actor is b.actor False >>> a.actor.world is b.actor.world False The intention here is probably that a and b should both be part of the same World, but as you can see that is not the case; the World got copied along with everything else. Python provides machinery to let you avoid deep copying absolutely everything, but it's important to be aware of cases like this. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list