calculate difference between two timestamps [newbie]
I'm trying to calculate the difference in seconds between two timestamps, but I'm totally stuck: date1="Dec-13-09:47:12" date2="Dec-13-09:47:39" >>> diff=datetime.date(date2)-datetime.date(date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required struct_date1=time.strptime(date1, "%b-%d-%H:%M:%S") struct_date2=time.strptime(date2, "%b-%d-%H:%M:%S") >>> diff=datetime.date(struct_date2)-datetime.date(struct_date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required thanks in advance nukey -- http://mail.python.org/mailman/listinfo/python-list
Re: calculate difference between two timestamps [newbie]
On 12/17/2011 05:19 AM, nukeymusic wrote: I'm trying to calculate the difference in seconds between two timestamps, but I'm totally stuck: date1="Dec-13-09:47:12" date2="Dec-13-09:47:39" diff=datetime.date(date2)-datetime.date(date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required struct_date1=time.strptime(date1, "%b-%d-%H:%M:%S") struct_date2=time.strptime(date2, "%b-%d-%H:%M:%S") diff=datetime.date(struct_date2)-datetime.date(struct_date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required thanks in advance nukey You should post the full code; you omitted your import line(s) That last approach was closer, try this one: import datetime struct_date1=datetime.datetime.strptime(date1, "%b-%d-%H:%M:%S") struct_date2=datetime.datetime.strptime(date2, "%b-%d-%H:%M:%S") diff = struct_date2 - struct_date1 print diff diff is of type datetime.timedelta -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: calculate difference between two timestamps [newbie]
Le 17/12/11 11:19, nukeymusic a écrit : I'm trying to calculate the difference in seconds between two timestamps, but I'm totally stuck: date1="Dec-13-09:47:12" date2="Dec-13-09:47:39" diff=datetime.date(date2)-datetime.date(date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required struct_date1=time.strptime(date1, "%b-%d-%H:%M:%S") struct_date2=time.strptime(date2, "%b-%d-%H:%M:%S") diff=datetime.date(struct_date2)-datetime.date(struct_date1) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required thanks in advance nukey That's work: import datetime begin = datetime.datetime(2011, 12, 13, 9, 47, 12) today = datetime.datetime(2011, 12, 13, 9, 47, 39) dif = str(today - begin) print dif >>> 0:00:27 Regards -- Vincent V.V. Oqapy . Qarte+7 . PaQager -- http://mail.python.org/mailman/listinfo/python-list
Re: calculate difference between two timestamps [newbie]
On Sat, Dec 17, 2011 at 02:19:44AM -0800, nukeymusic wrote: > I'm trying to calculate the difference in seconds between two > timestamps, but I'm totally stuck: > date1="Dec-13-09:47:12" > date2="Dec-13-09:47:39" > >>> diff=datetime.date(date2)-datetime.date(date1) > Traceback (most recent call last): > File "", line 1, in > TypeError: an integer is required > > struct_date1=time.strptime(date1, "%b-%d-%H:%M:%S") > struct_date2=time.strptime(date2, "%b-%d-%H:%M:%S") > >>> diff=datetime.date(struct_date2)-datetime.date(struct_date1) > Traceback (most recent call last): > File "", line 1, in > TypeError: an integer is required You're trying to compare two time.struct_time types when they need to be datetime.datetime types. This will do the conversion for you: import datetime,time date1="Dec-13-09:47:12" date2="Dec-13-09:47:39" struct_date1=datetime.datetime(*time.strptime(date1, "%b-%d-%H:%M:%S")[:6]) struct_date2=datetime.datetime(*time.strptime(date2, "%b-%d-%H:%M:%S")[:6]) print struct_date2 - struct_date1 -- http://mail.python.org/mailman/listinfo/python-list
Re: calculate difference between two timestamps [newbie]
nukeymusic wrote: >I'm trying to calculate the difference in seconds between two [...] >>> import datetime >>> date1 = datetime.datetime.strptime("Dec-13-09:47:12", "%b-%d-%H:%M:%S") >>> date2 = datetime.datetime.strptime("Dec-13-09:47:39", "%b-%d-%H:%M:%S") >>> delta = date2 - date1 >>> delta_seconds = (delta.days * 60 * 60 * 24) + delta.seconds + >>> ((delta.microseconds + 50) / 100) For very big time differences you should consider to use the Decimal arithmetics (standard module Decimal) instead of integer arithmetics for the last line. If you are sure, that you don't use fractional seconds, you can omit the part with 'delta.microseconds'. Best regards, Günther -- http://mail.python.org/mailman/listinfo/python-list
Online Data Entry Jobs Without Investment http://ponlinejobs.yolasite.com/
Online Data Entry Jobs Without Investment http://ponlinejobs.yolasite.com/ -- http://mail.python.org/mailman/listinfo/python-list
Pythonification of the asterisk-based collection packing/unpacking syntax
This is a follow-up discussion on my earlier PEP-suggestion. Ive integrated the insights collected during the previous discussion, and tried to regroup my arguments for a second round of feedback. Thanks to everybody who gave useful feedback the last time. PEP Proposal: Pythonification of the asterisk-based collection packing/ unpacking syntax. This proposal intends to expand upon the currently existing collection packing and unpacking syntax. Thereby we mean the following related python constructs: head, *tail = somesequence #pack the remainder of the unpacking of somesequence into a list called tail def foo(*args): pass #pack the unbound positional arguments into a tuple calls args def foo(**kwargs): pass #pack the unbound keyword arguments into a dict calls kwargs foo(*args) #unpack the sequence args into positional arguments foo(**kwargs) #unpack the mapping kwargs into keyword arguments We suggest that these constructs have the following shortcomings that could be remedied. It is unnecessarily cryptic, and out of line with Pythons preference for an explicit syntax. One can not state in a single line what the asterisk operator does; this is highly context dependent, and is devoid of that ‘for line in file’ pythonic obviousness. From the perspective of a Python outsider, the only hint as to what *args means is by loose analogy with the C-way of handling variable arguments. The current syntax, in its terseness, leaves to be desired in terms of flexibility. While a tuple might be the logical choice to pack positional arguments in the vast majority of cases, it need not be true that a list is always the preferred choice to repack an unpacked sequence, for instance. Type constraints: In case the asterisk is not used to signal unpacking, but rather to signal packing, its semantics is essentially that of a type constraint. The statement: head, tail = sequence Signifies regular unpacking. However, if we add an asterisk, as in: head, *tail = sequence We demand that tail not be just any python object, but rather a list. This changes the semantics from normal unpacking, to unpacking and then repacking all but the head into a list. It may be somewhat counter-intuitive to think of this as a type constraint, since python is after all a weakly-typed language. But the current usage of askeriskes is an exception to that rule. For those who are unconvinced, please consider the analogy to the following simple C# code: var foo = 3; An ‘untyped‘ object foo is created (actually, its type will be inferred from its rhs as an integer). float foo = 3; By giving foo a type-constraint of float instead, the semantics are modified; foo is no longer the integer 3, but gets silently cast to 3.0. This is a simple example, but conceptually entirely analogous to what happens when one places an asterisk before an lvalue in Python. It means ‘be a list, and adjust your behavior accordingly’, versus ‘be a float, and adjust your behavior accordingly’. The aim of this PEP, is that this type-constraint syntax is expanded upon. We should be careful here to distinguish with providing optional type constraints throughout python as a whole; this is not our aim. This concept has been considered before, but the costs have not been found to out-weight the benefits. http://www.artima.com/weblogs/viewpost.jsp?thread=86641 Our primary aim is the niche of collection packing/unpacking, but if further generalizations can be made without increasing the cost, those are most welcome. To reiterate: what is proposed is nothing radical; merely to replace the asterisk-based type constraints with a more explicit type constraint. Currently favored alternative syntax: Both for the sake of explicitness and flexibility, we consider it desirable that the name of the collection type is used directly in any collection packing statement. Annotating a variable declaration with a collection type name should signal collection packing. This association between a collection type name and a variable declaration can be accomplished in many ways; for now, we suggest collectionname::collectiontype for packing, and ::collectionname for unpacking. Examples of use: head, tail::tuple = ::sequence def foo(args::list, kwargs::dict): pass foo(::args, ::kwargs) The central idea is to replace annotations with asteriskes by annotations with collection type names, but note that we have opted for several other minor alterations of the existing syntax that seem natural given the proposed changes. First of all, explicitly mentioning the type of the collection involved eliminates the need to have two symbols, * and **. Which variable captures the positional arguments and which captures the keyword arguments can be inferred from the collection type they model, mapping or sequence. The rare case of collections that both model a sequence and a mapping can either be excluded or handled by assigning precedence
Re: Help about Xlib Library in Python
On 16.12.2011 05:55, 阮铮 wrote: Hi, A question about Xlib Library in Python troubled me for several days and I finally found this email list. I hope someone could answer my question. I think it is easy for experienced user. I would like to write a small script to response my mouse click in root screen and write something in the terminal. My script is like this, but it does not work in my computer. from Xlib import X import Xlib.display def main(): display = Xlib.display.Display() root = display.screen().root root.change_attributes(event_mask= X.ButtonPressMask | X.ButtonReleaseMask) while True: event = root.display.next_event() print "1" if __name__ == "__main__": main() Any hints are welcome Thank you! Ruan zheng You haven't said *how* your script is not working and what distro/desktop-environment you use, but I suspect, that your script collides with the window manager. Most window managers occupy the root window for them self, and even display another window above the root window (for the wallpaper, the desktop icons, etc.), so your clicks never reach the root window, but whatever the window manager draws as the background. If you run your script in a plain and naked X "session" with nothing but an xterm *and no window manager*, your script will probably work. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help about Xlib Library in Python
On Saturday, December 17, 2011 11:22:32 PM UTC+8, Alexander Kapps wrote: > On 16.12.2011 05:55, 阮铮 wrote: > > Hi, > > > > A question about Xlib Library in Python troubled me for several days > > and I finally found this email list. I hope someone could answer my > > question. I think it is easy for experienced user. > > > > I would like to write a small script to response my mouse click in > > root screen and write something in the terminal. My script is like > > this, but it does not work in my computer. > > > > from Xlib import X > > import Xlib.display > > > > def main(): > > display = Xlib.display.Display() > > root = display.screen().root > > root.change_attributes(event_mask= > > X.ButtonPressMask | > > X.ButtonReleaseMask) > > while True: > > event = root.display.next_event() > > print "1" > > if __name__ == "__main__": > > main() > > > > > > Any hints are welcome > > Thank you! > > > > Ruan zheng > > > > You haven't said *how* your script is not working and what > distro/desktop-environment you use, but I suspect, that your script > collides with the window manager. > > Most window managers occupy the root window for them self, and even > display another window above the root window (for the wallpaper, the > desktop icons, etc.), so your clicks never reach the root window, > but whatever the window manager draws as the background. > > If you run your script in a plain and naked X "session" with nothing > but an xterm *and no window manager*, your script will probably work. Check co-linux and VNC and X-windows. It's trivial to play with PYTHON under co-linux. NT, WindowsXP, and Windows7 are excellent in the heap manager of a single process with multiple threads. Linux is multiple-process not multiple threads. Also the brain damaged heap walker is inferior to $$$MS. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sat, 17 Dec 2011 06:38:22 -0800, Eelco wrote: > One can not state in a single line what the asterisk > operator does; Multiplication, exponentiation, sequence packing/unpacking, and varargs. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
In article <4eeccabe$0$29979$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano wrote: > On Sat, 17 Dec 2011 06:38:22 -0800, Eelco wrote: > > > One can not state in a single line what the asterisk > > operator does; > > Multiplication, exponentiation, sequence packing/unpacking, and varargs. Import wildcarding? -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 4:14 AM, Roy Smith wrote: > Import wildcarding? That's not an operator, any more than it is when used in filename globbing. The asterisk _character_ has many meanings beyond those of the operators * and **. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Python install regression test fail
Here's a result from "make", "make test" of a fresh download of Python 2.7.2 on Linux 2.6.18-1.2239.fc5smp: 350 tests OK. 2 tests failed: test_os test_site 35 tests skipped: test_aepack test_al test_applesingle test_bsddb185 test_bsddb3 test_cd test_cl test_codecmaps_cn test_codecmaps_hk test_codecmaps_jp test_codecmaps_kr test_codecmaps_tw test_curses test_gdb test_gl test_imgfile test_kqueue test_linuxaudiodev test_macos test_macostools test_msilib test_ossaudiodev test_scriptpackages test_smtpnet test_socketserver test_startfile test_sunaudiodev test_timeout test_tk test_ttk_guionly test_urllib2net test_urllibnet test_winreg test_winsound test_zipfile64 3 skips unexpected on linux2: test_gdb test_tk test_ttk_guionly make: *** [test] Error 1 -bash-3.1$ Here are the fails: test_os test test_os failed -- Traceback (most recent call last): File "/var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.7.2/Lib/test/test_os.py", line 563, in helper self.check(getattr(os, f)) File "/var/www/vhosts/sitetruth.com/private/downloads/python/Python-2.7.2/Lib/test/test_os.py", line 572, in check self.assertEqual(e.errno, errno.EBADF) AssertionError: 25 != 9 (This test expected EBADF and got ENOTTY on making a bad file descriptor. Not clear why it got ENOTTY, but that's "Inappropriate IOCTL", as if the file descriptor number was in use but not valid for the test.) test_site test test_site crashed -- : [Errno 13] Permission denied: '/var/www/vhosts/sitetruth.com/.local' (That looks like a bug in the test suite. It shouldn't be storing into the user's home directory.) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Bug in multiprocessing.reduction?
You can see my all code below, theoritically that code should work I guess. But I keep getting this error: [SUBWARNING/MainProcess] thread for sharing handles raised exception : --- Traceback (most recent call last): File "/usr/lib/python2.7/multiprocessing/reduction.py", line 127, in _serve send_handle(conn, handle_wanted, destination_pid) File "/usr/lib/python2.7/multiprocessing/reduction.py", line 80, in send_handle _multiprocessing.sendfd(conn.fileno(), handle) OSError: [Errno 9] Bad file descriptor --- Do you see an error in my side, or is this a bug in Python? import multiprocessing as mp import logging import socket import time from random import randint from multiprocessing.reduction import reduce_socket, rebuild_socket logger = mp.log_to_stderr(logging.DEBUG) def worker(queue): while True: reduced_socket = queue.get() # This is the line where I get Bad file descriptor error: print reduced_socket[0](*reduced_socket[1]) if __name__ == '__main__': serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind(('',9090)) serversocket.listen(5) num_workers = 5 socket_queue = mp.Queue() worker_processes = [mp.Process(target=worker,args=(socket_queue,)) for i in range(num_workers)] for worker_process in worker_processes: worker_process.daemon = True worker_process.start() while True: client, address = serversocket.accept() client_handle = reduce_socket(client) socket_queue.put(client_handle) -- http://yasar.serveblog.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: % is not an operator [was Re: Verbose and flexible args and kwargs syntax]
On 2011-12-16, Gregory Ewing wrote: > Eelco wrote: >> the actual english usage of the phrase, which omits >> the negation completely :). (I could care less) > > No, that's the American usage. That's the _ignorant_ American usage. Americans with a clue use the "couldn't" version. I won't comment on the relative sizes of the two groups. > The English usage is "I couldn't care less", which has the advantage > of actually making sense. Indeed. -- Grant Edwards grant.b.edwardsYow! HUGH BEAUMONT died at in 1982!! gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Dec 17, 6:18 pm, Chris Angelico wrote: > On Sun, Dec 18, 2011 at 4:14 AM, Roy Smith wrote: > > Import wildcarding? > > That's not an operator, any more than it is when used in filename > globbing. The asterisk _character_ has many meanings beyond those of > the operators * and **. > > ChrisA To cut short this line of discussion; I meant the asterisk symbol purely in the context of collection packing/unpacking. Of course it has other uses too. Even that single use requires a whole paragraph to explain completely; when does it result in a tuple or a list, when is unpacking implicit and when not, why * versus **, and so on. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging issues
On Dec 13, 5:03 pm, Andrea Crotti wrote: > The set_verbosity seems to do its job, the second is also > called and the filters are added but I don't see the output > formatted as it should.. Generally speaking, you should only do logging configuration once, as Jean-Michel said - from your main() function or "if __name__ == '__main__'" suite. Until you show more detail about what you're getting and what you're expecting, it's hard to provide more help. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sat, 17 Dec 2011 12:11:04 -0800, Eelco wrote: > > One can not state in a single line what the asterisk > > operator does; ... > To cut short this line of discussion; I meant the asterisk symbol purely > in the context of collection packing/unpacking. Of course it has other > uses too. > > Even that single use requires a whole paragraph to explain completely; > when does it result in a tuple or a list, when is unpacking implicit and > when not, why * versus **, and so on. Do you think that this paragraph will become shorter if you change the spelling * to something else? It takes more than one line to explain list comprehensions, content managers, iterators, range(), and import. Why should we care if * and ** also take more than one paragraph? Even if you could get it down to a single line, what makes you think that such extreme brevity is a good thing? You might not be able to explain them in a single line, but you can explain them pretty succinctly: Varags: Inside a function parameter list, * collects an arbitrary number of positional arguments into a tuple. When calling functions, * expands any iterator into positional arguments. In both cases, ** does the same thing for keyword arguments. Extended iterator unpacking: On the left hand side of an assignment, * collects multiple values from the right hand side into a list. Let's see you do better with your suggested syntax. How concisely can you explain the three functions? Don't forget the new type coercions (not constraints, as you keep calling them) you're introducing. It boggles my mind that you complain about the complexity of existing functionality, and your solution involves *increasing* the complexity with more functionality. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
PyCon US 2012 sprints
Hi folks. Next March I'm planning to attend PyCon US (for the first time) and stay for the sprints. I am not sure how they work, however. Are there any "first-timer guide to PyCon sprints"? -- Ricardo Bánffy http://www.dieblinkenlights.com http://twitter.com/rbanffy -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sat, 17 Dec 2011 06:38:22 -0800, Eelco wrote: > Type constraints: > > In case the asterisk is not used to signal unpacking, but rather to > signal packing, its semantics is essentially that of a type constraint. "Type constraint" normally refers to type restrictions on *input*: it is a restriction on what types are accepted. When it refers to output, it is not normally a restriction, therefore "constraint" is inappropriate. Instead it is normally described as a coercion, cast or conversion. Automatic type conversions are the opposite of a constraint: it is a loosening of restrictions. "I don't have to use a list, I can use any sequence or iterator". In iterator unpacking, it is the *output* which is a list, not a restriction on input: in the statement: head, *tail = sequence tail may not exist before the assignment, and so describing this as a constraint on the type of tail is completely inappropriate. > The statement: > > head, tail = sequence > > Signifies regular unpacking. However, if we add an asterisk, as in: > > head, *tail = sequence > > We demand that tail not be just any python object, but rather a list. We don't demand anything, any more than when we say: for x in range(1, 100): we "demand" that x is not just any python object, but rather an int. Rather, we accept what we're given: in case of range and the for loop, we are given an int. In the case of extended tuple unpacking, we are given a list. > This changes the semantics from normal unpacking, to unpacking and then > repacking all but the head into a list. Aside: iterator unpacking is more general than just head/tail unpacking. >>> a, b, *var, c, d, e = range(10) >>> print(a, b, c, d, e, var) 0 1 7 8 9 [2, 3, 4, 5, 6] You are jumping to conclusions about implementation details which aren't supported by the visible behaviour. What evidence do you have that iterator unpacking creates a tuple first and then converts it to a list? > It may be somewhat counter-intuitive to think of this as a type > constraint, since python is after all a weakly-typed language. The usual test of a weakly-typed language is that "1"+1 succeeds (and usually gives 2), as in Perl but not Python. I believe you are confusing weak typing with dynamic typing, a common mistake. [...] > The aim of this PEP, is that this type-constraint syntax is expanded > upon. We should be careful here to distinguish with providing optional > type constraints throughout python as a whole; this is not our aim. Iterator unpacking is no more about type constraints than is len(). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Parsing stream of JSON objects incrementally
I'm interested in writing two programs, A and B, which communicate using JSON. At a high level, A wants to transfer an array to B. However, I would very much like to make it possible for A and B to run in parallel, so my current plan is to have A output and B read a *sequence* of JSON objects. In other words, instead of [ {"a": 0}, {"b":0}, {"c": 0} ] it would just send {"a": 0} {"b": 0} {"c": 0} I know about the raw_decode() object inside the json.JSONParser class, and that gets me most of the way there there. However, what I'm *not* sure about is the best way to get the input to the raw_decode() function, which expects a "string or buffer": >>> d = json.JSONDecoder() >>> d.raw_decode(sys.stdin) Traceback (most recent call last): ... File "json\scanner.py", line 42, in iterscan match = self.scanner.scanner(string, idx).match TypeError: expected string or buffer Now I'm not very familiar with the buffer and how it could be used (and whether a file or stdin could be used as one in an incremental fashion), but the best way I can come up with is the following: 1. Read a line of input 2. Try to decode it 3. If not, read another line, concatenate it to the end, and try again 4. etc. That seems... inelegant at least. Some other information: * I'm looking for a 2.7 solution ideally * I'd prefer not to use a different JSON library entirely * As suggested, I *am* willing to wait for a newline to do processing * However, I don't want to require exactly one object per line (and want to allow both multiple objects on one line and newlines within an object) Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: AttributeError in "with" statement (3.2.2)
On 12/16/2011 8:26 PM, Steven D'Aprano wrote: On Fri, 16 Dec 2011 17:05:57 -0500, Terry Reedy wrote: It is am important distinction [unbound versus bound] It is not an important distinction, and I am not confusing the two. So we agree on the distinction but disagree on its importance. Let us leave it at that. > Bound or unbound, it is still an instance method. OK. So 'instance method' is a bit ambiguous (more than I thought, or would prefer) in that it can refer to unbound methods, bounds methods, or both. So be it. and that a function defined inside a class is different from a function outside of a class. That, and your repetition of the same claim further on, is a insulting lie. If you can't assume I'm carrying on this discussion in good faith, If you can't assume that I am intelligent and experienced enough to know the meaning of def, one on the most basic aspects of Python, and you are unwilling to give me the benefit of any doubt you might have on that score, but instead go on to 'correct' me publicly, then no, I can't. Def statements always create functions. I have known that for 14 years since the first day I started with Python. I have never thought differently. If you actually think that I have, you are wrong. I'm glad to hear it. But nevertheless you have made statements (which I quoted, and you deleted from your reply) that suggest the opposite. OK, let us look at the my statement and your 'repetition of the same claim further on' that I previously deleted. I wrote >> These are bound methods. The instance methods are the functions wrapped. As I indicated in response to Ethan, I would now revised the second sentence now to "The unbound methods are the function wrapped" or "The instance-requiring methods are the functions wrapped." But that is not important here. In my opinion, there is no way that anyone reading that in good faith could conclude that I do not know the meaning of def statements. They are not the subject of discussion in that sentence or the rest of this thread. But in response you wrote. > I am afraid you are mistaken. About what? You go on to explain. > What you say may very well apply to other languages, > but in Python, def creates functions no matter where you > execute it. Always and without exception. So that makes twice that you said or implied that I think the location of a def statement changes what it creates, even though I explicitly said the opposite when I suggested that the glossary entry might be revised. What am I to think at such a tactic. You are normally much more careful in what you write. > If I have misinterpreted them, or if you had worded them badly, > there's no need to attribute malice to me. I did not do that. I gave my opinion of your statement, just as you have given your opinions of mine. I really did not and do not know why you misrepresented my knowledge of Python. I actually consider overt intentional malice much less likely than other possibilities. Calling me a liar I did not do that, any more than you have been calling me things. I believe you are asking for the same 'benefit of the doubt' that I believe you denied to me. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 11:59 AM, Steven D'Aprano wrote: > The usual test of a weakly-typed language is that "1"+1 succeeds (and > usually gives 2), as in Perl but not Python. I believe you are confusing > weak typing with dynamic typing, a common mistake. I'd go stronger than "usually" there. If "1"+1 results in "11", then that's not weak typing but rather a convenient syntax for stringification - if every object can (or must) provide a to-string method, and concatenating anything to a string causes it to be stringified, then it's still strongly typed. Or is a rich set of automated type-conversion functions evidence of weak typing? And if so, then where is the line drawn - is upcasting of int to float weak? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On 12/17/2011 20:45, Chris Angelico wrote: > I'd go stronger than "usually" there. If "1"+1 results in "11", then > that's not weak typing but rather a convenient syntax for > stringification - if every object can (or must) provide a to-string > method, and concatenating anything to a string causes it to be > stringified, then it's still strongly typed. > > Or is a rich set of automated type-conversion functions evidence of > weak typing? And if so, then where is the line drawn - is upcasting of > int to float weak? > > ChrisA Sorry, I just subscribed to the list so am stepping in mid-conversation, but "strong" vs "weak" typing does not have a particularly well-defined meaning. There are at least three very different definitions you'll find people use which are almost pairwise orthogonal in theory, if less so in practice. There's a great mail to a Perl mailing list I've seen [1] where someone lists *eight* definitions (albeit with a couple pairs of definitions that are only slightly different). I like to use it in the "automated conversion" sense, because I feel like the other possible definitions are covered by other terms (static/dynamic, and safe/unsafe). And in that sense, I think that thinking of languages as "strong" *or* "weak" is a misnomer; it's a spectrum. (Actually even a spectrum is simplifying things -- it's more like a partial order.) Something like ML or Haskell, which does not even allow integer to double promotions, is very strong typing. Something like Java, which allows some arithmetic conversion and also automatic stringification (a la "1" + 1) is somewhere in the middle of the spectrum. Personally I'd put Python even weaker on account of things such as '[1,2]*2' and '1 < True' being allowed, but on the other hand it doesn't allow "1"+1. Evan [1] http://groups.google.com/group/comp.lang.perl.moderated/msg/89b5f256ea7bfadb (though I don't think I've seen all of those) signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: root[:]=[root,root]
On 12/16/2011 9:40 PM, YAN HUA wrote: Hi,all. Could anybody tell how this code works? >>> root = [None, None] >>> root[:] = [root, root] >>> root [[...], [...]] >>> root[0] [[...], [...]] >>> root[0][0][1][1][0][0][0][1][1] [[...], [...]] A simpler example: >>> l = [] >>> l.append(l) >>> l [[...]] Python is (now) smart enough to recognize a recursive list and print '...' instead of going into an infinite loop printing '['s (as it once did, I believe). -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On 12/17/2011 21:03, Evan Driscoll wrote: > Personally I'd put Python even weaker on account of things such as > '[1,2]*2' and '1 < True' being allowed, but on the other hand it > doesn't allow "1"+1. Not to mention duck typing, which under my definition I'd argue is pretty much the weakest of typing that you can apply to structure-like types which I can think of. Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, 18 Dec 2011 13:45:35 +1100, Chris Angelico wrote: > On Sun, Dec 18, 2011 at 11:59 AM, Steven D'Aprano > wrote: >> The usual test of a weakly-typed language is that "1"+1 succeeds (and >> usually gives 2), as in Perl but not Python. I believe you are >> confusing weak typing with dynamic typing, a common mistake. > > I'd go stronger than "usually" there. If "1"+1 results in "11", then > that's not weak typing but rather a convenient syntax for > stringification - if every object can (or must) provide a to-string > method, and concatenating anything to a string causes it to be > stringified, then it's still strongly typed. For what it's worth, Wikipedia's article on type systems gives Javascript as an example of weak typing because it converts "1"+1 to "11". I agree with them. http://en.wikipedia.org/wiki/Type_system I think that weak and strong typing aren't dichotomies, but extremes in a continuum. Assembly languages are entirely weak, since everything is bytes and there are no types to check; some academic languages may be entire strong; but most real-world languages include elements of both. Most commonly coercing ints to floats. Chris Smith's influence article "What To Know Before Debating Type Systems" goes further, suggesting that weak and strong typing are meaningless terms. I don't go that far, but you should read his article: http://cdsmith.wordpress.com/2011/01/09/an-old-article-i-wrote/ > Or is a rich set of automated type-conversion functions evidence of weak > typing? And if so, then where is the line drawn - is upcasting of int to > float weak? To my mind, the distinction that should be drawn is that if two types are in some sense the same *kind* of thing, then automatic conversions or coercions are weak evidence of weak typing. Since we consider both ints and floats to be kinds of numbers, mixed int/float arithmetic is not a good example of weak typing. But since numbers and strings are quite different kinds of things, mixed str/int operations is a good example of weak typing. But not *entirely* different: numbers can be considered strings of digits; and non-digit strings can have numeric values. I don't know of any language that allows 1 + "one" to return 2, but such a thing wouldn't be impossible. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Newman's community structure algorithms
Hello, I am in need of the python or matlab implementation of following algorithms: Newman, M. E. J. 2006. Modularity and community structure in networks. PNAS 103(23): 8577-8582. Newman, M. E. J. and Leicht, E. A. 2007. Mixture models and exploratory analysis in networks. PNAS 104(23): 9564-9569. If anyone could share that or guide me to a possible source, I shall be immensely grateful. Best regards, --- Muhammad Shafique Ph.D. Fellow United Nations University, UNU-MERIT Keizer Kareplein 19, 6211 TC Maastricht The Netherlands http://www.merit.unu.edu/about/profile.php?id=1058-- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 2:03 PM, Evan Driscoll wrote: > Sorry, I just subscribed to the list so am stepping in mid-conversation, Welcome to the list! If you're curious as to what's happened, check the archives: http://mail.python.org/pipermail/python-list/ > Something like ML or Haskell, which does not even allow integer to > double promotions, is very strong typing. Something like Java, which > allows some arithmetic conversion and also automatic stringification (a > la "1" + 1) is somewhere in the middle of the spectrum. Personally I'd > put Python even weaker on account of things such as '[1,2]*2' and '1 < > True' being allowed, but on the other hand it doesn't allow "1"+1. But [1,2]*2 is operator overloading. The language doesn't quietly convert [1,2] into a number and multiply that by 2, it keeps it as a list and multiplies the list by 2. Allowing 1 < True is weaker typing. It should be noted, however, that "1 < True" is False, and "1 > True" is also False. The comparison doesn't make much sense, but it's not an error. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
In article <4eed5eef$0$29979$c3e8da3$54964...@news.astraweb.com>, Steven D'Aprano wrote: > some academic languages may be > entire strong; but most real-world languages include elements of both. > Most commonly coercing ints to floats. Early Fortran compilers did not automatically promote ints to floats. > But not *entirely* different: numbers can be considered strings of > digits; and non-digit strings can have numeric values. I don't know of > any language that allows 1 + "one" to return 2, but such a thing wouldn't > be impossible. It is possible for 1 + "one" to be equal to 2 in C or C++. All it takes is for the string literal to be located at memory location 1. Not likely, but nothing in the language prevents it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 2:59 PM, Roy Smith wrote: > It is possible for 1 + "one" to be equal to 2 in C or C++. All it takes > is for the string literal to be located at memory location 1. Not > likely, but nothing in the language prevents it. Not quite; 1 + "one" will be "ne", which might happen to be at memory location 2. The data type is going to be char* (or, in a modern compiler, const char*), not int. That said, though, I think that (in this obscure circumstance) it would compare equal with 2. For what that's worth. :) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Debugging a difficult refcount issue.
I'm getting a fatal python error "Fatal Python error: GC object already tracked"[1]. Using gdb, I've pinpointed the place where the error is detected. It is an empty dictionary which is marked as in-use. This is somewhat helpful since I can reliably find the memory address of the dict, but it does not help me pinpoint the issue. I was able to find the piece of code that allocates the problematic dict via a malloc/LD_PRELOAD interposer, but that code was pure python. I don't think it was the cause. I believe that the dict was deallocated, cached, and re-allocated via PyDict_New to a C routine with bad refcount logic, then the above error manifests when the dict is again deallocated, cached, and re-allocated. I tried to pinpoint this intermediate allocation with a similar PyDict_New/LD_PRELOAD interposer, but that isn't working for me[2]. How should I go about debugging this further? I've been completely stuck on this for two days now :( [1] http://hg.python.org/cpython/file/99af4b44e7e4/Include/objimpl.h#l267 [2] http://stackoverflow.com/questions/8549671/cant-intercept-pydict-new-with-ld-preload -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On 12/17/2011 21:42, Chris Angelico wrote: > Welcome to the list! If you're curious as to what's happened, check > the archives: > http://mail.python.org/pipermail/python-list/ Thanks! Incidentally, is there a good way to respond to the original post in this thread, considering it wasn't delivered to me? > But [1,2]*2 is operator overloading. The language doesn't quietly > convert [1,2] into a number and multiply that by 2, it keeps it as a > list and multiplies the list by 2. > > Allowing 1 < True is weaker typing. It should be noted, however, that > "1 < True" is False, and "1 > True" is also False. The comparison > doesn't make much sense, but it's not an error. I see where you're coming from, especially as I wouldn't consider overloading a function on types (in a language where that phrase makes sense) moving towards weak typing either. Or at least I wouldn't have before this discussion... At the same time, it seems a bit implementationy. I mean, suppose '1' were an object and implemented __lt__. Does it suddenly become not weak typing because of that? (The other thing is that I think strong vs weak is more subjective than many of the other measures. Is '1 < True' or '"1"+1' weaker? I think it has a lot to do with how the operations provided by the language play to your expectations.) On 12/17/2011 22:05, Chris Angelico wrote: > Not quite; 1 + "one" will be "ne", which might happen to be at memory > location 2. The data type is going to be char* (or, in a modern > compiler, const char*), not int. I'm not quite sure I'd say that it could be 2, exactly, but I definitely disagree with this... after running 'int x = 5, *p = &x' would you say that "p is 5"? (Assume &x != 5.) 1+"one" *points to* "ne", but it's still a pointer. Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
I like the spirit of this. Let's look at your examples. > Examples of use: > head, tail::tuple = ::sequence > def foo(args::list, kwargs::dict): pass > foo(::args, ::kwargs) My initial reaction was "nonono!", but this is simply because of the ugliness. The double-colon is very visually busy. I find that your second example is inconsistent with the others. If we say that the variable-name is always on the right-hand-side, we get: > def foo(list::args, dict::kwargs): pass This nicely mirrors other languages (such as in your C# example: "float foo") as well as the old python behavior (prefixing variables with */** to modify the assignment). As for the separator, let's examine the available ascii punctuation. Excluding valid variable characters, whitespace, and operators, we have: ! -- ok. " -- can't use this. Would look like a string. # -- no. Would looks like a comment. $ -- ok. ' -- no. Would look like a string. ( -- no. Would look like a function. ) -- no. Would look like ... bad syntax. , -- no. Would indicate a separate item in the variable list. . -- no. Would look like an attribute. : -- ok, maybe. Seems confusing in a colon-terminated statement. ; -- no, just no. ? -- ok. @ -- ok. [ -- no. Would look like indexing. ] -- no. ` -- no. Would look like a string? { -- too strange } -- too strange ~ -- ok. That leaves these. Which one looks least strange? float ! x = 1 float $ x = 1 float ? x = 1 float @ x = 1 The last one looks decorator-ish, but maybe that's proper. The implementation of this would be quite decorator-like: take the "normal" value of x, pass it through the indicated function, assign that value back to x. Try these on for size. head, @tuple tail = sequence def foo(@list args, @dict kwargs): pass foo(@args, @kwargs) For backward compatibility, we could say that the unary * is identical to @list and unary ** is identical to @dict. -buck -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 3:43 PM, Evan Driscoll wrote: > On 12/17/2011 21:42, Chris Angelico wrote: >> Welcome to the list! If you're curious as to what's happened, check >> the archives: >> http://mail.python.org/pipermail/python-list/ > Thanks! Incidentally, is there a good way to respond to the original > post in this thread, considering it wasn't delivered to me? I don't know of a way, but this works. It's all part of the same thread. > I mean, suppose '1' were an object and implemented > __lt__. Does it suddenly become not weak typing because of that? Is it weak typing to overload a function? //C++ likes this a lot. int foo(int x,int y) {return x*3+y;} double foo(double x,double y) {return x*3+y;} This is definitely making the term "strongly typed language" fairly useless. > (The other thing is that I think strong vs weak is more subjective than > many of the other measures. Is '1 < True' or '"1"+1' weaker? I think it > has a lot to do with how the operations provided by the language play to > your expectations.) +1. My expectations are: 1) The Boolean value "True" might be the same as a nonzero integer, or might not; it would make sense to use inequality comparisons with zero, MAYBE, but not with 1. So I don't particularly care what the language does with "1 < True", because it's not something that I would normally do. 2) "1"+1, in any high level language with an actual string type, I would expect to produce "11". It makes the most sense this way; having it return 2 means there's a special case where the string happens to look like a number - meaning that " 1"+1 is different from "1"+1. That just feels wrong to me... but I'm fully aware that many other people will disagree. Yep, it's pretty subjective. > On 12/17/2011 22:05, Chris Angelico wrote: >> Not quite; 1 + "one" will be "ne", which might happen to be at memory >> location 2. The data type is going to be char* (or, in a modern >> compiler, const char*), not int. > I'm not quite sure I'd say that it could be 2, exactly, but I definitely > disagree with this... after running 'int x = 5, *p = &x' would you say > that "p is 5"? (Assume &x != 5.) 1+"one" *points to* "ne", but it's > still a pointer. Point. I stand corrected. I tend to think of a char* as "being" the string, even though technically it only points to the beginning of it; it's the nearest thing C has to a string type. (To be honest, it's still a lot better than many high level languages' string types for certain common operations - eg trimming leading whitespace is pretty efficient on a PSZ.) In your example, p would be some integer value that is the pointer, but *p is 5. However, there's really no syntax in C to say what the "string value" is. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sun, Dec 18, 2011 at 3:52 PM, buck wrote: > The last one looks decorator-ish, but maybe that's proper. The implementation > of this would be quite decorator-like: take the "normal" value of x, pass it > through the indicated function, assign that value back to x. > > Try these on for size. > > head, @tuple tail = sequence > def foo(@list args, @dict kwargs): pass > foo(@args, @kwargs) That's reasonably clean as a concept, but it's not really quite the same. None of these examples is the way a decorator works; each of them requires a fundamental change to the way Python handles the rest of the statement. head, @tuple tail = sequence -- Does this mean "take the second element of a two-element sequence, pass it through tuple(), and store the result in tail"? Because, while that might be useful, and would make perfect sense as a decorator, it's insufficient as a replacement for current "*tail" syntax. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On 12/17/2011 22:52, buck wrote: > Try these on for size. > > head, @tuple tail = sequence > def foo(@list args, @dict kwargs): pass > foo(@args, @kwargs) > > For backward compatibility, we could say that the unary * is identical to > @list and unary ** is identical to @dict. > I like this idea much more than the original one. In addition to the arguments buck puts forth, which I find compelling, I have one more: you go to great length to say "this isn't really type checking in any sense" (which is true)... but then you go forth and pick a syntax that looks almost exactly like how you name types in many languages! (In fact, except for the fact that it's inline, the 'object :: type' syntax is *exactly* how you name types in Haskell.) buck's syntax still has some of the feel of "I wonder if this is type checking" to a newbie, but much much less IMO. I have a bigger objection with the general idea, however.It seems very strange that you should have to specify types to use it. If the */** syntax were removed, that would make the proposed syntax very very unusual for Python. I could be missing something, but I can think of any other place where you have to name a type except where the type is an integral part of what you're trying to do. (I would not say that choosing between tuples and lists are an integral part of dealing with vararg functions.) If */** were to stick around, I could see 99% of users continuing to use them. And then what has the new syntax achieved? You can fix this if you don't require the types and just allow the user to say "def foo(@args)" and "foo(@args)". Except... that's starting to look pretty familiar... (Not to mention if you just omit the type from the examples above you need another way to distinguish between args and kwargs.) I have one more suggestion. I do have one more thing to point out, which is that currently the Python vararg syntax is very difficult to Google for. In the first pages of the four searches matching "python (function)? (star | asterisk)", there was just one relevant hit on python.org which wasn't a bug report. I certainly remember having a small amount of difficulty figuring out what the heck * and ** did the first time I encountered them. This would suggest perhaps some keywords might be called for instead of operators. In the grand scheme of things the argument packing and unpacking are not *all* that common, so I don't think the syntactic burden would be immense. The bigger issue, of course, would be picking good words. This also helps with the issue above. Let's say we'll use 'varargs' and 'kwargs', though the latter too well-ingrained in code to steal. (I don't want to get too much into the debate over *what* word to choose. Also these don't match the 'head, *tail = l' syntax very well.) Then we could say: def foo(varargs l, kwargs d): bar(varargs l, kwargs d) and varargs would be equivalent to * and kwargs would be equivalent to **. But then you could also say def foo(varargs(list) l, kwargs(dict) d) Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On 12/17/2011 23:33, Evan Driscoll wrote: > I do have one more thing to point out, which is that currently the > Python vararg syntax is very difficult to Google for. In the first pages > of the four searches matching "python (function)? (star | asterisk)", > there was just one relevant hit on python.org which wasn't a bug report. Though in the interest of full disclosure, and I should have said this before, the first hit for all of those searches except "python star" *is* relevant and reasonably helpful; just from someone's blog post instead of "from the horse's mouth", so to speak. Evan signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonification of the asterisk-based collection packing/unpacking syntax
On Sat, 17 Dec 2011 23:33:27 -0600, Evan Driscoll wrote: > I do have one more thing to point out, which is that currently the > Python vararg syntax is very difficult to Google for. You're coming in late to the conversation, but that was literally the second thing pointed out by the original poster: On Sun, 11 Dec 2011 11:49:23 +0100, Eelco Hoogendoorn wrote: > Throwing an idea for a PEP out there: > > It strikes me that the def func(*args, **kwargs) syntax is rather > unpytonic. It certainly did not have that 'for line in file' > pythonic obviousness for me as a beginner. Plus, asterikses are > impossible to google for, so finding out what exactly they do more > or less forces you to write a forum post about it. And rebutted. Modesty[1] prevents me from quoting myself, but here are some links to searches: http://duckduckgo.com/?q=python+asterisk http://duckduckgo.com/?q=python+* My normal first place to look for something is Wikipedia. Enjoy it before SOPA kills it. http://en.wikipedia.org/wiki/Asterisk#Programming_languages > In the first pages > of the four searches matching "python (function)? (star | asterisk)", Your search looks overly complicated to me. I'm not an expert on Google's syntax, but if you search for "python, optionally with function", isn't that the same as just searching for "python" since it will return hits either with or without "function"? > I certainly remember having a small amount of difficulty figuring out > what the heck * and ** did the first time I encountered them. Answering that sort of question is what the interactive interpreter excels at. Suppose you see a function declared with *args as an argument, and you have no idea what it means. Try it and find out! py> def spam(*args): ... print(args, type(args)) ... py> spam(42) ((42,), ) py> spam(42, 23) ((42, 23), ) Never underestimate the power of Python's introspection tools, especially the two simplest ones: print and type. Often you will learn more in 10 minutes experimentation than in an hour googling. [1] Eh, who am I fooling? -- Steven -- http://mail.python.org/mailman/listinfo/python-list