Re: Recursion error in metaclass
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). See Objects/typeobject.c in the source, or read the docs on metaclasses carefully. If the proper metaclass is MC1, ... def __new__(cls, name, bases, dict): mro = None docstring = dict.get('__doc__') if docstring == 'ham': mro = cls.get_mro(bases) and you unconditionally call get_mro again, to call this again... dict['__doc__'] = "spam spam spam" # Create the class we want, and return it. K = super().__new__(cls, name, bases, dict) if mro: assert K.__mro__ == (K,) + mro return K you are in an endless loop. 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. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: i want to learn pyqt ,but i have no c++ knowlage. is it ok????
2011/6/10 可乐 : > On 6月11日, 下午12时03分, Javier wrote: >> ?? wrote: >> > i want to learn pyqt ,but i have no c++ knowlage. is it ok >> >> It should be ok. I would recoomend this book: >> >> "Rapid GUI Programming with Python and Qt" (Prentice Hall Open Source >> Software >> Development) >> Mark Summerfield (Author) > thanks a lot ,i have got a e-book which is you recomended. So I don't know anyone Mandarin/Cantonese resources so these are all in English. Google has some great Python courses on Youtube and also UW has a Python series: http://www.google.com/search?q=youtube+google+python&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a http://www.cs.washington.edu/education/courses/cse142/10au/python.shtml The python docs you will undoubtedly run into as well. This was posted to the list recently too in case you missed it: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html I'm sure everyone else has their own list of links. Thanks, Dennis O. -- http://mail.python.org/mailman/listinfo/python-list
(*args **kwargs) how do I use' em?
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
Re: i want to learn pyqt ,but i have no c++ knowlage. is it ok????
On 6月11日, 下午12时03分, Javier wrote: > ?? wrote: > > i want to learn pyqt ,but i have no c++ knowlage. is it ok > > It should be ok. I would recoomend this book: > > "Rapid GUI Programming with Python and Qt" (Prentice Hall Open Source Software > Development) > Mark Summerfield (Author) thanks a lot ,i have got a e-book which is you recomended. -- http://mail.python.org/mailman/listinfo/python-list
Re: i want to learn pyqt ,but i have no c++ knowlage. is it ok????
?? wrote: > i want to learn pyqt ,but i have no c++ knowlage. is it ok It should be ok. I would recoomend this book: "Rapid GUI Programming with Python and Qt" (Prentice Hall Open Source Software Development) Mark Summerfield (Author) -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
Íàì, ãîâîðèò, î÷åíü ïðèÿòíî, è íàì íóæíû îáðàçîâàííûå Îíè íå ïðîñ÷èòàþò Âû, ãîâîðèò, òîæå, êàæåòñÿ, ïî êîììåð÷åñêîé ÷àñòè? http://rayjonz8231.de.tl/esp1006nimfia.htm -- http://mail.python.org/mailman/listinfo/python-list
Recursion error in metaclass
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:] def __new__(cls, name, bases, dict): mro = None docstring = dict.get('__doc__') if docstring == 'ham': mro = cls.get_mro(bases) dict['__doc__'] = "spam spam spam" # Create the class we want, and return it. K = super().__new__(cls, name, bases, dict) if mro: assert K.__mro__ == (K,) + mro return K It seems to work fine: >>> class A(metaclass=MC1): ... pass ... >>> class B(A): ... 'ham' ... get_mro called >>> assert B.__doc__ == 'spam spam spam' >>> But if I move the call to get_mro outside of the if block, it works fine at first, and then blows up with RecursionError: class MC2(type): @staticmethod def get_mro(bases): print('get_mro called') return type('K', bases, {}).__mro__[1:] def __new__(cls, name, bases, dict): mro = None docstring = dict.get('__doc__') mro = cls.get_mro(bases) if docstring == 'ham': dict['__doc__'] = "spam spam spam" # Create the class we want, and return it. K = super().__new__(cls, name, bases, dict) if mro: assert K.__mro__ == (K,) + mro return K >>> class C(metaclass=MC2): ... pass ... get_mro called >>> >>> sys.setrecursionlimit(15) >>> class D(C): ... 'ham' ... get_mro called get_mro called get_mro called Traceback (most recent call last): File "", line 1, in File "", line 9, in __new__ File "", line 5, in get_mro File "", line 9, in __new__ File "", line 5, in get_mro File "", line 9, in __new__ File "", line 4, in get_mro RuntimeError: maximum recursion depth exceeded while calling a Python object I am utterly perplexed. What's going on here? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
i want to learn pyqt ,but i have no c++ knowlage. is it ok????
i want to learn pyqt ,but i have no c++ knowlage. is it ok -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, 10 Jun 2011 14:46:06 -0700, Carl Banks wrote: > On Friday, June 10, 2011 2:51:20 AM UTC-7, Steven D'Aprano wrote: >> On Thu, 09 Jun 2011 20:36:53 -0700, Carl Banks wrote: >> > Put it this way: if Python doesn't automatically inherit docstrings, >> > the worst that can happen is missing information. If Python does >> > inherit docstrings, it can lead to incorrect information. >> >> This is no different from inheriting any other attribute. If your class >> inherits "attribute", you might get an invalid value unless you take >> steps to ensure it is a valid value. This failure mode doesn't cause us >> to prohibit inheritance of attributes. > > Ridiculous. The docstring is an attribute of the function, not the > class, which makes it very different from any other attribute. I don't know about you, but I'm talking about inheritance of both class and method docstrings. > Consider this: > > > class A(object): > foo = SomeClass() > > > class B(A): > foo = SomeOtherUnrelatedClass() > > > Would you have B.foo "inherit" all the attributes of A.foo that it > doesn't define itself? If A.foo and B.foo are *unrelated*, they probably don't belong in *related* classes. But putting that aside, if they truly are unrelated, then no, of course you wouldn't inherit attributes of A.foo in B.foo, including the docstring. That would be a stupid thing to do. But why do you assume they are unrelated? Nobody is suggesting that (say) str.len should inherit its doc string from dict.update. That would be ridiculous, but not as ridiculous as assuming that's what we want to happen! If the classes, or methods, are related, chances are good that the docstrings need to be related too. Possibly even identical. If they need to be identical, then this proposal gives a way of enforcing that identity without needing to keep two docstrings in sync manually. Carl, I'm not exactly sure what your opposition is about here. Others have already given real-world use cases for where inheriting docstrings would be useful and valuable. Do you think that they are wrong? If so, you should explain why their use-case is invalid and what solution they should use. If you fear that such docstring inheritance will become the default, leading to a flood of inappropriate documentation, then I think we all agree that this would be a bad thing. But we can already "inherit" docstrings, in a manner of speaking, via an explicit name binding step, and that hasn't lead to inappropriate documentation: def blarg1(*args): """Blarg the input and return a wibble.""" # implementation #1 def blarg2(*args): # implementation #2 blag2.__doc__ = blag1.__doc__ # or perhaps blag1.__doc__.replace("wibble", "frob") When you need to keep the docstrings of blag1 and blag2 in sync, it may be better to "inherit" them rather than keep two independent strings that need to be manually edited in sync. functools.wraps() already does this. This proposal merely extends that same idea to classes and methods via inheritance instead of explicit name binding. Provided that such "inheritance" requires a deliberate choice by the caller (a decorator, a metaclass, some other syntax), where's the harm? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported operand type(s) for +: 'float' and 'tuple'
On 6/10/2011 6:30 AM, Francesc Segura wrote: Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG<= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I'm working with networkx and my program is this one: [snip about 100 lines] Before posting code that does not work, it is a good idea to reduce to to some minimum needed to exhibit the problem. If you had done that, you may well have found the answer. In this specific case, you should have searched for all lines making assignments to the names causing a problem. This is easier to do by eye with a minimal example. Or, use a search function for 'T0 =' (or 'T0=' if needed, but it is not) with Find Next and the second hit is the offending line ("T0 = initCost*0,1"). -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt
On 6/10/2011 3:15 PM, KK wrote: Thanks for the reply!! i ve installed the binary but when i import anything of PyQt in my prog it says error?? i think there is some problem with folders If you install in python32/Lib/site-packages, it should work. But see Andrew's message. Show both actual import statement and resulting traceback and error. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: best book about Webdesign with Django
I found that Head First Python gives a really good introduction to Django. It's definitely a beginners book, as are all of the Head First books, but it still teaches the basics in a very good manner. If you're very knowledgeable with Python, you can skip the first few chapters (or read through them as a refresher), and eventually you'll get to some chapters where you do some web design with Django. It doesn't go REALLY into depth here, but you have to start somewhere, right? I hope that this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: __doc__ immutable for classes
On 6/10/2011 3:31 AM, Gregory Ewing wrote: Eric Snow wrote: But for "method" objects (really a wrapper for bound functions) would it change the __doc__ of the wrapper or of the bound function? You probably wouldn't want to change the __doc__ of a method wrapper; instead you'd make sure you got hold of the underlying function first. So __doc__ on method wrappers should probably remain read-only to avoid surprises. In 3.x there are no general method wrappers; only bound methods. The .__doc__ attribute of bound methods equals and I am very sure *is* the doc string of the underlying function, accessed through a custom method.__getattr__. It is not writable through the bound method. I presume this is because method.__setattr__ blocks the write. Directly binding a new string to the underlying function does work. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported operand type(s) for +: 'float' and 'tuple'
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura escribió: Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG <= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I see Tim Chase already told you about this error. Let me make a few comments about the rest. try: import matplotlib.pyplot as plt except: raise I guess the above try/except was left from some earlier debugging attempt - such an except clause is useless, just omit it. T0 = 0.5 RO = 0.99 Perhaps those names make sense in your problem at hand, but usually I try to use more meaningful ones. 0 and O look very similar in some fonts. for i in range(len(edges)): total = 0 cost = 0 factor = 1 liedges = list(edges[i]) linode1 = list(liedges[0]) linode2 = list(liedges[1]) list(something) creates a new list out of the elements from `something`. You're just iterating here, so there is no need to duplicate those lists. In addition, Python is not C: the `for` statement iterates over a collection, you don't have to iterate over the indices and dereference each item: for liedges in edges: linode1 = liedges[0] linode2 = liedges[1] distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]- linode1[1])%N)^2) That doesn't evaluate what you think it does. ^ is the "bitwise xor" operator, and I bet you want **, the "power" operator. total = total + cost return(total) return is not a function but a statement; those () are unnecesary and confusing. And I think you want to initialize total=0 *before* entering the loop; also, initializing cost and factor is unnecesary. def costGeasy(G): bc = NX.edge_betweenness_centrality(G,normalized=True) total = 0 for i in range(len(bc)): total=total+bc.values()[i] return (total) bc = NX.edge_betweenness_centrality(G,normalized=True) values = bc.values() total = sum(values) return total ==> return sum(bc.values()) pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed in the 3.x version. If you put this line at the top of your script: from __future__ import division then 1/3 returns 0.... When you actually want integer division, use //, like 1//3 So we can rewrite the above as: from __future__ import division ... for node in nod: pos[node] = (node[0] / N, node[1] / N) Another way, not relying on true division: divisor = float(N) for node in nod: pos[node] = (node[0] / divisor, node[1] / divisor) or even: pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod) for y in range(NK): for x in range(ITERATIONS): cost = costG(G) if (cost < (best_cost)): best_graph = G best_cost = cost GG = G Again, I think this doesn't do what you think it does. GG = G means "let's use the name GG for the object currently known as G". GG is not a "copy" of G, just a different name for the very same object. Later operations like GG.remove_edge(...) modify the object - and you'll see the changes in G, and in best_graph, because those names all refer to the same object. I think you'll benefit from reading this: http://effbot.org/zone/python-objects.htm a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=G.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) As above, I'd avoid using indexes, take two random nodes using random.sample instead, and avoid adjacency_list(): while True: a, b = random.sample(nod, 2) if b not in G[a]: break GG.add_edge(a, b) (mmm, I'm unsure of the adjacency test, I've used networkx some time ago but I don't have it available right now) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported operand type(s) for +: 'float' and 'tuple'
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura escribió: Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG <= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I see Tim Chase already told you about this error. Let me make a few comments about the rest. try: import matplotlib.pyplot as plt except: raise I guess the above try/except was left from some earlier debugging attempt - such an except clause is useless, just omit it. T0 = 0.5 RO = 0.99 Perhaps those names make sense in your problem at hand, but usually I try to use more meaningful ones. 0 and O look very similar in some fonts. for i in range(len(edges)): total = 0 cost = 0 factor = 1 liedges = list(edges[i]) linode1 = list(liedges[0]) linode2 = list(liedges[1]) list(something) creates a new list out of the elements from `something`. You're just iterating here, so there is no need to duplicate those lists. In addition, Python is not C: the `for` statement iterates over a collection, you don't have to iterate over the indices and dereference each item: for liedges in edges: linode1 = liedges[0] linode2 = liedges[1] distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]- linode1[1])%N)^2) That doesn't evaluate what you think it does. ^ is the "bitwise xor" operator, and I bet you want **, the "power" operator. total = total + cost return(total) return is not a function but a statement; those () are unnecesary and confusing. And I think you want to initialize total=0 *before* entering the loop; also, initializing cost and factor is unnecesary. def costGeasy(G): bc = NX.edge_betweenness_centrality(G,normalized=True) total = 0 for i in range(len(bc)): total=total+bc.values()[i] return (total) bc = NX.edge_betweenness_centrality(G,normalized=True) values = bc.values() total = sum(values) return total ==> return sum(bc.values()) pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed in the 3.x version. If you put this line at the top of your script: from __future__ import division then 1/3 returns 0.... When you actually want integer division, use //, like 1//3 So we can rewrite the above as: from __future__ import division ... for node in nod: pos[node] = (node[0] / N, node[1] / N) Another way, not relying on true division: divisor = float(N) for node in nod: pos[node] = (node[0] / divisor, node[1] / divisor) or even: pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod) for y in range(NK): for x in range(ITERATIONS): cost = costG(G) if (cost < (best_cost)): best_graph = G best_cost = cost GG = G Again, I think this doesn't do what you think it does. GG = G means "let's use the name GG for the object currently known as G". GG is not a "copy" of G, just a different name for the very same object. Later operations like GG.remove_edge(...) modify the object - and you'll see the changes in G, and in best_graph, because those names all refer to the same object. I think you'll benefit from reading this: http://effbot.org/zone/python-objects.htm a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=G.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) As above, I'd avoid using indexes, take two random nodes using random.sample instead, and avoid adjacency_list(): while True: a, b = random.sample(nod, 2) if b not in G[a]: break GG.add_edge(a, b) (mmm, I'm unsure of the adjacency test, I've used networkx some time ago but I don't have it available right now) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: uhmm... your chance to spit on me
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 and fed up with the way you sometimes seem unaccountably angry with the rest of the world or with some imaginary group within it, the "tech fuck geekers" or whatever it is. So I represent an option that you missed out :-) Anyway, keep it up. Jim > Dear Xah, your writing is: > > • Full of bad grammar. River of Hiccups. > > • Stilted. Chocked under useless structure and logic. > > • WRONG — Filled with uncouth advices. > > • Needlessly insulting. You have problems. > > • Simply stinks. Worthless. > > • Mediocre. Just like everybody, admit it. > > • I love it. > > • Your writing is pro! > > • you are genius! one of the great expositor, eassyist. > > • Dude, you are full of shit. I've not seen a crank quite like > you. > > Vote at: http://xahlee.blogspot.com/2011/06/xahs-writing-is.html. > > Xah > (i code python small time too) -- J Burton j...@sdf-eu.org -- http://mail.python.org/mailman/listinfo/python-list
Re: best book about Webdesign with Django
Hi Thomas, APologies for not being clear enough in my question. On 06/09/2011 04:40 PM, Thomas Guettler wrote: > On 08.06.2011 12:29, News123 wrote: >> Hi, >> >> >> Do you have any recommendations for a good book about Web design with >> Django? > > You can do web design with HTML, CSS and Javascript. There are a lot > of books about this. I'm having some basic knowlege about web html / css javascript cgi, wsgi , mysql php /perj / python, javascript Now I would like to learn a little more about web frame works and existing libraries to help me manager slightly bigger pojects, which require - session mamagement - i18n So after some first experiments Django looks rather intersting with its templating, data models and so on. However I'd like to know whether there is a good book ( cook book style or a book explaining Django by an example project) about Django. The online documentation and Goolge is not bad, but sometimes it's rather time consuming to find some tricks / ideas and I don't want to bother this group with all the questions which po up over time. to give some examples of questions which show up - how to set the language (i18n) on a user basis (I'd like to save user preferences and make sure, that the page is served in the language, that I (not the user's browser preference) choose. - how to best serve static contents with authenification (it seems xsendfile is the answer) - how to handle browsing huge database tables with a few thousand entries. The default admin page provides pulldown lists for choosing entries, which is no more practical if my tables grow too big, so I would be interested how to implement a system with slow response times, where the user starts typing a name list of matching entries is filtered while typing - how to best do i18n for text stored in java scripts. - examples of combining django and jquery - how to impement django applications, which need to run some time consuming tasks on the server ( mod_wsgi aemon mode? threading? multiprocessing? ) and 'notify' ( js polling? ) the web user when the task is done. - Anythng wrong with osing the django data model for non web applications. - time example projects explainign session management - how to disconnect a user after a certain time of inactivity I hope I clarified a little what I am interested in. SO is there nybody who can recommend a good book (or good books) about django? > > Django is a good web framework. It does not care much about CSS and > Javascript. > > I guess you need buy two books :-) In fact I need tons of books. Still so many things to learn. > Thomas > > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, Jun 9, 2011 at 12:22 AM, Eric Snow wrote: > Sometimes when using class inheritance, I want the overriding methods > of the subclass to get the docstring of the matching method in the > base class. You can do this with decorators (after the class > definition), with class decorators, and with metaclasses [1]. > > However, I was hoping for a way to do it with just function decorators > on the methods (no metaclass or class decorator). I am not sure if > this is doable. I realize now that this is exactly the reason I got > to thinking last week about objects being notified when they are bound > [2]. > > So, is there a way to do this with just decorators, or am I "stuck" > with the metaclass/class decorator route? (It's not all that bad :) > Thanks for all the feedback on this thread everyone! I found a solution that works pretty well, using descriptors: class DocFunc: TRIGGER = None def __init__(self, f): self.f = f def __get__(self, obj, cls): doc = self.f.__doc__ if doc == self.TRIGGER: doc = self.get_doc(cls, self.f.__name__, self.TRIGGER) self.f.__doc__ = doc setattr(cls, self.f.__name__, self.f) return self.f @staticmethod def get_doc(cls, fname, default=TRIGGER, member=True): bases = cls.__mro__[:] if member: bases = bases[1:] for base in bases: func = getattr(base, fname, None) if not func: continue doc = getattr(func, '__doc__', default) if doc == default: continue return doc return default @staticmethod def inherits_docstring(f, context=None, fname=None, default=TRIGGER): if context is not None: cls, namespace = context fname = fname or f.__name__ f.__doc__ = DocFunc.get_doc(cls, fname, default, False) return f return DocFunc(f) class X: def something(self): """some method""" class Y(X): @DocFunc.inherits_docstring def something(self): ... This approach does not update the docstring if it changes in the base class, but I don't need that for what I am doing. If you want to trigger on an empty string, instead of None, just change the TRIGGER. -eric > Thanks! > > -eric > > > p.s. Am I missing something or can you really not change the docstring > of a class? I was thinking about the idea of inheriting class > docstrings too. > > > [1] > http://code.activestate.com/recipes/577743-using-decorators-to-inherit-function-docstrings/ > [2] http://mail.python.org/pipermail/python-ideas/2011-June/010446.html > -- http://mail.python.org/mailman/listinfo/python-list
Re: ContextDecorator via contextmanager: broken?
On Fri, Jun 10, 2011 at 4:57 PM, Ian Kelly wrote: > So as far as I can tell, generator-based context managers simply can't > be used as ContextDecorators. Furthermore, the documentation's claim > that they can is actually harmful, since they *appear* to work at > first. Or am I simply missing something here? Please ignore my previous post. Looks like this has already been fixed for Python 3.2.1 and 3.3. http://bugs.python.org/issue11647 -- http://mail.python.org/mailman/listinfo/python-list
ContextDecorator via contextmanager: broken?
Python 3.2 has this lovely new contextlib.ContextDecorator mixin [1] for context manager classes that allows you to apply the context manager as a decorator. The docs for this feature include the note: ContextDecorator is used by contextmanager(), so you get this functionality automatically. Sweet! So I tried this out: >>> @contextmanager ... def print_stuff(): ... print('Starting') ... try: ... yield 'Yielded' ... finally: ... print('Exiting') ... >>> @print_stuff() ... def test(): ... print('The bit in the middle') ... >>> test() Starting The bit in the middle Exiting So far so good. There seems to be no straight-forward way for the function to get access to the 'Yielded' value, but I suppose I can live with that. But then I tried calling the function again: >>> test() Traceback (most recent call last): File "c:\python32\lib\contextlib.py", line 28, in __enter__ return next(self.gen) StopIteration During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "c:\python32\lib\contextlib.py", line 15, in inner with self: File "c:\python32\lib\contextlib.py", line 30, in __enter__ raise RuntimeError("generator didn't yield") RuntimeError: generator didn't yield Whoops! The problem is that the same generator instance is used for both function calls, and since the first call has already exhausted the generator, the second call just fizzles. Now, you might think that this can be salvaged by looping inside the generator. But that doesn't work either: >>> @contextmanager ... def print_stuff(): ... while True: ... print('Starting') ... try: ... yield ... finally: ... print('Exiting') ... >>> @print_stuff() ... def test(): ... print('The bit in the middle') ... >>> test() Starting The bit in the middle Exiting Starting Traceback (most recent call last): File "", line 1, in File "c:\python32\lib\contextlib.py", line 16, in inner return func(*args, **kwds) File "c:\python32\lib\contextlib.py", line 39, in __exit__ raise RuntimeError("generator didn't stop") RuntimeError: generator didn't stop So as far as I can tell, generator-based context managers simply can't be used as ContextDecorators. Furthermore, the documentation's claim that they can is actually harmful, since they *appear* to work at first. Or am I simply missing something here? Cheers, Ian [1] http://docs.python.org/py3k/library/contextlib.html#contextlib.ContextDecorator -- http://mail.python.org/mailman/listinfo/python-list
Re: Function declarations ?
Andre Majorel wrote: > Is there a way to keep the definitions of the high-level > functions at the top of the source ? I don't see a way to > declare a function in Python. I am not a Python developer, but Pythonic way of definition not declaration is definitely interesting. Languages with variable and function declarations usually use hoisted environment. JavaScript is the perfect example. Hoisted environment allows you to use call expression before the physical declaration of the function in the source text. e.g. foo(); function foo() {} This code does not throw ReferenceError or TypeError in JavaScript. It calls `foo' exactly because it is used a hoisted environment. More precisely on entering in some context global or function JS engine define all function declarations as local scoped variables. While this has its advantages, it has a really big drawback. It cannot support default arguments which are bound to local variables. x = 10 def f(y = x): print y f() #10 This in hoisted environment cannot be implemented, because assignment is evaluating during the execution of the code, not on entering in specific context. So the interpreter is not able to predict the value for y here. Hope this helps, why Python use definitions instead of declarations. -- http://mail.python.org/mailman/listinfo/python-list
Re: help on QUICKFIX
En Fri, 10 Jun 2011 04:13:05 -0300, prakash jp escribió: I am using quickfix, would like to start with that ..\quickfix-1.13.3\quickfix\examples\executor\python\executor.py asks for a configuration file how should it look like. This one? http://www.quickfixengine.org/ I see a forum and a mailing list - I think you'll get more help there. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a piping error
On Jun 10, 5:56 pm, Hans Mulder wrote: > On 10/06/11 22:56:06, virdo wrote: > > > > > > > > > > > On Jun 10, 4:48 pm, John Gordon wrote: > >> In<6e035898-8938-4a61-91de-7a0ea7ead...@y30g2000yqb.googlegroups.com> > >> virdo writes: > > >>> My python file is simple print "test". I run it, it works no problem. > >>> I pipe the output to a file "run> logfile" and that's the error I > >>> get. This is with Windows Server 2008 (64 bit) using ActivePython > >>> 2.7.1.4 (64 bit). > > >> Are you using an actual pipe symbol in your command? Your post title > >> suggests you are, but your sample command uses the greater-than symbol. > > > My apologies, I miswrote. It is the greater than symbol rather than a > > pipe. > > > Example: > > > c:\PRG>test.py> test.log > > close failed in file object destructor: > > sys.excepthook is missing > > lost sys.stderr > > I think your problem is that some other process still has opened the > file test.log and Python cannot write it. Unfortunately, Python only > finds out when it is shutting down and cleaning out the "sys" module. > An exception is raised, but sys.excepthook has already been disposed. > Python's normal fallback stategy is to write the exception and the > traceback to sys.stderr. Unfortunately, sys.stderr has been disposed > as well. > > I get a similar message if I try to write to a closed pipe: > > $ python -c 'print "test"' | false > close failed in file object destructor: > sys.excepthook is missing > lost sys.stderr > $ > > I think this is a bug in Pyhton: the interpreter should flush sys.stdout > before tering dwn the 'sys' module, so that it can report an excption if > the flush attempt fails. > > A work-around is to add "import sys" at the top of your script, and > "sys.stdout.flush()" at the bottom: > > import sys > print "test" > sys.stdout.flush() > > That should report a proper exception; for example: > > $ python -c 'import sys; print "test"; sys.stdout.flush();' | false > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 32] Broken pipe > $ > > Hope this helps, > > -- HansM Thank you Hans! I've got it working, and posting it in case others end up running into the same problem. When I first changed the python test.py file to : import sys print "yes" sys.stdout.flush() I got : >test2.py > test2.log Traceback (most recent call last): File "C:\PRG\blah\test2.py", line 3, in sys.stdout.flush() IOError: [Errno 9] Bad file descriptor Googled a bit for the solution, but then I've ran your version (slightly modified) with no errors: python -c "import sys; print 'test'; sys.stdout.flush();" > test.log Finally, when I run the .py file with "python test.py > test.log" as opposed to just "test.py > test.log" or "test > test.log", it works. I've tried figuring out what the problem is, but from the quick glance, python that runs .py files and python that's in my path both are the same "c:\Python27\python.exe". I'm happy with the workaround however :) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Help for chimera
Hello, I am trying to create a movie in chimera UCSF using the python scripts. I want to take an input of certain images, rotate, translate, etc and make a movie out of them all through the command line. So if I were give a series of images from a matlab code, my script would generate a video out of that. Can you please enlighten me on this problem. I am not much familiar with the python scripts? It would be really great if I could get some link to some video or a tutorial that would help me. I found the documentation on the chimera web page not so user-friendly. Regards, Chinmaya -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
2011/6/11 Sérgio Monteiro Basto : > ok after thinking about this, this problem exist because Python want be > smart with ttys The *anomaly* (not problem) exists because Python has a way of being told a target encoding. If two parties agree on an encoding, they can send characters to each other. I had this discussion at work a while ago; my boss was talking about being "binary-safe" (which really meant "8-bit safe"), while I was saying that we should support, verify, and demand properly-formed UTF-8. The main significance is that agreeing on an encoding means we can change the encoding any time it's convenient, without having to document that we've changed the data - because we haven't. I can take the number "twelve thousand three hundred and forty-five" and render that as a string of decimal digits as "12345", or as hexadecimal digits as "3039", but I haven't changed the number. If you know that I'm giving you a string of decimal digits, and I give you "12345", you will get the same number at the far side. Python has agreed with stdout that it will send it characters encoded in UTF-8. Having made that agreement, Python and stdout can happily communicate in characters, not bytes. You don't need to explicitly encode your characters into bytes - and in fact, this would be a very bad thing to do, because you don't know _what_ encoding stdout is using. If it's expecting UTF-16, you'll get a whole lot of rubbish if you send it UTF-8 - but it'll look fine if you send it Unicode. Chris Angelico -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 10/06/11 20:03:44, Kurt Smith wrote: On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips wrote: How do I write my script so it picks up argument from the output of commands that pipe input into my script? def main(): import sys print sys.stdin.read() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ $ cat script.py def main(): print raw_input() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a piping error
On 10/06/11 22:56:06, virdo wrote: On Jun 10, 4:48 pm, John Gordon wrote: In<6e035898-8938-4a61-91de-7a0ea7ead...@y30g2000yqb.googlegroups.com> virdo writes: My python file is simple print "test". I run it, it works no problem. I pipe the output to a file "run> logfile" and that's the error I get. This is with Windows Server 2008 (64 bit) using ActivePython 2.7.1.4 (64 bit). Are you using an actual pipe symbol in your command? Your post title suggests you are, but your sample command uses the greater-than symbol. My apologies, I miswrote. It is the greater than symbol rather than a pipe. Example: c:\PRG>test.py> test.log close failed in file object destructor: sys.excepthook is missing lost sys.stderr I think your problem is that some other process still has opened the file test.log and Python cannot write it. Unfortunately, Python only finds out when it is shutting down and cleaning out the "sys" module. An exception is raised, but sys.excepthook has already been disposed. Python's normal fallback stategy is to write the exception and the traceback to sys.stderr. Unfortunately, sys.stderr has been disposed as well. I get a similar message if I try to write to a closed pipe: $ python -c 'print "test"' | false close failed in file object destructor: sys.excepthook is missing lost sys.stderr $ I think this is a bug in Pyhton: the interpreter should flush sys.stdout before tering dwn the 'sys' module, so that it can report an excption if the flush attempt fails. A work-around is to add "import sys" at the top of your script, and "sys.stdout.flush()" at the bottom: import sys print "test" sys.stdout.flush() That should report a proper exception; for example: $ python -c 'import sys; print "test"; sys.stdout.flush();' | false Traceback (most recent call last): File "", line 1, in IOError: [Errno 32] Broken pipe $ Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Friday, June 10, 2011 2:51:20 AM UTC-7, Steven D'Aprano wrote: > On Thu, 09 Jun 2011 20:36:53 -0700, Carl Banks wrote: > > Put it this way: if Python doesn't automatically inherit docstrings, the > > worst that can happen is missing information. If Python does inherit > > docstrings, it can lead to incorrect information. > > This is no different from inheriting any other attribute. If your class > inherits "attribute", you might get an invalid value unless you take > steps to ensure it is a valid value. This failure mode doesn't cause us > to prohibit inheritance of attributes. Ridiculous. The docstring is an attribute of the function, not the class, which makes it very different from any other attribute. Consider this: class A(object): foo = SomeClass() class B(A): foo = SomeOtherUnrelatedClass() Would you have B.foo "inherit" all the attributes of A.foo that it doesn't define itself? That's the analogous case to inheriting docstrings. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thursday, June 9, 2011 10:18:34 PM UTC-7, Ben Finney wrote: [snip example where programmer is expected to consult class docstring to infer what a method does] > There's nothing wrong with the docstring for a method referring to the > context within which the method is defined. > > > Whenever somebody overrides a method to do something different, the > > inherited docstring will be insufficient (as in your ABC example) or > > wrong. > > I hope the above demonstrates that your assertion is untrue. Every > single method on a class doesn't need to specify the full context; a > docstring that requires the reader to know what class the method belongs > to is fine. It does not. A docstring that requires the user to to figure out that is poor docstring. There is nothing wrong, as you say, incomplete documentation that doesn't say what the function actually does. There's nothing wrong with omitting the docstring entirely for that matter. However, the question here is not whether a programmer is within right to use poor docstrings, but whether the langauge would go out of its way to support them. It should not. There is one thing that is very wrong to do with a docstring: provide incorrect or misleading information. So, despite having brought the point up myself, I am going to say the point is moot. Even if it is absolutely desirable for a language to go out it's way to support incomplete docstrings, part of that bargain is that the language will go out of its way to support flat-out wrong docstrings, and that trumps any ostensible benefit. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 06/10/2011 04:00 PM, Benjamin Kaplan wrote: On Fri, Jun 10, 2011 at 11:31 AM, Tim Chase if os.isatty(sys.stdin): #<-- this check Any reason for that over sys.stdin.isatty()? my knowledge of os.isatty() existing and my previous lack of knowledge about sys.stdin.isatty() :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt
On Fri, Jun 10, 2011 at 12:15 PM, KK wrote: > Thanks for the reply!! > i ve installed the binary > but when i import anything of PyQt in my prog it says error?? > i think there is some problem with folders What is the exact text of the error message? We can't help you unless we know exactly what's wrong. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:31 AM, Tim Chase wrote: > On 06/10/2011 12:58 PM, Mark Phillips wrote: >> >> How do I write my script so it picks up argument from the >> output of commands that pipe input into my script? > > You can check > > if os.isatty(sys.stdin): # <-- this check Any reason for that over sys.stdin.isatty()? -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a piping error
On Jun 10, 4:48 pm, John Gordon wrote: > In <6e035898-8938-4a61-91de-7a0ea7ead...@y30g2000yqb.googlegroups.com> virdo > writes: > > > My python file is simple print "test". I run it, it works no problem. > > I pipe the output to a file "run > logfile" and that's the error I > > get. This is with Windows Server 2008 (64 bit) using ActivePython > > 2.7.1.4 (64 bit). > > Are you using an actual pipe symbol in your command? Your post title > suggests you are, but your sample command uses the greater-than symbol. My apologies, I miswrote. It is the greater than symbol rather than a pipe. Example: c:\PRG>test.py > test.log close failed in file object destructor: sys.excepthook is missing lost sys.stderr -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with a piping error
In <6e035898-8938-4a61-91de-7a0ea7ead...@y30g2000yqb.googlegroups.com> virdo writes: > My python file is simple print "test". I run it, it works no problem. > I pipe the output to a file "run > logfile" and that's the error I > get. This is with Windows Server 2008 (64 bit) using ActivePython > 2.7.1.4 (64 bit). Are you using an actual pipe symbol in your command? Your post title suggests you are, but your sample command uses the greater-than symbol. It's always best to include the actual command and the actual output rather than typing it by hand, specifically to avoid errors like this. Please repost a transcript of your real session. -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
Help with a piping error
Hi, I'm getting the following error and I can't Google my way out of it: close failed in file object destructor: sys.excepthook is missing lost sys.stderr My python file is simple print "test". I run it, it works no problem. I pipe the output to a file "run > logfile" and that's the error I get. This is with Windows Server 2008 (64 bit) using ActivePython 2.7.1.4 (64 bit). Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 1:33 PM, Dennis wrote: > On Fri, Jun 10, 2011 at 11:58 AM, Mark Phillips > fred > > ['alice'] > fred Just realized the if/else will have to be changed slightly if we want to output both argv and stdin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:58 AM, Mark Phillips wrote: \ > > Kurt, > > How does one write a main method to handle both command line args and stdin > args? Here is what I came up with: The one weird thing, the line from above didn't seem to work so I changed it if os.isatty(sys.stdin): to this: if not os.isatty(sys.stdin.fileno()): Below 3 tests, with stdin redirection, then with one argument, then with both stdin redirection and one argument, the results are at the very bottom. $ cat ./argvtest.py; echo "fred" | ./argvtest.py ; ./argvtest.py "alice"; echo "fred" | ./argvtest.py "bob" #!/usr/bin/python import os import sys def main(): #This checks to see if stdin is a not tty and > 0 if not os.isatty(sys.stdin.fileno()): arg = sys.stdin.read() print arg elif len(sys.argv[1:]) > 0: # if the length of the first argument is > 0 #[1:] strip the first string beacause it is the name of the script arg = sys.argv[1:] print arg if __name__ == "__main__": main() fred ['alice'] fred > > Thanks, > > Mark > Welcome, Dennis O. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
parallel computations: subprocess.Popen(...).communicate()[0] does not work with multiprocessing.Pool
Hi, I am having an issue when making a shell call from within a multiprocessing.Process(). Here is the story: i tried to parallelize the computations in 800-ish Matlab scripts and then save the results to MySQL. The non-parallel/serial version has been running fine for about 2 years. However, in the parallel version via multiprocessing that i'm working on, it appears that the Matlab scripts have never been kicked off and nothing happened with subprocess.Popen. The debug printing below does not show up either. Moreover, even if i replace the Matlab invocation with some trivial "sed" call, still nothing happens. Is it possible that the Python interpreter i'm using (version 2.6 released on Oct. 1, 2008) is too old? Nevertheless, i would like to make sure the basic framework i've now is not blatantly wrong. Below is a skeleton of my Python program: -- import subprocess from multiprocessing import Pool def worker(DBrow,config): # run one Matlab script cmd1 = "/usr/local/bin/matlab ... myMatlab.1.m" subprocess.Popen([cmd1], shell=True, stdout=subprocess.PIPE).communicate()[0] print "this does not get printed" cmd2 = "sed ..." print subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE).communicate()[0] print "this does not get printed either" sys.stdout.flush() ### main program below .. # kick off parallel processing pool = Pool() for DBrow in DBrows: pool.apply_async(worker,(DBrow,config)) pool.close() pool.join() .. -- Furthermore, i also tried adding the following: multiprocessing.current_process().curr_proc.daemon = False at the beginning of the "worker" function above but to no avail. Any help would really be appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Jun 10, 2011 10:26 AM, "Mark Phillips" wrote: > > I have a script that processes command line arguments > > def main(argv=None): > syslog.syslog("Sparkler stared processing") > if argv is None: > argv = sys.argv > if len(argv) != 2: > syslog.syslog(usage()) > else: > r = parseMsg(sys.argv[1]) > syslog.syslog(r) > return 0 > > if __name__ == "__main__": > sys.exit(main()) > > When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] > > When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. > > Is the problem with the echo command, or how I wrote my script? > > Thanks! > > Mark > Nothing wrong with either. The problem is a misunderstanding in how the command line works. When you write "python myscript fred", the shell calls the python executable and passes the arguments "myscript" and "fred" to the main function. In the second example, the shell calls "python myscript" and then sends echo's stdout in to python's stdin. It's not passed as an argument. If you were to call raw_input() on the second example, it would return "fred" without prompting you for anything because raw_input reads from stdin which in this case is the result of echo. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 6/10/11 12:58 PM, Mark Phillips wrote: On Fri, Jun 10, 2011 at 10:41 AM, MRAB mailto:pyt...@mrabarnett.plus.com>> wrote: On 10/06/2011 18:21, Mark Phillips wrote: I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? In the second case, there aren't any arguments. The echo command is writing "fred" to its standard output, which is attached to your script's standard input. How do I write my script so it picks up argument from the output of commands that pipe input into my script? You may want to just use the appropriate shell syntax instead: $ python myscript `echo fred` -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt
Thanks for the reply!! i ve installed the binary but when i import anything of PyQt in my prog it says error?? i think there is some problem with folders -- http://mail.python.org/mailman/listinfo/python-list
Re: The Forthcoder Diaries -- 2011 June 9
On Jun 10, 5:15 am, Brian Martin wrote: > Then again you could use a high level language like Perl, Python, APL ... > > On 10/06/2011 8:17 AM, Paul Rubin wrote: > > > Mentifex writes: > >> At one point, I had to create 8jun11T.F as a "Test" version of > >> MindForth, so that I could fix the JavaScript AI in comparison with > >> the Forth AI. > > > You could use both: > > > http://forthfreak.net/jsforth80x25.html > It is high time to port http://www.scn.org/~mentifex/AiMind.html into Python. Mentifex (Arthur) -- http://mind.sourceforge.net/python.html http://cyborg.blogspot.com/2011/01/aiapp.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:03 AM, Kurt Smith wrote: > On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips > wrote: > > How do I write my script so it picks up argument from the output of > commands > > that pipe input into my script? > > def main(): >import sys >print sys.stdin.read() > > if __name__ == '__main__': >main() > > $ echo "fred" | python script.py > fred > $ > Kurt, How does one write a main method to handle both command line args and stdin args? Thanks, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, Jun 10, 2011 at 11:26 AM, Ian Kelly wrote: > Everybody always focuses so much on properties and forgets that you > can also just write your own descriptors. > I'm so glad that you pointed this out. I totally forgot that properties simply returned themselves if not called on the instance. You are right about a custom descriptor. -eric class DocDescriptor(object): > ... def __get__(self, instance, owner): > ... return getattr(owner, "_mydoc", None) > ... class Meta(type): > ... def __init__(cls, name, bases, d): > ... super(Meta, cls).__init__(name, bases, d) > ... cls.__doc__ = DocDescriptor() > ... class X(object): > ... __metaclass__ = Meta > ... X.__doc__ X().__doc__ X._mydoc = 'test' X.__doc__ > 'test' X().__doc__ > 'test' class Derived(X): pass > ... Derived.__doc__ > 'test' Derived().__doc__ > 'test' > > There you go, a metaclass that adds a __doc__ descriptor that can be > inherited (thanks to the metaclass), can be accessed from either the > class or the instance (thanks to the descriptor), and can easily be > modified to generate the doc string dynamically at call-time if > desired. > > Cheers, > Ian > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
FYI, I started this topic up on python-ideas, as it seemed valid enough from the responses I've gotten here [1]. -eric [1] http://mail.python.org/pipermail/python-ideas/2011-June/010473.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 06/10/2011 12:58 PM, Mark Phillips wrote: How do I write my script so it picks up argument from the output of commands that pipe input into my script? You can check if os.isatty(sys.stdin): # <-- this check do_stuff_with_the_terminal() else: read_options_from_stdin() -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 11:03 AM, Dennis wrote: > On Fri, Jun 10, 2011 at 10:58 AM, Mark Phillips > wrote: >> On Fri, Jun 10, 2011 at 10:41 AM, MRAB wrote: >> >> On 10/06/2011 18:21, Mark Phillips wrote: > >> > How do I write my script so it picks up argument from the output of commands > that pipe input into my script? I think if you want to replicate stdin behaviour try looking into the xargs command, assuming that is available on your platform. However reading in stdin into argv may be more elegant, but slightly unexpected to the experienced user. Dennis O. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 12:58 PM, Mark Phillips wrote: > How do I write my script so it picks up argument from the output of commands > that pipe input into my script? def main(): import sys print sys.stdin.read() if __name__ == '__main__': main() $ echo "fred" | python script.py fred $ -- http://mail.python.org/mailman/listinfo/python-list
uhmm... your chance to spit on me
Dear lisp comrades, it's Friday! Dear Xah, your writing is: • Full of bad grammar. River of Hiccups. • Stilted. Chocked under useless structure and logic. • WRONG — Filled with uncouth advices. • Needlessly insulting. You have problems. • Simply stinks. Worthless. • Mediocre. Just like everybody, admit it. • I love it. • Your writing is pro! • you are genius! one of the great expositor, eassyist. • Dude, you are full of shit. I've not seen a crank quite like you. Vote at: http://xahlee.blogspot.com/2011/06/xahs-writing-is.html. Xah (i code python small time too) -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On Fri, Jun 10, 2011 at 10:41 AM, MRAB wrote: > On 10/06/2011 18:21, Mark Phillips wrote: > >> I have a script that processes command line arguments >> >> def main(argv=None): >> syslog.syslog("Sparkler stared processing") >> if argv is None: >> argv = sys.argv >> if len(argv) != 2: >> syslog.syslog(usage()) >> else: >> r = parseMsg(sys.argv[1]) >> syslog.syslog(r) >> return 0 >> >> if __name__ == "__main__": >> sys.exit(main()) >> >> When I run "python myscript fred" it works as expected - the argument >> fred is processed in parseMsg as sys.arv[1] >> >> When I run "echo fred | python myscript" the script thinks there are no >> arguments, so it prints out the usage statement. >> >> Is the problem with the echo command, or how I wrote my script? >> >> In the second case, there aren't any arguments. The echo command is > writing "fred" to its standard output, which is attached to your > script's standard input. > > How do I write my script so it picks up argument from the output of commands that pipe input into my script? Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Question About Command line arguments
On 10/06/2011 18:21, Mark Phillips wrote: I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? In the second case, there aren't any arguments. The echo command is writing "fred" to its standard output, which is attached to your script's standard input. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, 10 Jun 2011 11:01:41 -0600, Eric Snow wrote: > On Fri, Jun 10, 2011 at 10:47 AM, Steven D'Aprano > wrote: >> Here's some Python 3 code that uses a factory function as a metaclass >> to inherit docstrings. Give the class a docstring of an empty string, >> and it will be inherited from the first superclass found with a >> non-empty docstring. >> >> >> > Yeah, the idea of an empty docstring to trigger docstring inheritance > really appeals to me. Nice example. Incidently, aren't metaclasses > always inherited, as opposed to class decorators (which are never)? Metaclasses are inherited, but the example I give uses a factory function as a metaclass: it manipulates the docstring inside the dict, then returns an ordinary class. That makes it just a fancy class decorator using metaclass syntax. The type of each class A, B, ... F is just type, which means that when you subclass each class you don't get any magic metaclass behaviour unless you explicitly set the metaclass directly. That is: assert type(A) is type succeeds, so class B(A) doesn't do anything special unless you explicitly set the metaclass. I followed up with a second example using a conventional metaclass, that is, where the type of each class is *not* type. In that case, the magic behaviour is inherited and there's no need to explicitly set the metaclass except for the first time. (Whew. Talking about metaclasses is hard work.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, Jun 10, 2011 at 10:55 AM, Eric Snow wrote: > The only problem, as seen in the last line, is that the __doc__ on > instances is not inherited on instances of the class. Object > attribute lookup only looks to the type's __dict__ for inheritance, > and not the types's type. However, that should not be that hard to > work around. Everybody always focuses so much on properties and forgets that you can also just write your own descriptors. >>> class DocDescriptor(object): ... def __get__(self, instance, owner): ... return getattr(owner, "_mydoc", None) ... >>> class Meta(type): ... def __init__(cls, name, bases, d): ... super(Meta, cls).__init__(name, bases, d) ... cls.__doc__ = DocDescriptor() ... >>> class X(object): ... __metaclass__ = Meta ... >>> X.__doc__ >>> X().__doc__ >>> X._mydoc = 'test' >>> X.__doc__ 'test' >>> X().__doc__ 'test' >>> class Derived(X): pass ... >>> Derived.__doc__ 'test' >>> Derived().__doc__ 'test' There you go, a metaclass that adds a __doc__ descriptor that can be inherited (thanks to the metaclass), can be accessed from either the class or the instance (thanks to the descriptor), and can easily be modified to generate the doc string dynamically at call-time if desired. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Question About Command line arguments
I have a script that processes command line arguments def main(argv=None): syslog.syslog("Sparkler stared processing") if argv is None: argv = sys.argv if len(argv) != 2: syslog.syslog(usage()) else: r = parseMsg(sys.argv[1]) syslog.syslog(r) return 0 if __name__ == "__main__": sys.exit(main()) When I run "python myscript fred" it works as expected - the argument fred is processed in parseMsg as sys.arv[1] When I run "echo fred | python myscript" the script thinks there are no arguments, so it prints out the usage statement. Is the problem with the echo command, or how I wrote my script? Thanks! Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, 10 Jun 2011 16:47:03 +, Steven D'Aprano wrote: > On Thu, 09 Jun 2011 00:22:54 -0600, Eric Snow wrote: > >> Sometimes when using class inheritance, I want the overriding methods >> of the subclass to get the docstring of the matching method in the base >> class. You can do this with decorators (after the class definition), >> with class decorators, and with metaclasses [1]. > > > Here's some Python 3 code that uses a factory function as a metaclass to > inherit docstrings. Give the class a docstring of an empty string, and > it will be inherited from the first superclass found with a non-empty > docstring. [...] And here's a version using a more conventional metaclass. Extending this to work on methods is left as an exercise. class MetaDocstring(type): @staticmethod def get_mro(bases): return type('K', bases, {}).__mro__[1:-1] @staticmethod def get_docstring(mro): for k in mro: if k.__doc__: return k.__doc__ def __new__(cls, name, bases, dict): mro = None docstring = dict.get('__doc__') if docstring == '': mro = cls.get_mro(bases) dict['__doc__'] = cls.get_docstring(mro) assert dict.get('__doc__') != '' # Create the class we want, and return it. K = super().__new__(cls, name, bases, dict) if mro: assert K.__mro__ == (K,) + mro + (object,) return K class U(metaclass=MetaDocstring): pass class V(U): '' class W(V): 'A docstring.' class X(V): pass class Y(X, W): '' class Z(Y): '' assert all(type(cls) is MetaDocstring for cls in (U, V, W, X, Y, Z)) assert all(cls.__doc__ is None for cls in (U, V, X)) assert all(cls.__doc__ == 'A docstring.' for cls in (W, Y, Z)) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, Jun 10, 2011 at 10:47 AM, Steven D'Aprano wrote: > Here's some Python 3 code that uses a factory function as a metaclass to > inherit docstrings. Give the class a docstring of an empty string, and it > will be inherited from the first superclass found with a non-empty > docstring. > > Yeah, the idea of an empty docstring to trigger docstring inheritance really appeals to me. Nice example. Incidently, aren't metaclasses always inherited, as opposed to class decorators (which are never)? -eric > > def InheritableDocstring(name, bases, dict): > mro = None > docstring = dict.get('__doc__') > if docstring == '': > # Search the MRO for the first non-empty docstring. We let Python > # do all the hard work of calculating the MRO. > mro = type('K', bases, {}).__mro__[1:] # Exclude the class K. > # Also exclude object. > assert mro[-1] == object > mro = mro[:-1] > for cls in mro: > if cls.__doc__: > docstring = cls.__doc__ > break > else: > docstring = None > dict['__doc__'] = docstring > assert dict.get('__doc__') != '' > # Create the class we want, and return it. > cls = type(name, bases, dict) > if mro: > assert cls.__mro__ == (cls,) + mro + (object,) > return cls > > > > class A(metaclass=InheritableDocstring): > pass > > class B(A, metaclass=InheritableDocstring): > '' > > class C(B, metaclass=InheritableDocstring): > 'A docstring.' > > class D(B, metaclass=InheritableDocstring): > pass > > class E(D, C, metaclass=InheritableDocstring): > '' > > class F(E, metaclass=InheritableDocstring): > '' > > assert all(cls.__doc__ is None for cls in (A, B, D)) > assert all(cls.__doc__ == 'A docstring.' for cls in (C, E, F)) > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
2011/6/10 Sérgio Monteiro Basto : > ok after thinking about this, this problem exist because Python want be > smart with ttys, which is in my point of view is wrong, should not encode to > utf-8, because tty is in utf-8. Python should always encode to the same > thing. If the default is ascii, should always encode to ascii. > yeah should send to tty in ascii, if I send my code to a guy in windows > which use tty with cp1000whatever , shouldn't give decoding errors and > should send in ascii . You can't have your cake and eat it too. If Python needs to output a string in ascii, and that string can't be represented in ascii, then raising an exception is the only reasonable thing to do. You seem to be suggesting that Python should do an implicit output.encode('ascii', 'replace') on all Unicode output, which might be okay for a TTY, but you wouldn't want that for file output; it would allow Python to silently create garbage data. And what if you send your code to somebody with a UTF-16 terminal? You try to output ASCII to that, and you're just going to get complete garbage. If you want your output to behave that way, then all you have to do is specify that with an explicit encode step. > If we want we change default for whatever we want, but without this "default > change" Python should not change his behavior depending on output. > yeah I prefer strange output for a different platform, to a decode errors. Sorry, I disagree. If your program is going to fail, it's better that it fail noisily (with an error) than silently (with no notice that anything is wrong). -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, Jun 10, 2011 at 5:05 AM, Tim Chase wrote: > On 06/09/2011 01:22 AM, Eric Snow wrote: >> >> Sometimes when using class inheritance, I want the overriding methods >> of the subclass to get the docstring of the matching method in the >> base class. You can do this with decorators (after the class >> definition), with class decorators, and with metaclasses [1]. > > While asking for __doc__ ponies and picking colors for bike-sheds, in a > similar vein, I've occasionally wanted to do something like > > class Foo: > @property > def __doc__(self): > return dynamically_generated_string > # perhaps using introspection > However, on the class the property is just a property object (a descriptor). If you want to have a dynamic doc on the class then you have to do it on a metaclass: class Meta(type): @property def __doc__(cls): if not hasattr(cls, "_mydoc"): cls._mydoc = None return cls._mydoc class X(metaclass=Meta): pass X.__doc__ # None X._mydoc # None X._mydoc = "test" X.__doc__ # 'test' X().__doc__ # None The only problem, as seen in the last line, is that the __doc__ on instances is not inherited on instances of the class. Object attribute lookup only looks to the type's __dict__ for inheritance, and not the types's type. However, that should not be that hard to work around. -eric > This would have been most helpful in things like generating help (like in > command-line parsers), where the doc-string can introspect the class and > learn about its methods at runtime. Some things seem to inherit, some don't, > and help() doesn't seem to pick up on any of the dynamically-defined __doc__ > properties. Test code below. > > -tkc > > > > from datetime import datetime > from sys import stdout > class Base(object): > "Base docstring" > @property > def __doc__(self): > return datetime.now().strftime('%c') > > class WithDoc(Base): > "WithDoc docstring" > pass > > class WithoutDoc(Base): pass > > base = Base() > has = WithDoc() > lacks = WithoutDoc() > > for test in ( > "help(base)", # why not in help? > "help(has)", # expected > "help(lacks)", # why not in help? > "help(Base)", > "help(WithDoc)", # expected > "help(WithoutDoc)", > "stdout.write(repr(base.__doc__))", # works > "stdout.write(repr(has.__doc__))", # expected > "stdout.write(repr(lacks.__doc__))", # where'd it go? > "stdout.write(repr(Base.__doc__))", # expected > "stdout.write(repr(WithDoc.__doc__))", # expected > "stdout.write(repr(WithoutDoc.__doc__))", # what? > ): > print test > eval(test) > print > -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, 09 Jun 2011 00:22:54 -0600, Eric Snow wrote: > Sometimes when using class inheritance, I want the overriding methods of > the subclass to get the docstring of the matching method in the base > class. You can do this with decorators (after the class definition), > with class decorators, and with metaclasses [1]. Here's some Python 3 code that uses a factory function as a metaclass to inherit docstrings. Give the class a docstring of an empty string, and it will be inherited from the first superclass found with a non-empty docstring. def InheritableDocstring(name, bases, dict): mro = None docstring = dict.get('__doc__') if docstring == '': # Search the MRO for the first non-empty docstring. We let Python # do all the hard work of calculating the MRO. mro = type('K', bases, {}).__mro__[1:] # Exclude the class K. # Also exclude object. assert mro[-1] == object mro = mro[:-1] for cls in mro: if cls.__doc__: docstring = cls.__doc__ break else: docstring = None dict['__doc__'] = docstring assert dict.get('__doc__') != '' # Create the class we want, and return it. cls = type(name, bases, dict) if mro: assert cls.__mro__ == (cls,) + mro + (object,) return cls class A(metaclass=InheritableDocstring): pass class B(A, metaclass=InheritableDocstring): '' class C(B, metaclass=InheritableDocstring): 'A docstring.' class D(B, metaclass=InheritableDocstring): pass class E(D, C, metaclass=InheritableDocstring): '' class F(E, metaclass=InheritableDocstring): '' assert all(cls.__doc__ is None for cls in (A, B, D)) assert all(cls.__doc__ == 'A docstring.' for cls in (C, E, F)) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: the stupid encoding problem to stdout
Ben Finney wrote: >> > What should it decode to, then? >> >> UTF-8, as in tty > > But when you explicitly redirect to a file, it's not going to a TTY. > It's going to a file whose encoding isn't known unless you specify it. ok after thinking about this, this problem exist because Python want be smart with ttys, which is in my point of view is wrong, should not encode to utf-8, because tty is in utf-8. Python should always encode to the same thing. If the default is ascii, should always encode to ascii. yeah should send to tty in ascii, if I send my code to a guy in windows which use tty with cp1000whatever , shouldn't give decoding errors and should send in ascii . If we want we change default for whatever we want, but without this "default change" Python should not change his behavior depending on output. yeah I prefer strange output for a different platform, to a decode errors. And I have /usr/bin/iconv . Thanks for attention, sorry about my very limited English. -- Sérgio M. B. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt
On 2011.06.10 08:09 AM, KK wrote: > I have python 3.2 installed m not able to install PyQt. > i have downloaded and configured sip but how to build it??? The pages are misleading. You only need the SIP source if you want to build everything from source. Since you don't seem to be familiar with make, I'll assume you're on Windows, in which case you should grab the binaries here: http://www.riverbankcomputing.com/software/pyqt/download Choose the bitness that matches the bitness of your installed Python. -- http://mail.python.org/mailman/listinfo/python-list
PyQt
I have python 3.2 installed m not able to install PyQt. i have downloaded and configured sip but how to build it??? whats the make and make install given on the installation Plzzz help m a newbie to python -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported operand type(s) for +: 'float' and 'tuple'
On 10 jun, 13:38, Tim Chase wrote: > On 06/10/2011 05:30 AM, Francesc Segura wrote: > > > Hello all, I'm new to this and I'm having problems on summing two > > values at python. > > > I get the following error: > > > Traceback (most recent call last): > > File "C:\edge-bc (2).py", line 168, in > > if (costGG<= cost + T0): > > TypeError: unsupported operand type(s) for +: 'float' and 'tuple' > > > I'm working with networkx and my program is this one: > ... > > T0 = initCost*0,1 > > Here, you're setting T0 to the tuple "(initCost*0, 1)" == "(0, > 1)". I think you mean to use a period instead of a comma. > > You then try to add that to a float (cost), and Python doesn't > like that. I wouldn't either :) > > -tkc Thanks a lot, I am a noob retard! -- http://mail.python.org/mailman/listinfo/python-list
Kathryn Sokolich Spawned A Crook
Sure did http://www.manta.com/c/mmlq5dm/w-gary-sokolich W Gary Sokolich 801 Kings Road Newport Beach, CA 92663-5715 (949) 650-5379 http://www.tbpe.state.tx.us/da/da022808.htm TEXAS BOARD OF PROFESSIONAL ENGINEERS February 28, 2008 Board Meeting Disciplinary Actions W. Gary Sokolich , Newport Beach, California – File B-29812 - It was alleged that Dr. Sokolich unlawfully offered or attempted to practice engineering in Texas (...) Dr. Sokolich chose to end the proceedings by signing a Consent Order that was accepted by the Board to cease and desist from representing himself as an “Engineer” in Texas, from any and all representations that he can offer or perform engineering services and from the actual practice of engineering in Texas (...) Dr. Sokolich was also assessed a $1,360.00 administrative penalty. ___ http://articles.latimes.com/1988-04-14/local/me-1922_1_ucla-researcher A former UCLA physiologist has agreed to provide copies of his research to the school to settle a lawsuit the university filed against him in 1985, lawyers in the case said. (...) The University of California Board of Regents filed a $620,000 lawsuit against Sokolich, accusing him of taking research on the hearing capabilities of animals in June, 1982. Sokolich was dismissed by UCLA because research funding had run out. (...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Unsupported operand type(s) for +: 'float' and 'tuple'
On 06/10/2011 05:30 AM, Francesc Segura wrote: Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG<= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I'm working with networkx and my program is this one: ... T0 = initCost*0,1 Here, you're setting T0 to the tuple "(initCost*0, 1)" == "(0, 1)". I think you mean to use a period instead of a comma. You then try to add that to a float (cost), and Python doesn't like that. I wouldn't either :) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On 06/09/2011 01:22 AM, Eric Snow wrote: Sometimes when using class inheritance, I want the overriding methods of the subclass to get the docstring of the matching method in the base class. You can do this with decorators (after the class definition), with class decorators, and with metaclasses [1]. While asking for __doc__ ponies and picking colors for bike-sheds, in a similar vein, I've occasionally wanted to do something like class Foo: @property def __doc__(self): return dynamically_generated_string # perhaps using introspection This would have been most helpful in things like generating help (like in command-line parsers), where the doc-string can introspect the class and learn about its methods at runtime. Some things seem to inherit, some don't, and help() doesn't seem to pick up on any of the dynamically-defined __doc__ properties. Test code below. -tkc from datetime import datetime from sys import stdout class Base(object): "Base docstring" @property def __doc__(self): return datetime.now().strftime('%c') class WithDoc(Base): "WithDoc docstring" pass class WithoutDoc(Base): pass base = Base() has = WithDoc() lacks = WithoutDoc() for test in ( "help(base)", # why not in help? "help(has)", # expected "help(lacks)", # why not in help? "help(Base)", "help(WithDoc)", # expected "help(WithoutDoc)", "stdout.write(repr(base.__doc__))", # works "stdout.write(repr(has.__doc__))", # expected "stdout.write(repr(lacks.__doc__))", # where'd it go? "stdout.write(repr(Base.__doc__))", # expected "stdout.write(repr(WithDoc.__doc__))", # expected "stdout.write(repr(WithoutDoc.__doc__))", # what? ): print test eval(test) print -- http://mail.python.org/mailman/listinfo/python-list
Unsupported operand type(s) for +: 'float' and 'tuple'
Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG <= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I'm working with networkx and my program is this one: import networkx as NX import pylab as P from math import exp, log import random try: import matplotlib.pyplot as plt except: raise ##N=27 N=30 ITERATIONS = 60 T0 = 0.5 RO = 0.99 NK = 20 def costG(G): bc = NX.edge_betweenness_centrality(G,normalized=True) edges = NX.edges(G) for i in range(len(edges)): total = 0 cost = 0 factor = 1 liedges = list(edges[i]) linode1 = list(liedges[0]) linode2 = list(liedges[1]) distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]- linode1[1])%N)^2) edgecentrality = bc[edges[i]] factor = (distance-19790)*(-0.55586) cost = distance*edgecentrality*factor total = total + cost return(total) def avedistance(G): return (AvgDist) def costGeasy(G): bc = NX.edge_betweenness_centrality(G,normalized=True) total = 0 for i in range(len(bc)): total=total+bc.values()[i] return (total) G = NX.grid_2d_graph(N,N,True) for i in range(N): for j in range(N): G.add_edge((i,j),((i+1) % N ,(j+1) % N)) G.add_edge((i,j),((i-1) % N ,(j+1) % N)) NODES=NX.number_of_nodes(G) nod=NX.nodes(G) EDGES=NX.number_of_edges(G) edg=NX.edges(G) pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Inicial graph, Toroidal 27x27, degree 8") plt.savefig("initial_grid_malla.png") plt.show() pos=NX.spring_layout(G,iterations=100) NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Inicial graph, Toroidal 27x27, degree 8") plt.savefig("initial_grid_tor.png") plt.show() initGr = G best_graph = G best_cost = costG(G) average_distance = avedistance(G) initCost = best_cost initGHist = NX.degree_histogram(G) ##print NX.info(initGr) ##print 'Diameter = %f ' % (NX.diameter(G)) ##print 'Avg Clust Coeff. NetworkX = %-6.4f ' % (NX.average_clustering(G)) ##print 'Avg Dist. NetworkX = %-6.4f ' % (average_distance) ##print 'Distribucio de Graus' ##print initGHist ##print 'Cost inicial' ##print initCost T0 = initCost*0,1 for y in range(NK): for x in range(ITERATIONS): cost = costG(G) if (cost < (best_cost)): best_graph = G best_cost = cost GG = G u = random.randint(0,NODES-1) while GG.degree(nod[u]) <= 1: u = random.randint(0,NODES-1) v = random.randint(0,GG.degree(nod[u])-1) GG.remove_edge(nod[u],GG[nod[u]].keys()[v]) a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=G.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) while (NX.is_connected(GG) == 0): GG = G u = random.randint(0,NODES-1) while GG.degree(nod[u]) <= 1: u = random.randint(0,NODES-1) v = random.randint(0,GG.degree(nod[u])-1) GG.remove_edge(nod[u],GG[nod[u]].keys()[v]) a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=GG.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) costGG = costG(GG) if (costGG <= cost): G = GG else: if (costGG <= cost + T0): G = GG T0 = T0 * RO print 'IT %d' % y print 'BEST %f ' % best_cost best_graph = G print NX.info(best_graph) print 'Diameter = %f ' % (NX.diameter(best_graph)) print 'Avg Clust Coeff. NetworkX = %-6.4f ' % (NX.average_clustering(best_graph)) average_distance = avedistance(best_graph) print 'Avg Dist. NetworkX = %-6.4f ' % (average_distance) print 'Distribucio de Graus' print NX.degree_histogram(best_graph) print 'Millor Cost' print best_cost NX.write_edgelist(best_graph,'optimal-graph.dat') pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Final graph, Toroidal 27x27, degree 8") plt.savefig("final_grid_malla.png") plt.show() pos=NX.spring_layout(G,iterations=100) NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Final graph, Toroidal 27x27, degree 8") plt.savefig("final_grid_tor.png") plt.show() -- http://mail.python.org/mailman/listinfo/python-list
Unsupported operand type(s) for +: 'float' and 'tuple'
Hello all, I'm new to this and I'm having problems on summing two values at python. I get the following error: Traceback (most recent call last): File "C:\edge-bc (2).py", line 168, in if (costGG <= cost + T0): TypeError: unsupported operand type(s) for +: 'float' and 'tuple' I'm working with networkx and my program is this one: import networkx as NX import pylab as P from math import exp, log import random try: import matplotlib.pyplot as plt except: raise ##N=27 N=30 ITERATIONS = 60 T0 = 0.5 RO = 0.99 NK = 20 def costG(G): bc = NX.edge_betweenness_centrality(G,normalized=True) edges = NX.edges(G) for i in range(len(edges)): total = 0 cost = 0 factor = 1 liedges = list(edges[i]) linode1 = list(liedges[0]) linode2 = list(liedges[1]) distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]- linode1[1])%N)^2) edgecentrality = bc[edges[i]] factor = (distance-19790)*(-0.55586) cost = distance*edgecentrality*factor total = total + cost return(total) def avedistance(G): return (AvgDist) def costGeasy(G): bc = NX.edge_betweenness_centrality(G,normalized=True) total = 0 for i in range(len(bc)): total=total+bc.values()[i] return (total) G = NX.grid_2d_graph(N,N,True) for i in range(N): for j in range(N): G.add_edge((i,j),((i+1) % N ,(j+1) % N)) G.add_edge((i,j),((i-1) % N ,(j+1) % N)) NODES=NX.number_of_nodes(G) nod=NX.nodes(G) EDGES=NX.number_of_edges(G) edg=NX.edges(G) pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Inicial graph, Toroidal 27x27, degree 8") plt.savefig("initial_grid_malla.png") plt.show() pos=NX.spring_layout(G,iterations=100) NX.draw(G,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Inicial graph, Toroidal 27x27, degree 8") plt.savefig("initial_grid_tor.png") plt.show() initGr = G best_graph = G best_cost = costG(G) average_distance = avedistance(G) initCost = best_cost initGHist = NX.degree_histogram(G) ##print NX.info(initGr) ##print 'Diameter = %f ' % (NX.diameter(G)) ##print 'Avg Clust Coeff. NetworkX = %-6.4f ' % (NX.average_clustering(G)) ##print 'Avg Dist. NetworkX = %-6.4f ' % (average_distance) ##print 'Distribucio de Graus' ##print initGHist ##print 'Cost inicial' ##print initCost T0 = initCost*0,1 for y in range(NK): for x in range(ITERATIONS): cost = costG(G) if (cost < (best_cost)): best_graph = G best_cost = cost GG = G u = random.randint(0,NODES-1) while GG.degree(nod[u]) <= 1: u = random.randint(0,NODES-1) v = random.randint(0,GG.degree(nod[u])-1) GG.remove_edge(nod[u],GG[nod[u]].keys()[v]) a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=G.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) while (NX.is_connected(GG) == 0): GG = G u = random.randint(0,NODES-1) while GG.degree(nod[u]) <= 1: u = random.randint(0,NODES-1) v = random.randint(0,GG.degree(nod[u])-1) GG.remove_edge(nod[u],GG[nod[u]].keys()[v]) a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) adj=GG.adjacency_list() while ((nod[b] in adj[a]) or (b == a)): a = random.randint(0,NODES-1) b = random.randint(0,NODES-1) GG.add_edge(nod[a],nod[b]) costGG = costG(GG) if (costGG <= cost): G = GG else: if (costGG <= cost + T0): G = GG T0 = T0 * RO print 'IT %d' % y print 'BEST %f ' % best_cost best_graph = G print NX.info(best_graph) print 'Diameter = %f ' % (NX.diameter(best_graph)) print 'Avg Clust Coeff. NetworkX = %-6.4f ' % (NX.average_clustering(best_graph)) average_distance = avedistance(best_graph) print 'Avg Dist. NetworkX = %-6.4f ' % (average_distance) print 'Distribucio de Graus' print NX.degree_histogram(best_graph) print 'Millor Cost' print best_cost NX.write_edgelist(best_graph,'optimal-graph.dat') pos={} for i in range(NODES): pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0)) NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Final graph, Toroidal 27x27, degree 8") plt.savefig("final_grid_malla.png") plt.show() pos=NX.spring_layout(G,iterations=100) NX.draw(best_graph,pos,node_color='r',node_size=20,with_labels=False,width=1) plt.title("Final graph, Toroidal 27x27, degree 8") plt.savefig("final_grid_tor.png") plt.show() -- http://mail.python.org/mailman/listinfo/python-list
Py2exe
Hi Im new to this and I am having a problem converting my .py to a .exe I get the following: Traceback (most recent call last): File "casemng.py", line 163, in File "casemng.py", line 38, in __init__ File "wx\_core.pyc", line 3369, in ConvertToBitmap wx._core.PyAssertionError: C++ assertion "image.Ok()" failed at ..\..\src\msw\bitmap.cpp(802) in wxBitmap::CreateFromImage(): invalid image I think that this is due to p2exe not being able manage the images which I have used on the buttons. As I say I'm very new to this so please take it easy on me. Thank you for any help -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, 09 Jun 2011 20:36:53 -0700, Carl Banks wrote: > x = random.choice([Triange(),Square()]) print x.draw.__doc__ # prints > "Draws a shape" > > > Quick, what shape is x.draw() going to draw? That's easy... it will draw a type(x).__name__. I think this not a terribly convincing argument. I don't particularly see how it is very different (worse, or better) from what you can already get in Python. If you don't know what x is, you might not know what it will do. >>> assert issubclass(ValueError, Exception) >>> ValueError.__doc__ 'Inappropriate argument value (of correct type).' >>> Exception.__doc__ 'Common base class for all non-exit exceptions.' >>> from random import choice >>> x = choice([ValueError, Exception]) Quick, what will x.__doc__ print? > Shouldn't your docstring > say what the method is going to do? But it does say what the method does. It prints a shape, just like the docstring says. It might not be a terribly detailed description, but that counts as a quality of implementation issue, not a functional bug. > So, I'm sorry, but I don't see this being sufficient for your use case > for ABCs. > > >> I'm just not clear on the >> impact this would have for the other use cases of docstrings. > > Whenever somebody overrides a method to do something different, the > inherited docstring will be insufficient (as in your ABC example) or > wrong. This, I would say, is the case most of the time when overriding > a base class method. When this happens, the language is committing an > error. It's hardly a *language* error if you, the developer, writes an incomplete or incorrect docstring. If you want to argue that the language shouldn't enable a failure mode of the developer (namely the use of an incomplete or incorrect docstring), well, perhaps you are right. But you are assuming that an inherited docstring is necessarily wrong, which is not the case. "Prints a shape", as in your above example, is a perfectly acceptable, if minimal, docstring. It might not be a *great* docstring, but it's not a wrong one. > Put it this way: if Python doesn't automatically inherit docstrings, the > worst that can happen is missing information. If Python does inherit > docstrings, it can lead to incorrect information. This is no different from inheriting any other attribute. If your class inherits "attribute", you might get an invalid value unless you take steps to ensure it is a valid value. This failure mode doesn't cause us to prohibit inheritance of attributes. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Thu, 09 Jun 2011 23:59:08 -0400, Terry Reedy wrote: > On 6/9/2011 9:12 PM, Carl Banks wrote: > >> Presumably, the reason you are overriding a method in a subclass is to >> change its behavior; I'd expect an inherited docstring to be inaccurate >> more often than not. So I'd be -1 on automatically inheriting them. >> >> However, I'd be +1 easily on a little help from the language to >> explicitly request to inherit the docstring. > > An empty docstring "" could be interpreted as 'ditto' ;-) It would be > useless otherwise. +1 Better than an decorator! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
On Fri, 10 Jun 2011 01:00:35 -0500, harrismh777 wrote: > So, be careful. I have had to separate *all* of my python installs on > *every* one of my systems for this similar reason. The bottom line is if > the distro ships with 2.6 (minus the idle) chances are that the > interpreter is there *not* to advocate for python explicitly, but > because the interpreter is being used by the system somewhere. If you > install 2.7 or 3.2 you need to be careful to *not* interfere with the > default setup. Yes. Never mess with the system Python unless you want to take full responsibility for fixing the system when it breaks :) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
On Fri, 10 Jun 2011 07:33:34 +1000, Ben Finney wrote: > Steven D'Aprano writes: >> It's an unnecessary restriction, as far as I'm concerned, but an old >> one. > > Well, it's incompatible with the Python compiler I keep in my head. Have > these developers no consideration for backward-thinking-compatibility? +1 QOTW -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Better logic for this problem..
On Thu, Jun 9, 2011 at 6:10 PM, Dan Stromberg wrote: > > On Thu, Jun 9, 2011 at 10:55 AM, geremy condra wrote: >> >> On Thu, Jun 9, 2011 at 4:38 AM, Dave Angel wrote: >> > On 01/-10/-28163 02:59 PM, Chris Rebert wrote: >> >> >> >> On Thu, Jun 9, 2011 at 1:31 AM, Ganapathy Subramanium >> >> wrote: >> >>> >> >>> Hi Guru's, >> >>> I'm working on a solution to find the prime factor of the number >> >>> This part of the code works.. http://www.pastie.org/2041584 >> >>> >> >>> When the number gets bigger, the range cannot iterate through bigger >> >>> number >> >>> and it does not work. >> >>> When I googled , I came across creating our own range function to >> >>> solve >> >>> this. I was just wondering if there was a better algorithm to get the >> >>> prime >> >>> numbers / prime factors of a long number? >> >>> >> >>> Any inputs is highly appreciated. >> >> >> > >> > Others have pointed out various inefficiencies. But I wanted to start by >> > asking what this is for. Do you really have a need to factor numbers >> > over 2 >> > billion? Repeatedly? In multiple runs of the program? Do you have >> > weeks >> > of computer time to spend or just hours? Are you really interested in >> > the >> > factors, or just whether or not a particular large number is prime >> > (==has >> > anyfactors) ? If this is a homework assignment, what's the exact >> > assignment? Are you permitted to use other libraries, or other >> > languages? >> > Are you permitted to use language features you haven't encountered yet >> > in >> > class? >> >> My solution: >> >> def factors(x): >> status, output = subprocess.getstatusoutput('factor %d' % x) >> if not status: >> return [int(i) for i in output.split()[1:]] >> else: >> print(output) >> >> Works pretty well. >> >> >> >> > So you should probably turn the problem around. Design a function that >> > calculates the nth prime, but that caches the work it's already done (on >> > disk if appropriate, but in a list if not). In the loop that's finding >> > the >> > factors, simply call the first function each time, and each time you >> > find a >> > factor, divide num by that so you're dealing with a smaller number. >> >> Just use a precomputed table to do your trial division. There's a list >> of the first fifty million primes on prime pages- if you aren't >> dealing with specially constructed values (ie, RSA moduli) and haven't >> found a factor by the end of the first ten thousand or so you probably >> need to do a primality check before moving on to trying to factor it. >> >> Geremy Condra >> -- >> http://mail.python.org/mailman/listinfo/python-list > > You Might be able to benefit from a primality test like Miller-Rabin, at > least if your numbers can be really large. It can answer with "this number > is definitely composite" or "this number is probably prime". For quite > large numbers, it might speed things up. For smaller numbers, trial > division is faster. > > I have a Python Miller-Rabin module at: > > http://stromberg.dnsalias.org/svn/big-prime/trunk/ Here's a non-gmpy randomized MR implementation: import random def miller_rabin(n, confidence=20): t, s, d = n-1, 0, 0 while not t % 2: t = t >> 1 s += 1 t, d = n-1, t for i in range(confidence): a = random.randrange(2, n) x = pow(a, d, n) if x == 1: continue if x == t: continue for r in range(1, s): x = pow(x, 2, n) if x == t: break if x == 1: return False else: return False return True -- http://mail.python.org/mailman/listinfo/python-list
Re: __doc__ immutable for classes (was: Re: how to inherit docstrings?)
Eric Snow wrote: But for "method" objects (really a wrapper for bound functions) would it change the __doc__ of the wrapper or of the bound function? You probably wouldn't want to change the __doc__ of a method wrapper; instead you'd make sure you got hold of the underlying function first. So __doc__ on method wrappers should probably remain read-only to avoid surprises. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Carl Banks wrote: x = random.choice([Triange(),Square()]) print x.draw.__doc__ # prints "Draws a shape" Quick, what shape is x.draw() going to draw? Your debugging code is insufficient. It should include print type(x) and then it will be obvious what shape is going to get drawn. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: how to inherit docstrings?
Carl Banks wrote: Presumably, the reason you are overriding a method in a subclass is to change its behavior; Not always true by any means, and maybe not even usually true. Consider overriding for the purpose of implementing an abstract method, or because something about the internal operation of a method needs to be modified to suit the requirements of the subclass. I have a lot of situations like this in PyGUI, where there is a bunch of generic classes defining the public API, and subclasses of them for each implementation (Cocoa, Gtk and Windows). There are heaps and heaps of overridden methods in the implementation classes, and very few of them need or should have a docstring different from the generic one. Not automatically inheriting the docstrings puts a big burden on the maintainer to keep all of them in sync. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.6 OR 3.2
On Thu, Jun 9, 2011 at 11:00 PM, harrismh777 wrote: > Andrew Berg wrote: >> >> AFAICT, there are three reasons to learn Python 2: > > ... there is a fourth reason. > > The linux distro you are using currently was customized with python 2.x > > I ran into this problem this week in fact... on my HP g6 ubuntu notebook > running 10.04 lucid. It ships with the 2.6.5 interpreter. I installed 2.7.1 > and 3.2 (from sources) and was working along happy as a clam until I needed > to configure a printer... and the config tools would not function... some of > them would not even open. Want to guess? Yup, the config tools are (some > of them) written in python 2.6-- and they don't run in 2.7.1 nor 3.2 . :( > > So, be careful. I have had to separate *all* of my python installs on > *every* one of my systems for this similar reason. The bottom line is if the > distro ships with 2.6 (minus the idle) chances are that the interpreter is > there *not* to advocate for python explicitly, but because the interpreter > is being used by the system somewhere. If you install 2.7 or 3.2 you need to > be careful to *not* interfere with the default setup. > > So, you will need to be able to use both. There is no getting around it... > but, I would start with 3.2 (seriously). Get 3.2 under your belt and then > when you need to, go back and deal with the 2.6 regression. > > 3.2 is better built, is more logically consistent (it really is, no > kidding), and has some new features that make it very attractive. The > down-side is that some (most) of the library support is still not there for > many projects. It will take some time, but it will happen. > > There's an altinstall make target that you're supposed to use in cases like this. It won't make the /usr/local/bin/python symlink (or whatever prefix you're using), just pythonx.y. This way, the programs that depend on "python" referring to a specific version will still continue to work and you can have your newer version. The Ubuntu packages that depend on the system Python+ system installed packages *should* be specifying /usr/bin/python specifically but as you can see, they don't always do that. > > kind regards, > m harris > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
help on QUICKFIX
Hi, I am using quickfix, would like to start with that ..\quickfix-1.13.3\quickfix\examples\executor\python\executor.py asks for a configuration file how should it look like. Thanks -- http://mail.python.org/mailman/listinfo/python-list