Re: Explanation of this Python language feature? [x for x in x for x in x] (to flatten a nested list)
x = [[1, 2], [3, 4]] for x in x: ... for x in x: ... print(x) This is valid in the syntax level in python. But it is only good for those writing obscure programs in my opinions at most team works. -- https://mail.python.org/mailman/listinfo/python-list
Re: CallBack function in C Libraries.
On Friday, March 21, 2014 7:56:43 AM UTC+8, fiens...@gmail.com wrote: Give the function call its required argument and the error will go away... well, at least that one. Yep, many thanks for the answer. But... im totally beginner with Python. I develop in Pascal and C and want to understand the basics of Python. In concrete, what must i change in the code ? Many thanks. Python is a dynamical typed functional language with OOP supports in the revisons, and well suited in the giga-byte dram capacity personal toy era that can relplace her mother lisp's unrealized AI project . -- https://mail.python.org/mailman/listinfo/python-list
Re: How security holes happen
On Wednesday, March 5, 2014 8:52:31 AM UTC+8, Andrew Cooper wrote: On 03/03/2014 22:19, Cameron Simpson wrote: On 03Mar2014 09:17, Neal Becker ndbeck...@gmail.com wrote: Charles R Harris charlesr.har...@gmail.com Wrote in message: Imo the lesson here is never write in low level c. Use modern languages with well designed exception handling. What, and rely on someone else's low level C? Why is C the lowest denominator? Even with correctly written C and assembly, how can you be sure that your processor is executing the SYSRET instruction safely? (CVE-2012-0217 for anyone interested) ~Andrew It is not difficult to write C with mixed assembly codes for different CPUs. #ifdef ASM /* asm follows */ #ifdef CPUTYPES /* insert CPU ASMS for different CPUs carefully here */ -- https://mail.python.org/mailman/listinfo/python-list
Re: Python programming
On Thursday, February 13, 2014 11:30:27 PM UTC+8, Neil Cerutti wrote: On 2014-02-12, Tim Delaney timothy.c.dela...@gmail.com wrote: OK - it's degenerated into one of these threads - I'm going to participate. Me, too! I wrote lots of programs, strictly for fun, on every personal computer I got my hands on. Toward the end of the 80's personal computer's stopped coming equipped with programming environments, and I stopped programming. I eventually learned some computing theory in college where they taught C and the rudiments of C++. Thanks to the open-source movement we've returned to the days when anybody can program for zero cash. You can program well enough to amuse yourself with very little effort indeed. To get from there to being able to write programs to do useful things for yourself is a lot harder, but this is the niche that Python fills excellent well. If this is what you want to do, Python is a good way to go. That's still just the beginning, but it's a pretty good place. -- Neil Cerutti I wrote programs for viewing gif, pcx, bmp, and jpg images in 1991 to 1992. Also I was planning to write an Lotus123 clone at the time, but I was too lazy to chunk out that project in 1993. -- https://mail.python.org/mailman/listinfo/python-list
Re: Functional programming
On Monday, March 3, 2014 10:08:11 PM UTC+8, Rustom Mody wrote: On Monday, March 3, 2014 7:30:17 PM UTC+5:30, Chris Angelico wrote: On Tue, Mar 4, 2014 at 12:48 AM, Rustom Mody wrote: ? [1,2] + [[3,4],[5]] ERROR: Type error in application *** expression : [1,2] + [[3,4],[5]] *** term : [1,2] *** type : [Int] *** does not match : [[Int]] IOW [1,2,[3,4],[5]] is a type-wise ill-formed expression just as in python [[1,2]) is syntax-wise ill-formed Is it worth having such a restriction? Thats a different argument... How do you know that [1,2] is a list that must contain nothing but integers? By extension, it's also a list that must contain positive integers less than three, so adding [5] violates that. And [] is a list that must contain nothing, ergo it can't be added to, although (since it contains nothing) it can be added to anything. If 'integer-less-than-3' were a type then yes there would be this problem. More generally, if types could overlap then automatic type-inference is impossible Whether all thats good is as I earlier said a different argument The OP asked about FP and so its appropriate to mention how python's and standard FPL's choices differ OK, lets talk about the real meats of high-level dynamical typed languages. Test the claim that the old OOP programs and modules can use the new objects and programs written or obtained later in the run time. -- https://mail.python.org/mailman/listinfo/python-list
Re: Can tuples be replaced with lists all the time?
On Sunday, February 23, 2014 12:06:13 PM UTC+8, Sam wrote: My understanding of Python tuples is that they are like immutable lists. If this is the cause, why can't we replace tuples with lists all the time (just don't reassign the lists)? Correct me if I am wrong. == OK, lets be serious about high-level programming lnguages. Python is a dynamical typed ( name binding mechnism implicitly), imperative language with the built in auto GC and the heap plus stack managements in the bundled scriptor. A tuple is treated immutable and a list is mutable in Python. I suggest one can read the introductions about Erlang which is a non-imperative high level language in the 5 to 6 th gen programming languages in back-end server applictions for the robustness and maintainence costs. Neverthless, Python is regarded as a programming firendly language when comparing with other high level languages. -- https://mail.python.org/mailman/listinfo/python-list
Re: Commonly-used names in the Python standard library
On Friday, February 21, 2014 12:26:00 AM UTC+8, Marko Rauhamaa wrote: Chris Angelico ros...@gmail.com: Also, what happens if two modules (one of which might be your script) written for different versions both import some third module? Should they get different versions, based on what version tags they use themselves? Compatibility can't be changed that easily. You either run on the new version, or run on the old. Not both. Shared C libraries face the exact same issue. Java seems pretty good on this front as well. When there is a will, there is a way. Marko Well, please check jython first under OS Andrioids( LINUX+JAVA-XWIN). The mobile phone SW applications are getting hoter and hoter these days. -- https://mail.python.org/mailman/listinfo/python-list
Re: Calculator Problem
On Monday, February 3, 2014 5:16:44 AM UTC+8, Charlie Winn wrote: Hey Guys i Need Help , When i run this program i get the 'None' Under the program, see what i mean by just running it , can someone help me fix this def Addition(): print('Addition: What are two your numbers?') 1 = float(input('First Number:')) 2 = float(input('Second Number:')) print('Your Final Result is:', 1 + 2) def Subtraction(): print('Subtraction: What are two your numbers?') 3 = float(input('First Number:')) 4 = float(input('Second Number:')) print('Your Final Result is:', 3 - 4) def Multiplication(): print('Multiplication: What are two your numbers?') 5 = float(input('First Number:')) 6 = float(input('Second Number:')) print('Your Final Result is:', 5 * 6) def Division(): print('Division: What are your two numbers?') 7 = float(input('First Number:')) 8 = float(input('Second Number:')) print('Your Final Result is:', 7 / 8) print('What type of calculation would you like to do?') Question = input('(Add, Subtract, Divide or Multiply)') if Question.lower().startswith('a'): print(Addition()) elif Question.lower().startswith('s'): print(Subtraction()) elif Question.lower().startswith('d'): print(Division()) elif Question.lower().startswith('m'): print(Multiplication()) else: print('Please Enter The First Letter Of The Type Of Calculation You Would Like To Use') while Question == 'test': Question() I suggest just get an input string of the valid python expression type first. Then just use exec and _ or eval to get the result. -- https://mail.python.org/mailman/listinfo/python-list
Re: Using a static library in a C extension for Python
On Thursday, January 23, 2014 3:22:52 AM UTC+8, lgabiot wrote: Le 22/01/14 18:31, 8 Dihedral a écrit : Check the C source code generated by Pyrex and check cython for what u want, but I did try that out in any mobile phone or flat panel programming. Thanks a lot for your answer. I didn't use Pyrex or other tool, but wrote myself the C python wrapping, using the Python C/API documentation (http://docs.python.org/2/c-api/). I then used the distutils tool (via a setup.py file) to build my extension. While there is several function in my C code, only one needed to be accessed by python. I'll check Cython then, but is there any tweaking of the setup.py file using distutils that will help me compile the extension with the cairo lib embedded into it? There are some design concerns in writing python scripts that might be modified for fast execution speeds in some platforms. Well, reducing basic operation overheads in well factored critical parts does help in getting the desired results faster. -- https://mail.python.org/mailman/listinfo/python-list
Re: SIngleton from __defaults__
On Thursday, January 23, 2014 12:37:36 AM UTC+8, Asaf Las wrote: On Wednesday, January 22, 2014 6:18:57 PM UTC+2, Chris Angelico wrote: On Thu, Jan 23, 2014 at 3:07 AM, Asaf Las r@gmail.com wrote: Why not simply: def get_singleton(x = SomeClass()): return x Or even: singleton = SomeClass() ? Neither of the above provides anything above the last one, except for late creation. ChrisA Actually need was to have some interface to running independent threads to give same and once created object always. For first - SomeClass's object will be created whenever there will be call to get_singleton(). For second, again it is free to create it whenever someone (thread) wish. Hmmm, use case was to create persistent counter in multithreaded app accessing single file where incrementing integer is stored. When my imagination expanded it onto multiprocessing mess i ended up using sqlite access to DB in exclusive transaction mode. But this was not pythonic :-) Asaf In a high level language such as Python, functions and class initilizers are the first class objects. Don't you get the proof? Everyting OOP is equivalent to everything functional but it is much trivial to debug by the designer than the old grandma lisp. -- https://mail.python.org/mailman/listinfo/python-list
Re: Using a static library in a C extension for Python
On Wednesday, January 22, 2014 7:01:50 PM UTC+8, lgabiot wrote: Hello, working on OS X 10.8.5 Python 2.7 I've written a simple C extension for Python that uses the cairo graphic library. It works well, and I can call it from Python with no problem. The only drawback is that I need to have the cairo library installed on my system (so it seems my extension calls dynamically the cairo library). I believe this because it doesn't work on a system where cairo is not installed. Is it possible to link statically cairo to my extension, so that even if cairo is not installed on a computer, the code will run? I guess I would need to modify the setup.py file using distutils to compile cairo statically into my .so file? Or am I completely wrong? If someone has a hint... thanks! Check the C source code generated by Pyrex and check cython for what u want, but I did try that out in any mobile phone or flat panel programming. -- https://mail.python.org/mailman/listinfo/python-list
Re: Editor for Python
On Friday, November 23, 2001 6:43:40 AM UTC+8, MANUEL FERNANDEZ PEREZ wrote: Hello, I'm looking for an editor for Python.I' m interested it works on Windows.Can anybody help me? Thank you Manuel OK, try the notepad++ at notepad-plus-plus.org/ or use IDLE with the pycrust. -- https://mail.python.org/mailman/listinfo/python-list
Re: Newbie question. Are those different objects ?
On Saturday, December 21, 2013 1:10:37 AM UTC+8, rusi wrote: On Friday, December 20, 2013 9:30:22 PM UTC+5:30, Mark Lawrence wrote: On 20/12/2013 15:34, rusi wrote: On Friday, December 20, 2013 8:46:31 PM UTC+5:30, dec...@msn.com wrote: y = raw_input('Enter a number:') print type y y = float(raw_input('Enter a number:')) print type y I'm assuming that y is an object. I'm also assuming that the second and the first y are different objects because they have different types. Well, in Python the assignment operation = of a variable named y in the LHS to the object of the RHS result is more complicated than = in those register basd low level languages designed for fast execution speeds in compiled machine codes without an auto GC bundled with the interpreter in the run time. -- https://mail.python.org/mailman/listinfo/python-list
Re: Experiences/guidance on teaching Python as a first programming language
Roy Smith於 2013年12月19日星期四UTC+8下午12時16分26秒寫道: In article 07c6e6a3-c5f4-4846-9551-434bdaba8...@googlegroups.com, rusi rustompm...@gmail.com wrote: Soon the foo has to split into foo1.c and foo2.c. And suddenly you need to understand: 1. Separate compilation 2. Make (which is separate from 'separate compilation') 3. Header files and libraries and the connection and difference None of that is specific to C. Virtually any language (including Python) allows a program to be split up into multiple source files. If you're running all but the most trivial example, you need to know how to manage these multiple files and how the pieces interact. It's pretty common here to have people ask questions about how import works. How altering sys.path effects import. Why is import not finding my module? You quickly get into things like virtualenv, and now you've got modules coming from your source tree, from your vitualenv, from your system library. You need to understand all of that to make it all work. OK, just any novice can take the BOA and WXPYTHON packages to implement an editor in 1 to 3 hours, but that is trivial in Delphi and object pascal long time ago. The GUI to python scrit generation engine is the smarter way to let the mass interested in programming. -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] trying socket as a replacement for nc
8 Dihedral dihedral88...@gmail.com wrote: It is trivial to use UDP with forward error correction such as the CD in 1982. CD uses Reed-Solomon coding, which is great for correcting the types of errors expected on a CD. Namely, bursts of bit errors caused by localized failure of the optical coating, scratches, dirt, etc. It Don't you interleave your bytes of data first before forming several UDP packets to send to the receiver? If a whole packet is lost or timed out, then just mark missed bytes in the missed UDP as erasures. wouldn't be hard to build something like that on top of UDP, but those sorts of errors are not what you typically see in networks. It's relatively rare for a bit to get corrupted in a network packet. And, when it does, it's almost certainly caught by lower-level mechanisms such as ethernet frame CRC. Much more likely is for a packet to get dropped because of queue overflow, or for sequential packets to arrive out of order due to multiple transmission paths with different latencies. Those are the sorts of things TCP protects against. Sure, you could implement retransmit timers and packet reordering in user code, but it would be distinctly non-trivial and ultimately you would end up reinventing most of TCP. Except that your implementation would suck compared to the kernel algorithms which have been continuously tested and fine-tuned for the past 30 years. -- https://mail.python.org/mailman/listinfo/python-list
Re: Need Help with the BeautifulSoup problem, please
On Monday, December 16, 2013 2:41:08 PM UTC+8, seas...@gmail.com wrote: I need to replace all tag b with span after ■. But the result from below is '■ span style=REPLACED/span / font/font' Can you explain what I did wrong, please. s = '■bA/b bB/b bC/b bD/b / font/font' soup = BeautifulSoup(s) for i in soup.find_all(text='■'): tag = soup.new_tag('span') tag['style'] = 'REPLACE' for ii in i.find_next_siblings(): if ii.name=='font' or str(ii).lstrip('')[0:1]=='/': break else: if ii.name=='b': tag.string=ii.string print(ii.replace_with(tag)) print(soup) I think you should try some descent free editors such as notepad++ for your source codes to replace trivial strings without programmig. -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] trying socket as a replacement for nc
On Friday, December 13, 2013 5:58:49 AM UTC+8, Chris Angelico wrote: On Fri, Dec 13, 2013 at 8:27 AM, Dan Stromberg drsali...@gmail.com wrote: On Thu, Dec 12, 2013 at 6:16 AM, Grant Edwards invalid@invalid.invalid wrote: Sockets reserve the right to split one socket.send() into multiple socket.recv()'s on the other end of the communication, or to aggregate multiple socket.send()'s into a single socket.recv() - pretty much any way the relevant IP stacks and communications equipment feel like for the sake of performance or reliability. Just to be pedantic: _TCP_ sockets reserver that right. UDP sockets do not, and do in fact guarantee that each message is discrete. [It appears that the OP is undoubtedly using TCP sockets.] I haven't done a lot of UDP, but are you pretty sure UDP can't at least fragment large packets? What's a router or switch to do if the Path MTU isn't large enough for an original packet? http://www.gamedev.net/topic/343577-fragmented-udp-packets/ I'm no expert on this (mostly I do TCP, or UDP with fairly small packets), but the packet should be reassembled at the far end. When your application comes to receive it, it'll receive the entire UDP packet as a whole. UDP fragmentation has several problems. First, if any fragment is lost, it won't be retransmitted (as TCP will), so the whole datagram is lost. And secondly, if you stream data across the network in a series of packets just a little too large to fit, each one will get split in two and you'll end up with twice as many packets going out, ergo abysmal performance. With TCP, there's the chance that the sender and receiver can between them figure out what packet size to use (cf path MTU discovery), but that won't happen with UDP unless the application consciously does it. So it's something to be cautious of in terms of performance, but if you want to send large UDP packets because they make sense, just go ahead and do it. Now, if you want reliability AND datagrams, it's a lot easier to add boundaries to a TCP stream (sentinel or length prefixes) than to add reliability to UDP... ChrisA It is trivial to use UDP with forward error correction such as the CD in 1982. -- https://mail.python.org/mailman/listinfo/python-list
Re: GUI:-please answer want to learn GUI programming in python , how should i proceed.
On Saturday, December 14, 2013 8:12:16 PM UTC+8, Jai wrote: GUI:-want to learn GUI programming in python , how should i proceed. There are lots of book here so I am confuse which book i should refer so that i don't waste time . please answer Please check JYTHON and those ready-for-novice GUI tools in java. Python is a higher level language that can support manny lower level languages. -- https://mail.python.org/mailman/listinfo/python-list
Re: Languages for different purposes (was Re: New user's initial thoughts / criticisms of Python)
On Sunday, November 10, 2013 4:56:38 PM UTC+8, Jorgen Grahn wrote: On Sun, 2013-11-10, Chris Angelico wrote: On Sun, Nov 10, 2013 at 11:41 AM, Roy Smith r...@panix.com wrote: On 09/11/2013 22:58, Chris Angelico wrote: * Some languages are just fundamentally bad. I do not recommend ever writing production code in Whitespace, Ook, or Piet. One of the worst coding experiences I ever had was trying to build an app for a Roku media player. They have a home-grown language called BrightScript. Barf. And this is exactly why I was so strongly against the notion of developing an in-house scripting language. It may be a lot of work to evaluate Lua, Python, JavaScript, and whatever others we wanted to try, but it's a *lot* less work than making a new language that actually is worth using. Yes. I am baffled that people insist on doing the latter. Designing a limited /data/ language is often a good idea; designing something which eventually will need to become Turing-complete is not. Python is designed with the VM interpreter to execute compiled byte codes. Of course, C/C++/JAVA are lower level languages not designed in this way. To remedy the efficient part, cython and C-extensions are available in Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: Basic Python Questions - Oct. 31, 2013
On Tuesday, November 5, 2013 1:22:05 PM UTC+8, E.D.G. wrote: Jim Gibson jimsgib...@gmail.com wrote in message news:031120131018099327%jimsgib...@gmail.com... One way to generate plot within a CGI program is this: To start off with, I am not a CGI expert. Also, I have several degrees in the physical sciences and many years of doing computer programming. But the programming work is done just to get various science projects to work. The question that I could not get an answer for was, “How can you get Gnuplot to run on an Internet server computer?” And I would eventually have to ask that same question for Python. My Internet Server looks like it has Perl, Perl5, and PHP available. And I have created a number of CGI Perl programs that run on the Web site. But as I said, I would not know how to get Gnuplot or Python to run at the site. Any recommendations for how to do that? Or should I just do a search for the necessary documentation? Please try modpy. -- https://mail.python.org/mailman/listinfo/python-list
Re: Show off your Python chops and compete with others
On Friday, November 8, 2013 3:02:10 AM UTC+8, jsk...@gmail.com wrote: We do not currently support cookieless or javascript-less browsing. We are definitely looking at relying less and less on cookies, but it's unlikely we'll ever be able to pull out javascript as it limits interactivity too much. Its definitely possible to do, and maybe something we can look at in the future, but right now we don't have the resources for that. Sorry for the inconvenience! - Jonathan Kirst Lead Engineer at MetaBright On Wednesday, November 6, 2013 7:19:23 PM UTC-8, Tim Chase wrote: On 2013-11-06 17:31, John Nagle wrote: MetaBright makes skill assessments to measure how talented people are at different skills. And recruiters use MetaBright to find outrageously skilled job candidates. With tracking cookies blocked, you get 0 points. And with JavaScript blocked, you get bupkis. :-) I was amused that the sidebar of similar challenges suggested that the Python challenge might be similar to this one. Ya think? So similar that even the URL is the same... -tkc That is easy. Please use FireFox plus NoScript to achieve what you want. -- https://mail.python.org/mailman/listinfo/python-list
Re: Hyper-spacial ray-tracer
On Saturday, October 5, 2013 8:17:52 AM UTC+8, Rouslan Korneychuk wrote: On 10/04/2013 04:23 PM, Tony the Tiger wrote: On Wed, 02 Oct 2013 17:05:32 -0400, Rouslan Korneychuk wrote: game Sorry, but that sounds awful. I hate games. This... isn't a game or even related to gaming. Is it because of the use of Pygame that you thought it was. I use Pygame because it's a wrapper for SDL, which gives you cross-platform graphics, input and even thread support, and because the additional drawing and font modules are useful for prototyping and implementing user-interfaces for navigating higher-dimensional space. The point of this was to explore the concept of hyperspace, which is a mathematical curiosity and also has relevance in theoretical physics. One idea I had for this was to simulate some sort of 3D scene involving physics (probably in another program, such as Blender), take the resulting coordinates of the geometry at every time interval and plot it as one 4D static scene. Every pair of connected vertexes would be extruded from one instant in time, to the next, so each object is a continuous 4D extrusion. When viewing with your local XYZ axes aligned with the global XYZ axes, you would see one instant of the scene as normal. Moving along the fourth axis, which I'll call T, will let you see the same, earlier or later in time, but if you rotate parallel to the T axis, you will effectively replace one of X, Y or Z with T. In essence you will turn the time axis into a spacial axis and the spacial axis into a time axis. Looking at a scene with space and time lumped into one 4D space might help in trying to better understand time, why it's different, and its relationship with space. I was also wondering about general relativity. I'm not going to go into too much detail, but basically: if an object with synchronized clocks on either end of it, passes by a static observer while traveling near the speed of light, to the outside observer, the object will appear shorter and the clocks will appear desynchronized, and from the object's perspective, it is the outside observer that becomes distorted this way. I was wondering if this seemingly strange effect is actually the natural consequence of a simple geometric transformation, such as rotation into the time axis. Use the synchronous digital logics with a globbal clock by iterators of various actions for this kind of projects in Python. Please check myHDL and Python. auto- -- https://mail.python.org/mailman/listinfo/python-list
Re: Tail recursion to while iteration in 2 easy steps
On Thursday, October 3, 2013 5:33:27 AM UTC+8, Terry Reedy wrote: On 10/2/2013 8:31 AM, random...@fastmail.us wrote: On Tue, Oct 1, 2013, at 17:30, Terry Reedy wrote: Part of the reason that Python does not do tail call optimization is that turning tail recursion into while iteration is almost trivial, once you know the secret of the two easy steps. Here it is. That should be a reason it _does_ do it - saying people should rewrite their functions with loops means declaring that Python is not really a multi-paradigm programming language but rather rejects functional programming styles in favor of imperative ones. It is true that Python does not encourage the particular functional style that is encouraged by auto optimization of tail recursion. A different functional style would often use reduce (or fold) instead. Some other points I left out in a post of medium length yet brief for the topic. 1. If one starts with body recursion, as is typical, one must consider commutativity (possibly associativity) of the 'inner' operator in any conversion. 2. Instead of converting to tail recursion, one might convert to while iteration directly. 3. One often 'polishes' the while form in a way that cannot be done automatically. 4. While loops are actually rare in idiomatic Python code. In Python, for loops are the standard way to linearly process a collection. The final version I gave for a factorial while loop, def fact_while(n): if n 0 or n != int(n): raise ValueError('fact input {} is not a count'.format(n)) fac = 1 while n 1: fac *= n n -= 1 return fac should better be written with a for loop: As I pointed out before, an accelerated version without the limit of the stack depth for computing facotrials can be obtained by storing a list of products of primes first. Of course integer divisions are required to transform the to stack depth problem into the size of the 32-64 bit heap space. -- https://mail.python.org/mailman/listinfo/python-list
Re: class implementation
On Tuesday, October 1, 2013 3:34:08 AM UTC+8, Dave Angel wrote: On 30/9/2013 08:41, markot...@gmail.com wrote: under variables, i mean, the int's and lists and strings and floats that the parent class uses. IF in parent class there is variable called location, then can i use the same variable in my sub class. Python doesn't actually have variables, but the things it documents as variables are local names within a method. Those are not visible outside of the method, regardless of whether you're in a class or a subclass. But perhaps you mean attributes. There are both class attributes and instance attributes, and the behavior is quite different. Roughly speaking a class attribute occurs only once per class, and all code can read its value with either Class.my_attrib or instance.my_attrib. It can be written with Class.my_attrib. On the other hand, instance attributes are usable by instance.my_attrib, regardless of whether the instance is a base class An instance is an object of some class that could have its own attributes i.e. instance priviate properties during the run time. or a child class. Each instance of the class gets a separate copy of such an attribute. They are normally defined in the __init__() method. If you don't happen to know the difference between a class an an instance of that class, then all the above will look like gibberish, and you need to do some studying first. -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: How to execute command on remote windows machine
gauran...@gmail.com於 2013年9月3日星期二UTC+8下午12時45分57秒寫道: Hi Guys, I have a requirement where i need to kill one process on remote windows machine. Following command just works fine if i have to kill process on local machine os.system('taskkill /f /im processName.exe') However I am not able to figure out how to execute this command on remote windows machine. Note: my local machine is also windows (machine from where i have to execute command) so is there any way i can execute command from windows machine on remote windows machine ? This is trivial. First install the VNC on the remote site and make sure your VNC is working in the proper forground. Just write a mouse/keyboard emulator service on the remote site with the propper port opened by python scripts. Use the control computer to send commands to the remote site. This scheme will work under unix-linux-windows OS. -- https://mail.python.org/mailman/listinfo/python-list
Re: Encapsulation unpythonic?
Fabrice Pombet於 2013年8月31日星期六UTC+8上午1時43分28秒寫道: On Saturday, August 17, 2013 2:26:32 PM UTC+2, Fernando Saldanha wrote: I am new to Python, with experience in Java, C++ and R. As I understand encapsulation is not a big thing in the Python world. I read that you can put two underscores before the name of a variable within a class declaration but in the many examples of code I looked at this is not widely used. I also read that encapsulation is unpythonic. Questions: 2) If it is in fact true that encapsulation is rarely used, how do I deal with the fact that other programmers can easily alter the values of members of my classes? Fernando, it is widely accepted that Python pays very little attention to encapsulation as a principle set in stone. Chaz's definition of encapsulation is also mine. Now you need to consider that taking this principle off the hostel of OOP does not mean that you can do whatever you fancy and you can't make anything unsettable. There are plenty of techniques within Python that allow you to protect your arguments (in particular, decorators) inside a Class. Now, lets get to the pretentious philosophical discussion: I guess encapsulation is quite the opposite of, say, dynamic typing, which is arguably core in Python. In practice this allows Python to be less verbose: at the end of the day, if you look back at your previous languages, don't you find that some of their compulsory features are usually more of a pain than something useful in practice? And after all, whither encapsulation? Can't we just have objects whose arguments are determined externally if we want to? And that is the ballgame: as my old tutor says: the claptrap of setters and getters does not need to be here if it is unnecessary. I would add: so long as you can have them when you deem it necessary, and Python allows that. The way to perform encapsulation in Python can be achieved by writing methods in C to be compiled as an extension which can be used by all instances of some classes in the upper level. CYTHON is easy to be used for the job. -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module Performance
Devyn Collier Johnson於 2013年7月16日星期二UTC+8下午6時30分33秒寫道: Am 07/12/2013 07:16 PM, schrieb MRAB: On 12/07/2013 23:16, Tim Delaney wrote: On 13 July 2013 03:58, Devyn Collier Johnson devyncjohn...@gmail.com mailto:devyncjohn...@gmail.com wrote: Thanks for the thorough response. I learned a lot. You should write articles on Python. I plan to spend some time optimizing the re.py module for Unix systems. I would love to amp up my programs that use that module. If you are finding that regular expressions are taking too much time, have a look at the https://pypi.python.org/pypi/re2/ and https://pypi.python.org/pypi/regex/2013-06-26 modules to see if they already give you enough of a speedup. FYI, you're better off going to http://pypi.python.org/pypi/regex because that will take you to the latest version. Thank you everyone for the suggestions. I have not tried them yet. Devyn Collier Johnson I was thinking to decompose RE patterns into string matching formats of various strings in some formats. Anyway that involves some compiler techniques. -- http://mail.python.org/mailman/listinfo/python-list
Re: RE Module Performance
On Saturday, July 13, 2013 1:37:46 PM UTC+8, Steven D'Aprano wrote: On Fri, 12 Jul 2013 13:58:29 -0400, Devyn Collier Johnson wrote: I plan to spend some time optimizing the re.py module for Unix systems. I would love to amp up my programs that use that module. In my experience, often the best way to optimize a regex is to not use it at all. [steve@ando ~]$ python -m timeit -s import re \ -s data = 'a'*100+'b' \ if re.search('b', data): pass 10 loops, best of 3: 2.77 usec per loop [steve@ando ~]$ python -m timeit -s data = 'a'*100+'b' \ if 'b' in data: pass 100 loops, best of 3: 0.219 usec per loop In Python, we often use plain string operations instead of regex-based solutions for basic tasks. Regexes are a 10lb sledge hammer. Don't use them for cracking peanuts. -- Steven OK, lets talk about the indexed search algorithms of a character streamor strig which can be buffered and indexed randomly for RW operations but faster in sequential block RW operations after some pre-processing. This was solved long time ago in the suffix array or suffix tree part and summarized in the famous BWT paper in 199X. Do we want volunteers to speed up search operations in the string module in Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: psutil 1.0.0 released
Giampaolo Rodola'於 2013年7月11日星期四UTC+8下午11時02分01秒寫道: Congratulations on the 1.0.0 release! Thanks a lot. =) Btw. any change you can put up a prebuilt installer for a 64-bit built with Python 3.3? You have one for Python 3.2 (http://code.google.com/p/psutil/downloads/list), but the version for Python 3.3 is not there. Unfortunately I'm having troubles with Visual Studio 64-bit I still haven't managed to fix. Hope I will get around that soon. --- Giampaolo http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ http://code.google.com/p/pysendfile/ Do you plan to install 8 or 16 G BYTES DRAM? -- http://mail.python.org/mailman/listinfo/python-list
Re: Stupid ways to spell simple code
Steven D'Aprano於 2013年7月2日星期二UTC+8上午6時09分18秒寫道: On Mon, 01 Jul 2013 20:36:29 +0100, Marcin Szamotulski wrote: Here is another example which I came across when playing with generators, the first function is actually quite useful, the second generator is the whole fun: from functools import wraps def init(func): decorator which initialises the generator @wraps(func) def inner(*args, **kwargs): g = func(*args, **kwargs) g.send(None) return g return inner @init def gen(func): x = (yield) while True: x = (yield func(x)) now if you have function f def f(arg): return arg**2 then calling f(5) is the same as g = gen(f) g.send(5) I think you must be missing an important part of the trick, because calling f(5) returns 25. It's not: @gen def f(arg): return arg**2 because that raises TypeError. -- Steven Lets be serious about generators and iterators. A generator can be used only once in a program is different from a a generator method of a class that can produce several instances with generators of the same kind but operated in each instance of the class. -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
Jason Friedman於 2013年6月28日星期五UTC+8上午11時52分33秒寫道: I was hoping to have a good laugh. :| Although I wouldn't call it hostile. I think the python community is being educated in how to spam and troll at the same time. It is possible the OP has a mental disease, which is about as funny as heart disease and cancer and not blameworthy. This is the poster's website from a previous post on this forum: http://thrinaxodon.wordpress.com. KIND OF BORING TO SHOW HOW THE LISP PROGRAMMING WAS ASSIMULATED BY THE PYTHON COMMUNITY. OF COURSE PYTHON IS A GOOD LANGUAGE FOR DEVELOPING ARTIFICIAL INTELEGENT ROBOT PROGRAMS NOT SO BRAIN DAMAGES, OR SO SLAVERY AS C/C++ OR ASEMBLY PARTS. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with subclassing enum34
Thomas Heller於 2013年6月28日星期五UTC+8下午6時48分38秒寫道: trying out the enum34 module. What I want to create is a subclass of enum.Enum that is also based on ctypes.c_int so that I can better use enum instances in ctypes api calls. When I do this, I get a metaclass conflict: class MyEnum(ctypes.c_int, enum.Enum): ...FOOBAR = 0 ... Traceback (most recent call last): File stdin, line 1, in module TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases When I do this, it does not work either: class MyEnum_meta(type(ctypes.c_int), type(enum.Enum)): ... pass ... class MyEnum(ctypes.c_int, enum.Enum): ... FOOBAR = 42 ... __metaclass__ = MyEnum_meta ... MyEnum.FOOBAR 42 It should have printed 'MyEnum.FOOBAR: 42'. Any ideas? Thanks, Thomas Just use a dictionary for the job. Python i not c/c++. -- http://mail.python.org/mailman/listinfo/python-list
Re: Variables versus name bindings [Re: A certainl part of an if() structure never gets executed.]
Michael Torrie於 2013年6月20日星期四UTC+8下午2時01分11秒寫道: But since the LISP never really got a form beyond S-expressions, leaving us with lots of parenthesis everywhere, Python wins much as the Hitchhiker's Guide to the Galaxy wins. Yep, a list is mutable even it's empty. But constant integers, floats, strings, and None is immutable. The variables in a function of python with default parameters which could be mutable or immutable. def fun1( x, alist=[]): alist.append(x*x) return alist ## valid def fun2(x, alist=None): if alist==None: alist=[] alist.append(x*x) return alist # kind of boring to show the name binding mechanism of objects # in Python in different usages -- http://mail.python.org/mailman/listinfo/python-list
Re: Default Value
rusi於 2013年6月21日星期五UTC+8上午1時12分01秒寫道: You know Rick, you are good at python, you are better at polemics. If only you would cut the crap I would (be able to) agree with you. See below On Jun 20, 7:49 pm, Rick Johnson rantingrickjohn...@gmail.com wrote: On Thursday, June 20, 2013 7:57:06 AM UTC-5, rusi wrote: Every language has gotchas. This is one of python's. So are we purposely injecting illogic into our language just to be part of some cool crowd of programming languages with gotchas. You thought intuitiveness was a virtue? Haha, we gotcha! Python (and all the other 'cool' languages) dont have gotchas because someone malevolently put them there. In most cases, the problem is seen too late and the cost of changing entrenched code too great. Or the problem is clear, the solution is not etc etc. Or maybe this is reminiscent of the fraternity hazing rituals of days gone by: *POP* Thank you Sir, may i have another? If you are a beginning python programmer, really the best answer is: Just dont do it! Dont do what? Dont use mutable arguments as function defaults. Once you cross the noob stage you can check that its a standard gotcha: Just run a search for 'python gotcha default []' And when you feel that you need to, use Steven's trick: use a immutable indicator 'None' for the mutable []. Once you cross the noob stage you can check that its a standard gotcha: Just run a search for 'python gotcha default []' Its even been discussed repeatedly on the python-ideas list Your attempting to excuse an inexcusable language flaw by pointing out that the effects of the flaw can be avoided by using a workaround. And, to add insult to injury, you provide no good reason for the flaw to exist: Just do x, y, and z and shut up. Yes we made a mistake but we are not about to admit our mistake and the onerous will be on all the noobs to re-invent the workaround each time To me that is unacceptable. Heres a correction suggestion: [...] Here's Terry Reedy's nicely explaining the 'why-of-the-how' : [...] FWIW here is a conceptual/philosophical explanation of your confusion: There are 2 fundamental ways for approaching the programming task -- functional and imperative. All these explanations ignore a fundamental fact about subroutines[1]. A call to a subroutine should exists as a unique transaction within the entire program. It is expected to optionally take inputs, and optionally return an output (depending on the definition). When the subroutine is completed, all inputs and local variables are expected to be destroyed. If the programmer wants a return value, he need simply ask. Data persistence is not a function of subroutines! Finally, a subroutine should never have side effects UNLESS the programmer explicitly ask for a side effect. However, the Python flaw of allowing mutable sequence arguments to persist between successive calls of a subroutine is breaking the entire definition of a subroutine, and for what noble purpose i ask? What purpose is SO important that you change a well established interface in a totally unintuitive manner? If your answer is that recursion is easier, then i say that is foolish because a programmer can keep a reference to a mutable sequence OUTSIDE the subroutine and you can save the gotchas for Guido's next birthday party. [1]:http://en.wikipedia.org/wiki/Subroutine You are saying in different language what I said: Functional programming is a good idea, imperative programming is a bad idea. From the invention of subroutines (ie 50 years) PL designers are hearing this truth but somehow or other fail to listen; for more details see http://blog.languager.org/2012/11/imperative-programming-lessons-not.html Well, that was the story of the expensive memory era.the In 198X -2000 the auto GC of LISP was beaten by practical engineers using C, C++, PASCAL, and object pascal. But now it is different in 201X. -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing modules from all installed packages
Carlos Nepomuceno於 2013年6月9日星期日UTC+8下午1時23分15秒寫道: print '\n'.join([re.findall(from '(.*)',str(v))[0] for k,v in sys.modules.items() if str(v).find('from')-1]) Date: Sat, 8 Jun 2013 21:30:48 -0700 Subject: Listing modules from all installed packages From: jph...@gmail.com To: pytho...@python.org Hi, I'm trying to write a function that programmatically obtains and returns the exact location of all first-level modules for all installed packages. For example, if the packages named 'django' and 'django-debug-toolbar' are installed, I'd like this function to return something like: installed_modules() /Users/my_user/.virtualenvs/my_venv/lib/python2.6/site-packages/django /Users/my_user/.virtualenvs/my_venv/src/debug_toolbar That is, this function needs to consider all installed packages, including those that have been installed in edit mode (i.e. in the src/ folder). Note also that the main module for the 'django-debug-toolbar' is in fact named 'debug_toolbar'. So far the closest I've been to retrieving the list of first-level modules is as follows: import os import pkg_resources import setuptools pkgs = set() for dist in pkg_resources.working_set: if os.path.isdir(dist.location): for pkg in setuptools.find_packages(dist.location): if '.' not in pkg: pkgs.add(pkg) The idea is then to loop through that list of modules, import them and get their exact locations by fetching their __file__ attribute values. However, this feels very hackish and I don't think it's actually quite correct either. I'm sure there must be a better way. If possible I'd also like to avoid having to use setuptools. Do you have any tips on how to achieve this? Many thanks! Julien -- http://mail.python.org/mailman/listinfo/python-list Please use a dictionary to store a tree first. Then it is trivial to walk through all nodes of the tree. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Magazine
Steven D'Aprano於 2013年5月26日星期日UTC+8上午11時50分31秒寫道: On Sat, 25 May 2013 21:54:43 -0400, Roy Smith wrote: Of course not every IPv6 endpoint will be able to talk to every other IPv6 endpoint, even if the both have globally unique addresses. But, the access controls will be implemented in firewalls with appropriately coded security policies. Or, more likely, *not* implemented in firewalls with *inappropriately* coded security policies. -- Steven Well, both the reliabl tcpip socket and the unstable udp socket are supported in Python. Aso the html and xml part is supported for the dirct web page content analysis through port 80. I am not sure whether Steven is interested in the web applictions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Short-circuit Logic
Steven D'Aprano於 2013年5月30日星期四UTC+8上午10時28分57秒寫道: On Wed, 29 May 2013 10:50:47 -0600, Ian Kelly wrote: On Wed, May 29, 2013 at 8:33 AM, rusi rustompm...@gmail.com wrote: 0.0 == 0.0 implies 5.4 == 5.4 is not a true statement is what (I think) Steven is saying. 0 (or if you prefer 0.0) is special and is treated specially. It has nothing to do with 0 being special. A floating point number will always equal itself (except for nan, which is even more special), and in particular 5.4 == 5.4. But if you have two different calculations that produce 0, or two different calculations that produce 5.4, you might actually get two different numbers that approximate 0 or 5.4 thanks to rounding error. If you then compare those two ever-so-slightly different numbers, you will find them unequal. EXACTLY! The problem does not lie with the *equality operator*, it lies with the calculations. And that is an intractable problem -- in general, floating point is *hard*. So the problem occurs when we start with a perfectly good statement of the facts: If you naively test the results of a calculation for equality without understanding what you are doing, you will often get surprising results which then turns into a general heuristic that is often, but not always, reasonable: In general, you should test for floating point *approximate* equality, in some appropriate sense, rather than exact equality which then gets mangled to: Never test floating point numbers for equality and then implemented badly by people who have no clue what they are doing and have misunderstood the nature of the problem, leading to either: * de facto exact equality testing, only slower and with the *illusion* of avoiding equality, e.g. abs(x-y) sys.float_info.epsilon is just a long and slow way of saying x == y when both numbers are sufficiently large; * incorrectly accepting non-equal numbers as equal just because they happen to be close. The problem is that there is *no one right answer*, except have everyone become an expert in floating point, then judge every case on its merits, which will never happen. But if nothing else, I wish that we can get past the rank superstition that you should never test floats for equality. That would be a step forward. -- Steven The string used to represent a floating number in a computer language is normally in the decimal base of very some limited digits. Anyway with the advances of A/D-converters in the past 10 years which are reflected in the anttena- transmitter parts in phones, the long integer part in Python can really beat the low cost 32- 64 bit floating computations in scientific calculations. -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
Chris Angelico於 2013年5月28日星期二UTC+8下午3時11分55秒寫道: On Tue, May 28, 2013 at 9:10 AM, Roy Smith r...@panix.com wrote: In article mailman.2265.1369693294.3114.python-l...@python.org, Chris Angelico ros...@gmail.com wrote: I'll use XML when I have to, but if I'm inventing my own protocol, nope. There are just too many quirks with it. How do you represent an empty string named Foo? Foo/Foo or equivalently Foo/ How do you represent an empty list named Foo? The same way. How do you represent an empty dict/mapping named Foo? Lemme look up my documentation... ah, the same way. Does this seem right to you?/JubalEarly XML doesn't represent strings, or lists, or dicts. It represents trees of nodes with labels. If you wish to invent some richer semantic meaning to impose on those nodes, that's up to you. Sure it doesn't, but it's very often used that way. So I guess what I'm really saying is that XML is wrong for 90% of the places it's used. ChrisA Please check the annual sales in Ebay or similar sites and the advertizement fees collected by Google and Yahoo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python #ifdef
Carlos Nepomuceno於 2013年5月29日星期三UTC+8上午3時46分37秒寫道: Are there Python 'preprocessor directives'? I'd like to have something like '#ifdef' to mix code from Python 2 and 3 in a single file. Is that possible? How? Use execfile(filename) at the beginning to get what you want. The .pyc version is preferred. -- http://mail.python.org/mailman/listinfo/python-list
Re: Future standard GUI library
Grant Edwards於 2013年5月29日星期三UTC+8上午2時25分08秒寫道: On 2013-05-28, Wolfgang Keller felip...@gmx.net wrote: Actually productive work of significant intensity at a computer screen. Oh. You mean emacs. -- Grant Edwards grant.b.edwardsYow! Will it improve my at CASH FLOW? gmail.com Check http://www.pyamf.org/index.html for Python +flash in browser applications. Annyway the virtual server part can be obtained from the Adobe system in the cloudy services or whatever. As long as it is scalable in fees to provide services to web users in PCs or mobile phones, then it might be very profitable than 10 to 15 years ago. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
Carlos Nepomuceno於 2013年5月22日星期三UTC+8上午2時49分28秒寫道: From: alyssonbr...@gmail.com Date: Tue, 21 May 2013 09:03:13 -0300 Subject: Re: PEP 378: Format Specifier for Thousands Separator To: python-list@python.org This work in 3.1+: $ python3 Python 3.1.3 (r313:86834, Nov 28 2010, 11:28:10) [GCC 4.4.5] on linux2 Type help, copyright, credits or license for more information. one_number = 1234567 print('number={:,}'.format(one_number)) number=1,234,567 Thank you, but let me rephrase it. I'm already using str.format() but I'd like to use '%' (BINARY_MODULO) operator instead. I've looked into the source code of CPython 2.7.5 and I've found no evidence of the thousands separator been implemented on formatint() in Objects/unicodeobject.c. I also didn't find the _PyString_FormatLong() used in formatlong(). Where is _PyString_FormatLong() located? So, the question is: Where would I change the CPython 2.7.5 source code to enable '%' (BINARY_MODULO) to format using the thousands separator like str.format() does, such as: sys.stderr.write('%,d\n' % 1234567) 1,234,567 Could a separate instance like the I/O device of a subprocess to be easily available in Python? The next question would be whether the flow of several I/O data streams could be easily piped and manipulated in the high level programming designs without consuming too much resources. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
Carlos Nepomuceno於 2013年5月22日星期三UTC+8上午11時38分45秒寫道: From: steve+comp.lang.pyt...@pearwood.info Subject: Re: PEP 378: Format Specifier for Thousands Separator Date: Wed, 22 May 2013 03:08:54 + To: python-list@python.org [...] So, the only alternative to have '%,d' % x rendering the thousands separator output would a C source code modification? That's one alternative. But the language you would be then running will no longer be Python. Another alternative would be to write a pre-processor that parses your Python source code, extracts any reference to the above, and replaces it with a call to the appropriate format call. But not only is that a lot of work for very little gain, but it's also more or less impossible to do in full generality. And again, what you are running will be something different than Python, it will be Python plus a pre-processor. Don't fight the language. You will lose. Not fighting the language. In fact it's not even a language issue. All I need is a standard library[1] improvement: %,d! That's all! Just to put in perspective the performance difference of str.__mod__() and str.format(): C:\Python27python -m timeit -cv -n1000 '%d'%12345 raw times: 0.386 0.38 0.373 1000 loops, best of 3: 0.0373 usec per loop C:\Python27python -m timeit -cv -n1000 '{:d}'.format(12345) raw times: 7.91 7.89 7.98 1000 loops, best of 3: 0.789 usec per loop C:\Python27python -m timeit -cv -n1000 '{:,d}'.format(12345) raw times: 8.7 8.67 8.78 1000 loops, best of 3: 0.867 usec per loop That shows str.format() is 20 times slower than str.__mod__() for a simple decimal integer literal formatting. And it's additionally 10% slower if the thousands separator format specifier (',') is used. [1] I think that translates to Python source code in 'Objects/stringobject.c' and maybe 'Objects/unicodeobject.c' -- Steven -- http://mail.python.org/mailman/listinfo/python-list The conversions of the 32 bit integers and 64 bit floats to the strings of the base 10 digits require an efficint div and mod normally in the low level. -- http://mail.python.org/mailman/listinfo/python-list
Re: @staticmethods called more than once
Ethan Furman於 2013年5月22日星期三UTC+8上午12時30分22秒寫道: On 05/21/2013 08:39 AM, Skip Montanaro wrote: Don't confuse the use of static in Python with its use in C/C++. From a post on StackOverflow: A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod. For there record, staticmethod is useful when you want to make it possible for subclasses to change behavior. -- ~Ethan~ I prefer objects in classes with slimer figures not heavily weighted with trivial methods in each instance construction and clone. But this is only my personal style of classes in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Please help with Threading
Chris Angelico於 2013年5月20日星期一UTC+8下午5時09分13秒寫道: On Mon, May 20, 2013 at 6:35 PM, Cameron Simpson c...@zip.com.au wrote: _lock = Lock() def lprint(*a, **kw): global _lock with _lock: print(*a, **kw) and use lprint() everywhere? Fun little hack: def print(*args,print=print,lock=Lock(),**kwargs): with lock: print(*args,**kwargs) Question: Is this a cool use or a horrible abuse of the scoping rules? ChrisA OK, if the python interpreter has a global hiden print out buffer of ,say, 2to 16 K bytes, and all string print functions just construct the output string from the format to this string in an efficient low level way, then the next question would be that whether the uses can use functions in this low level buffer for other string formatting jobs. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to write fast into a file in python?
Steven D'Aprano於 2013年5月18日星期六UTC+8下午12時01分13秒寫道: On Fri, 17 May 2013 21:18:15 +0300, Carlos Nepomuceno wrote: I thought there would be a call to format method by '%d\n' % i. It seems the % operator is a lot faster than format. I just stopped using it because I read it was going to be deprecated. :( Why replace such a great and fast operator by a slow method? I mean, why format is been preferred over %? That is one of the most annoying, pernicious myths about Python, probably second only to the GIL makes Python slow (it actually makes it fast). The print function in python is designed to print any printable object with a valid string representation. The format part of the print function has to construct a printable string according to the format string and the variables passed in on the fly. If the acctual string to be printed in the format processing is obtained in the high level OOP way , then it is definitely slow due to the high level overheads and generality requirements. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for philosophers
Chris Angelico於 2013年5月14日星期二UTC+8上午12時24分44秒寫道: On Tue, May 14, 2013 at 12:53 AM, rusi rustompm...@gmail.com wrote: int fact(int n, int acc) { return !n? acc : fact(n-1,acc*n); } - When I run these, the C happily keeps giving answers until a million However examined closely we find that though the C is giving answers its giving junk after around 12 fact 17 is -288522240 And 35 onwards its 0 (!!) That'll depend on your integer size. If it's a 32-bit integer, you can't store numbers greater than 2**31-1 (if you declared it as 'unsigned int', you could go all the way to 2**32-1). I'm sure you could write this to use the GNU Multi-Precision library, but it'd be a lot more complicated. However, as far as I know, the Turing machine never promises that; its cells aren't meant to be infinite integers. The Python script is, of course, governed by sys.setrecursionlimit(). But by adding a simple driver, we can test the real limit: import sys def fact(n,acc=1): return acc if not n else fact(n-1,n*acc) n=2 while True: sys.setrecursionlimit(n+2) print(fact,n,has,len(str(fact(n))),digits) n*=2 On my 64-bit system, running a recent trunk build of CPython 3.4, it can calculate 8192! but not 16384! (segfault). The limit seems to be 12772; after that, boom. Your crash-point will quite probably vary, and I'd say there'll be compile-time options that would change that. Of course, after playing with this in Python, I had to try out Pike. Using the exact same code you proposed for C, but with a different main() to save me the hassle of keying in numbers manually, I get this: fact 8192 has 28504 digits - 0.026 secs fact 16384 has 61937 digits - 0.097 secs fact 32768 has 133734 digits - 0.389 secs fact 65536 has 287194 digits - 1.628 secs fact 131072 has 613842 digits - 7.114 secs fact 262144 has 1306594 digits - 31.291 secs fact 524288 has 2771010 digits - 133.146 secs It's still going. One core consumed, happily working on 1048576!, and not actually using all that much memory. Hmm looks like the Pike optimizer has turned this non-recursive. Okay, let's tweak it so it's not tail-recursion-optimizable: return n?n*fact(n-1,1):1; Now it bombs at 65536, saying: Svalue stack overflow. (99624 of 10 entries on stack, needed 256 more entries) Hey, it's better than a segfault, which is what C would have done :) And it's a tweakable value, though I don't know what the consequences are of increasing it (presumably increased RAM usage for all Pike programs). Your final conclusion is of course correct; nothing we build can be truly infinite. But we can certainly give some very good approximations, if we're prepared to pay for them. The reality is, though, that we usually do not want to pay for approximations to infinity; why is IEEE 754 floating point so much more used than, say, arbitrary-precision rational? Most of the time, we'd rather have good performance and adequate accuracy than abysmal performance and perfect accuracy. But hey, if you want to render a Mandelbrot set and zoom in to infinity, the option IS there. ChrisA Hey, ChisA, are you delibrately to write a recursive version to demonstrate the stack depth problem in Python? def fact(n): ret=1 if n1: # integer checking is not used but can be added for x in xrange(n): ret*=x #print ret # debugging only for long integers return ret In a 32 or 64 bit system, this non-recursive verssion will be limited by the heap space not by the stack limit. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for philosophers
Chris Angelico於 2013年5月19日星期日UTC+8上午8時04分45秒寫道: On Sun, May 19, 2013 at 9:56 AM, 8 Dihedral dihedral88...@googlemail.com wrote: Hey, ChisA, are you delibrately to write a recursive version to demonstrate the stack depth problem in Python? def fact(n): ret=1 if n1: # integer checking is not used but can be added for x in xrange(n): ret*=x #print ret # debugging only for long integers return ret In a 32 or 64 bit system, this non-recursive verssion will be limited by the heap space not by the stack limit. And just when we're sure Dihedral's a bot, a post like this comes through. Dihedral, are you intelligent? I'm still in two minds about this... which may be why you so often appear to have no minds. I dunno. Mathematics somewhere I fancy. ChrisA I am too lazy to write a factorial computations with primes here. -- http://mail.python.org/mailman/listinfo/python-list
Re: Back-end Python Developer Seeking Telecommute Work
Rob Sutton於 2013年5月18日星期六UTC+8上午2時36分07秒寫道: I am seeking part/full time work as a back-end Python developer (telecommute or Utah only). I have been maintaining a Debian/Python/Django/Apache/PostgreSQL/PHP/MySql web application for 3 years on my own. I do all the development, database and system management myself. I can setup a complete system from scratch remotely or setup the hosting service. I have experience with Virtualbox and ProxMox virtualization. I have expereince in all areas of IT including telecom, programming, networking, hardware and software. Worked with Retail stores, warehousing systems, accounting software, data interchange, hardware interfacing, etc. Regards, Rob Nic,e I am working on several similar projects including EDA automations with expert systems and some VLSI-FPGA IP cores. Anyway I have to get some US patents first. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C-API: how to define nested classes?
Serge WEINSTOCK於 2013年5月16日星期四UTC+8下午4時55分07秒寫道: Hi, I'm currently writing a C extension module for python using the raw C-API. I would like to be able to define nested classes like in the following python code class A: class B: def __init__(self): self.i = 2 def __init__(self): self.b = A.B() a = A() b = A.B() print(a.b.i) print(b.i) How can I create such nested class with the C-API? Serge WEINSTOCK ___ This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and delete this e-mail. Any unauthorised copying, disclosure or distribution of the material in this e-mail is prohibited. Please refer to http://www.bnpparibas.co.uk/en/email-disclaimer/ for additional disclosures. The nested class is just defining the scope of the nested class object that can be used solely in all outer proper classes. It is not very useful in a language which supports dynamical run-time attribute binding in the instance level. in the outer -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's sad, unimaginative Enum
Chris Angelico於 2013年5月14日星期二UTC+8上午1時36分34秒寫道: On Mon, May 13, 2013 at 8:17 PM, Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote: Let's look at his major criticisms: 1) values aren't automatically generated. True. So what? That is the *least* important part of enums. I stopped following the -ideas threads about enums, but IIRC autogeneration of values was in quite a few of the specs early on. So you can probably find the arguments against it in the list archives. FWIW, though, I do like C's autogeneration of enum values - but use it in only a small proportion of my enums. It's not a terrible loss, but it is a loss. ChrisA Because a hash table can replace the enums in other languages, it is more pythonic to use a dictionary built first to replace the enums. I think it is the same style of programming in perl and ruby. -- http://mail.python.org/mailman/listinfo/python-list
Re: Append to python List
Chris Angelico於 2013年5月12日星期日UTC+8上午12時00分44秒寫道: On Sun, May 12, 2013 at 1:47 AM, Anssi Saari a...@sci.fi wrote: Chris Angelico ros...@gmail.com writes: On Thu, May 9, 2013 at 9:30 PM, Jussi Piitulainen jpiit...@ling.helsinki.fi wrote: 8 Dihedral writes: This is just the handy style for a non-critical loop. In a critical loop, the number of the total operation counts does matter in the execution speed. Do you use speed often? Dihedral is a bot. Quite a good one, but a bot. That's been said often enough. Is the source available and is it in Python? Not to my knowledge. Technically Dihedral is merely _rumoured_ to be a bot, as we have no actual proof; but we've been conducting a variety of Turing tests via this list and have yet to see any strong argument for his being deemed human. Most humans would get defensive, or at least protest, if treated as bots; Dihedral never has, despite being referred to in this way a number of times. ChrisA Don't you get the practices of POSIX ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Append to python List
Jussi Piitulainen於 2013年5月9日星期四UTC+8下午7時30分05秒寫道: 8 Dihedral writes: This is just the handy style for a non-critical loop. In a critical loop, the number of the total operation counts does matter in the execution speed. Do you use speed often? There is another concern about the list construction part in programming. Although a typical PC is installed with gaga bytes of DRAM now, anything that will use more memory from the heap dynamically could fail in the run time. It is the programmer's job to identify this kind of sources in minds. -- http://mail.python.org/mailman/listinfo/python-list
Re: Append to python List
Jussi Piitulainen於 2013年5月9日星期四UTC+8下午2時55分20秒寫道: RAHUL RAJ writes: Checkout the following code: sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y] output=[] output=[x for x in sample2 if x not in output] the output I get is 3 4 5 6 7 8 9 10 3 5 6 7 8 9 10 11 4 5 7 8 9 10 11 12 5 6 7 9 10 11 12 13 6 7 8 9 11 12 13 14 7 8 9 10 11 13 14 15 8 9 10 11 12 13 15 16 9 10 11 12 13 14 15 17 10 11 12 13 14 15 16 17 which contains duplicate values. The second comprehension, [x for x in sample2 if x not in output], in the context, is equivalent to [x for x in sample2 if x not in []]. It does not refer to an incomplete version of the list that gets assigned to the variable after it's done. This is just the handy style for a non-critical loop. In a critical loop, the number of the total operation counts does matter in the execution speed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do Perl programmers make more money than Python programmers
Chris Angelico於 2013年5月7日星期二UTC+8下午9時32分55秒寫道: On Tue, May 7, 2013 at 11:22 PM, jmfauth wxjmfa...@gmail.com wrote: There are plenty of good reasons to use Python. There are also plenty of good reasons to not use (or now to drop) Python and to realize that if you wish to process text seriously, you are better served by using corporate products or tools using Unicode properly. There are plenty of good reasons to use Python. One of them is the laughs you can get any time jmf posts here. There are also plenty of good reasons to drop Python. One of them is because corporate products like Microsoft Visual Studio are inherently better specifically because they cost you money, and there's no way that something you paid nothing for can ever be as good as that. Plus, you get to write People used MS products because most bosses did not want to pay the prices of work stations, the minis, or the main-frames and the salaries of the system administrators in 199x. code that works on only one platform, and that's really good. Finally, moving off Python would mean you don't feel obliged to respond to jmf, which will increase your productivity measurably. ChrisA The price issue of a software package or a platform is not the only way to judge a programming language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do Perl programmers make more money than Python programmers
Steven D'Aprano於 2013年5月6日星期一UTC+8上午3時10分47秒寫道: On Sun, 05 May 2013 12:11:11 -0500, Ignoramus16992 wrote: According to CIO.com, Python programmers make only $83,000 per year, while Perl programmers make $93,000 per year. http://www.cio.com/slideshow/detail/97819?source=ifwartcio#slide10 http://www.cio.com/slideshow/detail/97819?source=ifwartcio#slide11 I would like to know, what explains the discrepancy. Perl is much harder to use, so the average Perl programmer burns out after a few years and takes up a less stressful career, like going undercover in the Russian mob or the Taliban. So only the most dedicated, brilliant and extreme programmers last long enough to become a Perl expert, and consequently can demand higher pay, while any idiot can learn to program Python, as I have. Also, Perl programmers are an unprincipled, devious bunch, always looking for an opportunity to blackmail their employers into paying them extra. Python programmers are a decent, law-abiding people with a strong moral code who would never stoop to the sort of things that Perl coders are proud of doing. -- Steven Some bosses just like the 1 to 5 liners of the Perl style in some cryptic forms from villain Perl programmers. I did see the same tricks in the Lisp or C/C++ before but with extremely long fat source codes in tens of thousands of lines that could also pleased some managers or bosses. -- http://mail.python.org/mailman/listinfo/python-list
Re: (Learner-here) Lists + Functions = headache
Bradley Wright於 2013年5月6日星期一UTC+8上午8時59分15秒寫道: Hey guys and gals doing this tutorial(codecademy) and needed a bit help from the experienced. I'm writing a function that takes a list(one they supply during runtime) here's what my function is supposed to do 1. for each instance of the string fizz make a count 2. Finally return that count here's my code: def fizz_cout(x): count = 0 for item in x: while item == fizz: count += 1 return count This is not indented right in the scope to return the total count. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can read in the BMP data correctly ,but the size is not right?
Jimmie He於 2013年4月30日星期二UTC+8上午1時20分49秒寫道: I'm trying to read in the BMP data by the the code below,and I'm check the data array with WINHEX,and it is correct,but which confuse me is why the size is 0x180,but the actual picture should be 48*48 = 0x120 bytes because I use 1-bit BMP not the 24bit BMP,could any one give some hints? __Head_Info = [ [ 'Type' ,0 , 2],#BM [ 'FSize',2 , 4],#File Size [ 'Reserved' ,6 , 4],#0x [ 'OffBits' ,10 , 4],#Offset of Image [ 'SSize',14 , 4],# 40 [ 'Width',18 , 4],#Width [ 'Height' ,22 , 4],#Hight [ 'Planes' ,26 , 2],#1 [ 'BitCount' ,28 , 2],#{1,2,4,8,24} [ 'Compress' ,30 , 4],#0 [ 'SizeImage',34 , 4],#Bytes Per Line [ 'XPM' ,38 , 4],#2835 [ 'YPM' ,42 , 4],#2835 [ 'ClrUsed' ,46 , 4],#0 [ 'ClrImportant' ,50 , 4]#0 ] _Type =0; _FSize =1; _Reserved =2; _OffBits =3; _SSize =4; _Width =5; _Height=6; _Planes=7; _BitCount =8; _Compress =9; _SizeImage =10; _XPM =11; _YPM =12; _ClrUsed =13; _ClrImportant =14; def __getInt( b, idx): return binToInt(b,__Head_Info[idx][1],__Head_Info[idx][2]) def saveMatrixtoASC(bmpfilename,ascfilename): try: handle1=open( bmpfilename ,rb) raw = bytearray(handle1.read( )) handle1.close except Exception as E: return error:+ str(E), datastart=__getInt(raw, _OffBits) datasize =__getInt(raw, _SizeImage) print ('Image Offset = 0x%X'%datastart) print ('Image Size = 0x%X'%datasize) handle2=open( ascfilename ,w) for i in range(0,datasize): handle2.write('0x%02X,'%raw[datastart+i]) if (i+1) % 16 == 0 : handle2.write(\n) handle2.close The start of each line of bytes must be in the 32 bit=4byte boundary in the MS BMP format. Please read the MS specs. -- http://mail.python.org/mailman/listinfo/python-list
Re: epiphany
Roy Smith於 2013年4月25日星期四UTC+8上午7時50分33秒寫道: I discovered something really neat today. We've got a system with a bunch of rules. Each rule is a method which returns True or False. At some point, we need to know if all the rules are True. Complicating things, not all the rules are implemented. Those that are not implemented raise NotImplementedError. We used to have some ugly logic which kept track of which rules were active and only evaluated those. So, here's the neat thing. It turns out that bool(NotImplemented) returns True. By changing the unimplemented rules from raising NotImplementedError to returning NotImplemented, the whole thing becomes: return all(r() for r in rules) Problems of rules in Boolean algebra or the bi-level logic inference engine in AI were all solved long time ago in the text book about AI. There are some variations about the multi-level or the continuous level logic engine with some new phases in Fuzzy theory in the expert system. A dynamical typed language is better to be used in this kind of problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] Automatic context managers
Chris Angelico於 2013年4月27日星期六UTC+8上午12時52分38秒寫道: On Sat, Apr 27, 2013 at 1:54 AM, MRAB pyt...@mrabarnett.plus.com wrote: On 26/04/2013 14:02, anatoly techtonik wrote: This circular reference problem is interesting. In object space it probably looks like a stellar detached from the visible (attached) universe. Is the main problem in detecting it? The problem is in knowing in which order the objects should be collected. For example, if A refers to B and B refers to A, should you collect A then B, or B then A? If you collect A first, then, for a time, B will be referring to a non-existent object. That's not good if the objects have destructors which need to be run. Spin-off thread from python-ideas to discuss a more general question of garbage collection of cyclic structures. Once it's been proven that there's an unreferenced cycle, why not simply dispose of one of the objects, and replace all references to it (probably only one - preferably pick an object with the fewest references) with a special temporary object? In fact, that could probably be done in CPython by wiping out the object in memory and replacing it with a special marker of some sort, which would then automatically take over all references to the old object. Any attempt to manipulate this object could simply pop back with a DestructedObject exception or something. Is this a plausible (never mind viable yet, just conceptually plausible) alternative to sticking them into gc.garbage and ignoring them? It'd allow a double-linked list/tree to function cleanly - imagine, for instance, something like the DOM facilities available to web browser scripts: class DOMObject: def __init__(self,parent): self.parent=parent self.firstchild=self.sibling=None if not parent: return if not parent.firstchild: parent.firstchild=self else: child=parent.firstchild while child.sibling: child=child.sibling child.sibling=self def __del__(self): print(Disposing of id #%d%id(self)) document=DOMObject(None) body=DOMObject(document) p=DOMObject(body) p=DOMObject(body) p=DOMObject(body) del document,body,p gc.collect() The __del__ method would need to clean up the external resources used by this object, but wouldn't have to walk the tree. Yet, just because there is a reference loop and there are __del__ methods, the garbage collector gives up and leaves it to the program author to deal with. I can understand if this is considered too complicated and too unusual a circumstance to be worth bothering to support, but I'm curious as to whether it's at least conceptually reasonable to do something like this. ChrisA Please use the deep-copy methods from time to time to disentangle referenced objects in python. The cyclic reference cycle has to be broken by some mean first in python to proceed for further actions in the gc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lists and arrays
Ana Dionísio於 2013年4月23日星期二UTC+8上午2時13分38秒寫道: Hello! I need your help! I have an array and I need pick some data from that array and put it in a list, for example: array= [a,b,c,1,2,3] list=array[0]+ array[3]+ array[4] list: [a,1,2] When I do it like this: list=array[0]+ array[3]+ array[4] I get an error: TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray' Can you help me? The list part in Python is more versatile but definitely executed slower than the array in C. What I like is that maintaining the Python part is not as tedious and painful for the same programs in LISP. -- http://mail.python.org/mailman/listinfo/python-list
Re: List Count
Blind Anagram於 2013年4月22日星期一UTC+8下午7時58分20秒寫道: I would be grateful for any advice people can offer on the fastest way to count items in a sub-sequence of a large list. I have a list of boolean values that can contain many hundreds of millions of elements for which I want to count the number of True values in a sub-sequence, one from the start up to some value (say hi). I am currently using: sieve[:hi].count(True) but I believe this may be costly because it copies a possibly large part of the sieve. Ideally I would like to be able to use: sieve.count(True, hi) where 'hi' sets the end of the count but this function is, sadly, not available for lists. The use of a bytearray with a memoryview object instead of a list solves this particular problem but it is not a solution for me as it creates more problems than it solves in other aspects of the program. Can I assume that one possible solution would be to sub-class list and create a C based extension to provide list.count(value, limit)? Are there any other solutions that will avoid copying a large part of the list? For those problems related to a homogeneous list of numbers , please check whether the arrays in numpy can fit your needs practically or not. Sometimes I work on numbers in varied ranges, then the list and the long integers in Python is really handy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Unicode support so hard...
jmfauth於 2013年4月21日星期日UTC+8上午1時12分43秒寫道: In a previous post, http://groups.google.com/group/comp.lang.python/browse_thread/thread/6aec70817705c226# , Chris “Kwpolska” Warrick wrote: “Is Unicode support so hard, especially in the 21st century?” -- Unicode is not really complicate and it works very well (more than two decades of development if you take into account iso-14). But, - I can say, as usual - people prefer to spend their time to make a better Unicode than Unicode and it usually fails. Python does not escape to this rule. - I'm busy with TeX (unicode engine variant), fonts and typography. This gives me plenty of ideas to test the flexible string representation (FSR). I should recognize this FSR is failing particulary very well... I can almost say, a delight. jmf Unicode lover To support the unicode is easy in the language part. But to support the unicode in a platform involves the OS and the display and input hardware devices which are not suitable to be free most of the time. -- http://mail.python.org/mailman/listinfo/python-list
Re: [TYPES] The type/object distinction and possible synthesis of OOP and imperative programming languages
Uday S Reddy於 2013年4月17日星期三UTC+8下午5時10分58秒寫道: Mark Janssen writes: Having said that, theorists do want to unify concepts wherever possible and wherever they make sense. Imperative programming types, which I will call storage types, are semantically the same as classes. The imperative part is supported in Python by tuples only. The name binding assignment of an object is perative in Python. Anyway it is not so difficult to mimic the behaviors and to gain the benefits of imperative languages at least in the c-python implementation by those who can play with the Python language in programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: [TYPES] The type/object distinction and possible synthesis of OOP and imperative programming languages
Ned Batchelder於 2013年4月20日星期六UTC+8上午12時41分03秒寫道: On 4/19/2013 12:16 PM, Steven D'Aprano wrote: On Fri, 19 Apr 2013 12:02:00 -0400, Roy Smith wrote: PS: a great C++ interview question is, What's the difference between a class and a struct? Amazing how few self-professed C++ experts have no clue. I'm not a C++ expert, but I am an inquiring mind, and I want to know the answer! The only difference between a class and a struct is that classes default to private access for their members, and structs default to public. --Ned. In python even a class can be decorated. Also features of instances can be added at run time from programs by different programmers or even programs from machines by the code generation scheme used in many CAD tools. Nowadays the concept of a structure is not clear without specifying the language used in programming. A list is a structure of non-homogeneous types of items in LISP, PERL and PYTHON. But the cases are different in C++, PASCAL, ADDA, JAVA -- http://mail.python.org/mailman/listinfo/python-list
Re: a couple of things I don't understand wrt lists
Serhiy Storchaka於 2013年4月17日星期三UTC+8下午5時35分07秒寫道: 17.04.13 07:57, Larry Hudson написав(ла): So using a list comprehension you can do it in two lines: def get_rule(num): bs = bin(num)[2:] return [0] * (8 - len(bs)) + [int(i) for i in bs] You can do it in one line! def get_rule(num): return list(map(int, '{:08b}'.format(num))) Well, a new object is returned and can be used. Then who is going to clean up the object when required? -- http://mail.python.org/mailman/listinfo/python-list
Re: Atoms, Identifiers, and Primaries
Ian於 2013年4月17日星期三UTC+8下午3時21分00秒寫道: On Tue, Apr 16, 2013 at 8:57 PM, Bruce McGoveran wrote: These are terms that appear in section 5 (Expressions) of the Python online documentation. I'm having some trouble understanding what, precisely, these terms mean. I'd appreciate the forum's thoughts on these questions: 1. Section 5.2.1 indicates that an identifier occurring as an atom is a name. However, Section 2.3 indicates that identifiers are names. My question: can an identifier be anything other than a name? Yes. For example: from a import b Here a is an identifier but not a name, as it does not carry object-binding semantics. 2. Section 5.3 defines primaries as the most tightly bound operations of Python. What does this mean? Tightly bound here refers to operator precedence. For example, we say that the multiplication operator binds more tightly [to the surrounding operands] than the arithmetic operator, because the multiplication takes precedence. This section defines that the most tightly bound operations in Python are attribute references, subscriptions, slices and calls; these always take precedence over other neighboring operations. In particular, if an atom is a primary, what operation is the atom performing that leads to the label most tightly bound? An atom doesn't perform an operation. The grammar defines that a primary can be just an atom, so that anywhere in the grammar that expects a primary, a simple atom with no primary operation performed on it can equally be used. An atom can not be divided into further details. An atom can be created and cloned or just referenced in some relations. An object is composed of atoms linked in someway. Of course, one can box those atoms of an object to make the object immutable at least in some situations to be named and used. -- http://mail.python.org/mailman/listinfo/python-list
Re: The type/object distinction and possible synthesis of OOP and imperative programming languages
zipher於 2013年4月15日星期一UTC+8上午11時48分05秒寫道: Hello, I'm new to the list and hoping this might be the right place to introduce something that has provoked a bit of an argument in my programming community. I'll state about my opinions about the imperative and non-imperative part. If the finite stack depth is used instead of the infinite one, then the auto local variables of the imperative part can be implemented quite safe and cheap or at least self-recoverable from a stack overflow event. This can save a lot burdens in the GC part in an imperative language. -- http://mail.python.org/mailman/listinfo/python-list
Re: Threadpool item mailboxes design problem
Charles Hixson於 2013年4月15日星期一UTC+8上午7時12分11秒寫道: What is the best approach to implementing actors that accept and post messages (and have no other external contacts). So far what I've come up with is something like: actors = {} mailboxs = {} Stuff actors with actor instances, mailboxes with multiprocessing.queue instances. (Actors and mailboxes will have identical keys, which are id#, but it's got to be a dict rather than a list, because too many are rolled out to disk.) And I'm planning of having the actors running simultaneously and continually in a threadpool that just loops through the actors that are assigned to each thread of the pool. This lets any actor post messages to the mailbox of any other actor that it has the id of, and lets him read his own mail without multi-processing clashes. But I'm quite uncertain that this is the best way, because, if nothing else, it means that each mailbox needs to be allocated large enough to handle the maximum amount of mail it could possibly receive. (I suppose I could implement some sort of wait awhile and try again method.) It would, however, be better if the mailbox could be specific to the threadpool instance, so less space would be wasted. Or if the queues could dynamically resize. Or if there was a threadsafe dict. Or... But I don't know that any of these are feasible. (I mean, yes, I could write all the mail to a database, but is that a better answer, or even a good one?) -- Charles Hixson Actors can receive and response to messages to take actions accordingly in time in one or more cores. The timer is required and the message read/write operations are required. Do you want the actors to gain new methods to evolve in the long run? -- http://mail.python.org/mailman/listinfo/python-list
Re: shutil.copyfile is incomplete (truncated)
Steven D'Aprano於 2013年4月12日星期五UTC+8上午8時06分21秒寫道: On Thu, 11 Apr 2013 19:55:53 +, Neil Cerutti wrote: On 2013-04-11, Rob Schneider rmsc...@gmail.com wrote: Thanks. Yes, there is a close function call before the copy is launched. No other writes. Does Python wait for file close command to complete before proceeding? The close method is defined and flushing and closing a file, so it should not return until that's done. But note that done in this case means the file system thinks it is done, not *actually* done. Hard drives, especially the cheaper ones, lie. They can say the file is written when in fact the data is still in the hard drive's internal cache and not written to the disk platter. Also, in my experience, hardware RAID controllers will eat your data, and then your brains when you try to diagnose the problem. Don't you model this as a non-blocking operation in your program? I would consider the chance that the disk may be faulty, or the file system is corrupt. Does the problem go away if you write to a different file system or a different disk? -- Steven Back-ups and read-back verifications are important for those who care. -- http://mail.python.org/mailman/listinfo/python-list
Re: Functional vs. Object oriented API
David M Chess於 2013年4月12日星期五UTC+8下午11時37分28秒寫道: Roy Smith r...@panix.com As part of our initial interview screen, we give applicants some small coding problems to do. One of the things we see a lot is what you could call Java code smell. This is our clue that the person is really a Java hacker at heart who just dabbles in Python but isn't really fluent. ... It's not just LongVerboseFunctionNamesInCamelCase(). Nor is it code that looks like somebody bought the Gang of Four patterns book and is that maybe there's a class struggling to be written. And I think equally to the point, even if you have only data, or only functions, right now, if the thing in question has that thing-like feel to it :) you will probably find yourself with both before you're done, so you might as well make it a class now... DC If it is not time-critical and no needs to convert into CYTHON then it does not matter too much. But a well wrapped class structures with good documents can help others to use the python codes a lot. If the part is intended to be time-critical in the low level part, then avoiding seeking 4 levels of methods and properties inside a loop is helpful in python programs to be executed in the run time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help: pickle module unable to load rb mode files in linux
Surya Kasturi於 2013年4月2日星期二UTC+8下午10時54分25秒寫道: Hi, hope you can help me on it.. with open(pickle_f, 'r') as fhand: obj = pickle.load(fhand) This works on linux but not in windows until I use rb mode while creating file object. Surprisingly, the rb mode is not working on Linux.. raising EOFError. Just use a decorator with a pass in parameter about the OS to wrap the two versions in different platforms. By the way any function can be saved in a variable to be passed around means that the lambda 1-liner is not necessarily required in Python. In C++, the sub-classing with virtual membership function reload mechanism is the equivalent part. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator help
Jason Swails於 2013年3月28日星期四UTC+8上午4時33分08秒寫道: On Wed, Mar 27, 2013 at 3:49 PM, Joseph L. Casale jca...@activenetwerx.com wrote: I have a class which sets up some class vars, then several methods that are passed in data and do work referencing the class vars. I want to decorate these methods, the decorator needs access to the class vars, so I thought about making the decorator its own class and allowing it to accept args. I was hoping to do all the work on in_data from within the decorator, which requires access to several MyClass vars. Not clear on the syntax/usage with this approach here, any guidance would be greatly appreciated! My guess is that you don't quite 'get' decorators yet (since I remember similar types of questions when trying to learn them myself). Decorators execute when the class type itself is being built (e.g., when a module is first imported at runtime). So decorators will never take instance variables as arguments (nor should they, since no instance can possibly exist when they execute). Bear in mind, a decorator should take a callable as an argument (and any number of 'static' parameters you want to assign it), and return another callable. I provide an example decorator using the format the I typically adopt below (where the decorator is a simple function, not a class): def my_decorator(fcn): I might add default parameters here if I am programming in python to save the troubles of subclassing similar decorators. But that is only the stylish problem in python. I might need to translate the decorator part into cython or c/c++ in the future. Decorator for a function def new_fcn(self, *args, **kwargs): This is the new function that we will return. # You can access any instance variables here returnval = fcn(self, *args, **kwargs) # Do anything else here with instance variables return returnval # or any other return value you want return new_fcn Notice here I define a new_fcn callable function that takes self and an arbitrary argument/keyword-argument list, and I return this function (which does not get called) to replace the function I passed in. You can use instance variables inside new_fcn since new_fcn is called by instances of MyClass. This is a very simple type of decorator, but hopefully helps illustrate what decorators are. There is a particularly good thread on SO with information about decorators here: http://stackoverflow.com/questions/739654/understanding-python-decorators Hope this helps, Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: flaming vs accuracy [was Re: Performance of int/long in Python 3]
Chris Angelico於 2013年3月28日星期四UTC+8上午11時40分17秒寫道: On Thu, Mar 28, 2013 at 2:18 PM, Ethan Furman et...@stoneleaf.us wrote: Has anybody else thought that [jmf's] last few responses are starting to sound bot'ish? Yes, I did wonder. It's like he and Dihedral have been trading accounts sometimes. Hey, Dihedral, I hear there's a discussion of Unicode and PEP 393 and Python 3.3 and Unicode and lots of keywords for you to trigger on and Python and bots are funny and this text is almost grammatical! There. Let's see if he takes the bait. ChrisA Well, we need some cheap ram to hold 4 bytes per character in a text segment to be observed. For those not to be observed or shown, the old way still works. Windows got this job done right to collect taxes in areas of different languages. -- http://mail.python.org/mailman/listinfo/python-list
Re: free and nonlocal variables
bartolom...@gmail.com於 2013年3月21日星期四UTC+8下午4時52分17秒寫道: In Python 3, free variable and nonlocal variable are synonym terms? Or is there a difference, like a free variable is a variable that is not a local variable, then nonlocal variables and global variables are both free variables? Thanking you in advance, Bartolomé Sintes In python the interpreter has to check 4 levels of dictionaries in the run time to perform an action. The for levels are: 1. object instance level 2. class level 3. local function level 4. global level. Objects created at level 1,2,3 can be returned to some other object in the run time. Thus a GC is available to save the trouble of tracking everything for the programmer in a complex system. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] Message passing syntax for objects
zipher於 2013年3月19日星期二UTC+8上午1時04分36秒寫道: On Sun, Mar 17, 2013 at 11:46 PM, Steven D'Aprano st...@pearwood.info wrote: I am very interested in this as a concept, although I must admit I'm not entirely sure what you mean by it. I've read your comment on the link above, and subsequent emails in this thread, and I'm afraid I don't understand what you mean here. I feel you are assuming that your readers are already experts on message-passing languages (Smalltalk?). I know what *I* mean by message passing, but that's not necessarily what you mean by it. I'm sorry, I haven't been very clear. I'm not even an expert on message-passing languages, but I see that it's a profound concept that hasn't been adequately integrated into the OOP model. In any case, I will try to do better. And I apologize to everyone on the list for the prior mail spam. A part of me is a bit giddy with the idea. By message passing, I mean all the ways we communicate to objects in the OOP environment. Usually we communicate to them through method-invokation. But this is the wrong way, I argue, to look at the problem. With function or method syntax, you're telling the computer to execute something, but that is not the right concepts for OOP. You want the objects to interact with each other and in a high-level language, the syntax should assist with that. By building it into the language, it would *enforce* a modular object style, rather than the current, very specialized and very programmer specific way there is now. In fact, most people never really think in that paradigm, yet if the language supported/proposed such a syntax, programmers would start to re-arrange the whole object hierarchy in a new, more modular and universal way. [end quote] I don't understand this. In what way would message passing enforce a modular object style? In what way does Python not already have a modular object style? Hopefully my paragraph clarifies that a bit. But the key conceptual shift is that by enforcing a syntax that moves away from invoking methods and move to message passing between objects, you're automatically enforcing a more modular approach. Mark Please check object pascal and objective c and erlang for the message-action director model of what you want. C is too low level to be suitable for everything. -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the Min for positive and negative in python 3.3 list
Wolfgang Maier於 2013年3月13日星期三UTC+8下午6時43分38秒寫道: Steven D'Aprano steve+comp.lang.python at pearwood.info writes: On Tue, 12 Mar 2013 17:03:08 +, Norah Jones wrote: For example: a=[-15,-30,-10,1,3,5] I want to find a negative and a positive minimum. example: negative print(min(a)) = -30 positive print(min(a)) = 1 Thank you for providing examples, but they don't really cover all the possibilities. For example, if you had: a = [-1, -2, -3, 100, 200, 300] I can see that you consider -3 to be the negative minimum. Do you consider the positive minimum to be 100, or 1? If you expect it to be 100, then the solution is: min([item for item in a if item 0]) If you expect it to be 1, then the solution is: min([abs(item) for item in a]) which could also be written as: min(map(abs, a)) A third alternative is in Python 3.3: min(a, key=abs) which will return -1. thinking again about the question, then the min() solutions suggested so far certainly do the job and they are easy to understand. However, if you need to run the function repeatedly on larger lists, using min() is suboptimal because its performance is an O(n) one. It's faster, though less intuitive, to sort your list first, then use bisect on it to find the zero position in it. Two manipulations running at O(log(n)). compare these two functions: def with_min(x): return (min(n for n in a if n0), min(n for n in a if n=0)) def with_bisect(x): b=sorted(x) return (b[0] if b[0]0 else None, b[bisect.bisect_left(b,0)]) then either time them for small lists or try: a=range(-1000,1000) with_min(a) with_bisect(a) of course, the disadvantage is that you create a huge sorted list in memory and that it's less readable. Best, Wolfgang Sorting numbers of such range M in a list of length N by radix sort is faster but requires more memory. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reversing bits in a byte
Oscar Benjamin於 2013年3月12日星期二UTC+8下午11時44分50秒寫道: On 12 March 2013 14:59, Oscar Benjamin oscar.j.benja...@gmail.com wrote: Numpy and matplotlib will do what you want: import numpy as np import matplotlib.pyplot as plt def bits_to_ndarray(bits, shape): abytes = np.frombuffer(bits, dtype=np.uint8) abits = np.zeros(8 * len(abytes), np.uint8) for n in range(8): abits[n::8] = (abytes % (2 ** (n+1))) != 0 Whoops! The line above should be abits[n::8] = (abytes (2 ** n)) != 0 return abits.reshape(shape) # 8x8 image = 64 bits bytes object bits = b'\x00\xff' * 4 img = bits_to_ndarray(bits, shape=(8, 8)) plt.imshow(img) plt.show() Oscar Now the dram is so cheap in the street. Please type in a tuple of all 8 bit inversions from the index to the result then just take a look up by the index to solve the problem. # there are ways to exchange the top 4 bits and the low 4bits, then swap inside the nibbles then swap the 4 2bit pairs in the old way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating an object that can track when its attributes are modified
Ben Sizer於 2013年3月7日星期四UTC+8上午12時56分09秒寫道: On Wednesday, 6 March 2013 16:22:56 UTC, Chris Angelico wrote: Effectively, you would need to have a subclass of list/dict/tuple/whatever that can respond to the change. This is certainly something I'd be interested in having, but I guess that would be fragile since the user would have the burden of having to remember to use those types. What's the goal of this class? Can you achieve the same thing by using, perhaps, a before-and-after snapshot of a JSON-encoded form of the object? I need to be able to perform complex operations on the object that may modify several properties, and then gather the properties at the end as an efficient way to see what has changed and to store those changes. Any comparison of before-and-after snapshots could work in theory, but in practice it could be expensive to produce the snapshots on larger objects and probably expensive to calculate the differences that way too. Performance is important so I would probably just go for an explicit function call to mark an attribute as having been modified rather than trying to do a diff like that. (It wouldn't work for rollbacks, but I can accept that.) -- Ben Sizer Please hook a stack implemented as a list in python to every property of the object that you want to track down. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is it impossible to create a compiler than can compile Python to machinecode like C?
On Tuesday, March 5, 2013 6:55:06 AM UTC+8, CM wrote: The main issue is that python has dynamic typing. The type of object that is referenced by a particular name can vary, and there's no way (in general) to know at compile time what the type of object foo is. That makes generating object code to manipulate foo very difficult. Could you help me understand this better? For example, if you have this line in the Python program: foo = 'some text' bar = {'apple':'fruit'} If the interpreter can determine at runtime that foo is a string and bar is a dict, why can't the compiler figure that out at compile time? Or is the problem that if later in the program you have this line: foo = 12 now foo is referring to an integer object, not a string, and compilers can't have two names referring to two different types of objects? Something like that? I in no way doubt you that this is not possible, I just don't understand enough about how compiling works to yet get why dynamic typing is a problem for compilers. Thanks. The dynamic type part is normally in the higher level components of objects and functions and generators. Of course if one can be sure of the types of variables used in some functions then that is the cython way to speed up pure OOP python programs in executions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python script not working on windows 7 but works fine on linux
On Tuesday, March 5, 2013 3:20:28 AM UTC+8, ian douglas wrote: On 03/04/2013 11:06 AM, io wrote: esclusioni_file = open('/home/io/btc_trading/exclusions.txt','r') Windows error : Traceback (most recent call last): File C:\btc_trading\scripts \import_json_2_csv_from_web_and_exclusions.py, line 10, in module f = open(/home/io/btc_trading/markets.csv,wb) IOError: [Errno 2] No such file or directory: '/home/io/btc_trading/ markets.csv' The error tells you everything you need to know: the file system has no path/file called /home/io/btc_trading/markets.csv I imagine your CSV file lives in a different location on your Windows 7 system (which also uses back-slashes '\' instead of forward-slashes '/', so you'll need to maybe do a try/except around the open() call to open a Windows path like open(c:\\users\\io\\Documents\\markets.csv) or whatever. OR you'll need to do some OS detection ahead of time to set the file path properly. Well, I'll suggest an old trick I did long time ago to resolve the platform dependent problem in python. Just write a generator as a buffered input method to work under some file of some OS correctly first, then you can pass the generator which is tested rigorously to act properly in the function or the object which will use the generator to sip up the data to perform jobs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is it impossible to create a compiler than can compile Python to machinecode like C?
kramer65於 2013年3月1日星期五UTC+8上午4時25分07秒寫道: Hello, I'm using Python for a while now and I love it. There is just one thing I cannot understand. There are compilers for languages like C and C++. why is it impossible to create a compiler that can compile Python code to machinecode? My reasoning is as follows: When GCC compiles a program written in C++, it simply takes that code and decides what instructions that would mean for the computer's hardware. What does the CPU need to do, what does the memory need to remember, etc. etc. If you can create this machinecode from C++, then I would suspect that it should also be possible to do this (without a C-step in between) for programs written in Python. Where is my reasoning wrong here? Is that because Python is dynamically typed? Does machinecode always need to know whether a variable is an int or a float? And if so, can't you build a compiler which creates machinecode that can handle both ints and floats in case of doubt? Or is it actually possible to do, but so much work that nobody does it? I googled around, and I *think* it is because of the dynamic typing, but I really don't understand why this would be an issue.. Any insights on this would be highly appreciated! I think a smart object can perform some experiments in its lifetime in sensing and collecting data to improve its methods in the long run. This will require a dynamical language definitely. -- http://mail.python.org/mailman/listinfo/python-list
Re: string.replace doesn't removes :
Rick Johnson於 2013年2月14日星期四UTC+8上午12時34分11秒寫道: On Wednesday, February 13, 2013 1:10:14 AM UTC-6, jmfauth wrote: d = {ord('a'): 'A', ord('b'): '2', ord('c'): 'C'} 'abcdefgabc'.translate(d) 'A2CdefgA2C' def jmTranslate(s, table): ... table = {ord(k):table[k] for k in table} ... return s.translate(table) ... d = {'a': 'A', 'b': '2', 'c': 'C'} jmTranslate('abcdefgabc', d) 'A2CdefgA2C' d = {'a': None, 'b': None, 'c': None} jmTranslate('abcdefgabc', d) 'defg' d = {'a': '€', 'b': '', 'c': ''} jmTranslate('abcdefgabc', d) '€defg€' In python the variables of value types, and the variables of lists and dictionaries are passed to functions somewhat different. This should be noticed by any serious programmer in python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simulate Keyboard keypress Delay
DaGeek247於 2013年2月14日星期四UTC+8上午3時47分36秒寫道: I am using the windows api feature getasynckeystate() to check the status of every key pressed; like this; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): #do stuff This works great, almost. The issue that comes up now is that every time i press a key, the code grabs two or three key presses. So i tried making sure that repeated keys weren't pressed repeatedly; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): if oldkeychar == num: #don't do stuff else: #do stuff this works great, but It won't record stuff like 'look' or 'suffer' because it doesn't record repeated keys. So I try doing a delay instead; #always checking while(True): #iterate through list of ascii codes for num in range(0,127): #if ascii code key is being pressed if win32api.GetAsyncKeyState(num): if oldkeychar == num: if crrenttime (time.time() - .5) #do stuff because key has been repeated, but not because it was held down else: #don't do stuff because key is pressed to soon else: #do stuff because key is not repeated currenttime = time.time() this almost works, but I end recording some double keypresses, and missing others. Does anybody have any suggestions? I believe you can use the raw_input function in python. But loop through strings ended by \r\n or \r. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
Rick Johnson於 2013年2月13日星期三UTC+8上午1時48分07秒寫道: On Monday, February 11, 2013 11:55:19 PM UTC-6, Chris Angelico wrote: On Tue, Feb 12, 2013 at 12:06 PM, 8 Dihedral wrote: A permanently mutated list is a tuple of constant objects. I nominate this line as bemusing head-scratcher of the week. Actually the statement is fact IF you can grok it through the eyes of clarity. A permanently mutated list... A list that has been mutated permanently, that is, it cannot be changed back into a list. psst: i have a sneaking suspicion that he his referring to tuples, let's see. ...is a tuple... Ha! Well in Python the immutable sequence type /is/ a tuple after all. ...of constant objects... The tuple contains objects, and it's objects will maintain a constant ordering (relatively in tuple structure) until until the tuple's death. a1=[1,2,3] tuple1=(a1,4,5,6) tuple1 ([1, 2, 3], 4, 5, 6) a1=[1,2] tuple1 ([1, 2, 3], 4, 5, 6) Yes, a tuple of constant objects is still not clear. Your confusion may stem from interpreting constant as the CS term CONSTANT[1]; whereby the objects in the tuple are programming CONSTANTS, that is, unable to change. But in reality, although a tuple (bka:StaticList) cannot expand to add more objects, or shrink to eject existing objects, the objects themselves CAN change their own internal state WITHOUT disrupting the immutable harmony of the tuple. Observe: py class Foo(object): pass py foo = Foo() py t = (1,'1', foo) py t (1, '1', __main__.Foo object at 0x0267BF50) py t[-1].bar = abc py t (1, '1', __main__.Foo object at 0x0267BF50) Or by expanding a list py t = (1,2,3) py t = t+([],) py t (1, 2, 3, []) py t[-1].append('circus') py t (1, 2, 3, ['circus']) [1] Which is an unfortunate side-effect of polysemy and compounded exponentially by naive (and sometimes a purely malevolent intent when) transformation of words into esoteric problem domains. -- http://mail.python.org/mailman/listinfo/python-list
Re: Implicit conversion to boolean in if and while statements
Rick Johnson於 2013年2月11日星期一UTC+8下午9時13分58秒寫道: On Monday, February 11, 2013 6:40:23 AM UTC-6, Chris Angelico wrote: [...] Or doing what you were pointing and laughing at Pike for, and using two-symbol delimiters. You could even make it majorly logical: list_ = [[ 1, 2, 3 ]] tuple_ = ([ 1, 2, 3 ]) dict_ = [{ 1, 2, 3 }] frozendict_ = ({ 1, 2, 3 }) set_ = [ 1, 2, 3 ] frozenset_ = ( 1, 2, 3 ) I am vehemently against using more than one opening seq char and one closing seq char. It works fine for single depth sequences, however, once you start nesting the mental focus required to parse the doubled openers/closers is headache inducing. I would accept wrapping the literal in some sort of declaration though, something like i proposed earlier in the thread. The easiest is to use: set({1,2,3}) but that looks like a function call! So we'd need a unique syntax. Either a single tag like: set{1,2,3} Or we could use start and end tags like: set{1,2,3}set where set{ and }set are delimiters. For lists, tuples, and dict we would use the short form because these literals are far too ubiquitous: [1,2,3] # list {k:v} # dict (1,2,3) # tuple However, the grouping chars for tuples has always been confusing because they can clash with grouping of expressions. What is this? (1) It's NOT a tuple! But it looks like a tuple! What is this: 1,2 it IS a tuple, but it does not look like a tuple! That's an unfortunate side effect of a poorly thought-out tuple syntax. I am thinking a mutated list temporarily is useful when a list is to be used to be iterated through all of its elements efficiently. A permanently mutated list is a tuple of constant objects. As for the set type, I prefer to use the operations of the list, dictionaries in Python to act for the designed purposes. -- http://mail.python.org/mailman/listinfo/python-list
Re: LangWart: Method congestion from mutate multiplicty
Steven D'Aprano於 2013年2月9日星期六UTC+8上午11時36分52秒寫道: Rick Johnson wrote: The solution is simple. Do not offer the copy-mutate methods and force all mutation to happen in-place: py l = [1,2,3] py l.reverse py l [3,2,1] If the user wants a mutated copy he should explicitly create a new object and then apply the correct mutator method: py a1 = [1,2,3] py a2 = list(a1).reverse() Oh wow, Rick has re-discovered programming in Python during the mid to late 1990s! I was there, and I remember what it was like. For about a month, you try hard to follow Rick's prescription. Then you realise that with a small helper function, you can halve the amount of code it takes to do a common operation: def reversed(sequence): seq = list(sequence) seq.reverse() return seq Soon you've copied this reversed() function into all your projects. And of course, they start to diverge... in project A, you only care about lists. In project B, you realise that you also need to support tuples and strings: def reversed(sequence): seq = sequence[:] try: seq.reverse() except AttributeError: seq = seq[::-1] return seq Will a temprary new list be formed here? If it is not necessary, I'll prefer a reverse generator for all lists to save the heap space and the GC burden. which in project C you realise can be shortened: def reversed(sequence): return sequence[::-1] until you get to project D when you realise that you also want this to work on dicts: def reversed(sequence): everything = list(sequence) return everything[::-1] and then in project E you wonder why reversed(string) returns a list: def reversed(sequence): everything = list(sequence)[::-1] if isinstance(sequence, tuple): return tuple(everything) elif isinstance(sequence, str): return ''.join(everything) return everything and then finally you learn about iterators and generators and become more comfortable with a flow-based programming paradigm and generators: def reversed(sequence): for item in list(sequence)[::-1]: yield item at which point you realise that, hell, this is so useful that pretty much everyone has implemented it a dozen times or more in their own projects, and you start to agitate for it to be added to the builtins so that there is *one* implementation, done *right*, that everyone can use. And then you get told that Guido's time machine has struck again, because Python has already had this since Python 2.4. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: confusion with decorators
Jason Swails於 2013年1月31日星期四UTC+8上午8時34分03秒寫道: Hello, I was having some trouble understanding decorators and inheritance and all that. This is what I was trying to do: # untested class A(object): def _protector_decorator(fcn): def newfcn(self, *args, **kwargs): return fcn(self, *args, **kwargs) return newfcn @_protector_decorator def my_method(self, *args, **kwargs): do something here class B(A): def _protector_decorator(fcn): def newfcn(self, *args, **kwargs): raise MyException('I do not want B to be able to access the protected functions') return newfcn The goal of all that was to be able to change the behavior of my_method inside class B simply by redefining the decorator. Basically, what I want is B.my_method() to be decorated by B._protector_decorator, but in the code I'm running it's decorated by A._protector_decorator. I presume this is because once the decorator is applied to my_method in class A, A.my_method is immediately bound to the new, 'decorated' function, which is subsequently inherited (and not decorated, obviously), by B. Am I correct here? My workaround was to simply copy the method from class A to class B, after which B._protector_decorator decorated the methods in B. While this doesn't make the use of decorators completely pointless (the decorators actually do something in each class, it's just different), it does add a bunch of code duplication which I was at one point hopeful to avoid. I'm still stumbling around with decorators a little, but this exercise has made them a lot clearer to me. Thanks! Jason It sounds that you need a decorator mapper to perform the functionality of your designs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Maximum Likelihood Estimation
subhaba...@gmail.com於 2013年2月2日星期六UTC+8上午1時17分04秒寫道: Dear Group, I am looking for a Python implementation of Maximum Likelihood Estimation. If any one can kindly suggest. With a google search it seems scipy,numpy,statsmodels have modules, but as I am not finding proper example workouts I am failing to use them. I am using Python 2.7 on Windows 7. Thanking You in Advance, Regards, Subhabrata I suggest you can google python and symbolic computation to get some package for your need first. Because it seems that you have to work out some math formula and verify some random process first of your data sources with noises . -- http://mail.python.org/mailman/listinfo/python-list
Re: Maximum Likelihood Estimation
在 2013年2月2日星期六UTC+8上午2时47分22秒,subhaba...@gmail.com写道: On Friday, February 1, 2013 11:07:48 PM UTC+5:30, 8 Dihedral wrote: subhaba...@gmail.com於 2013年2月2日星期六UTC+8上午1時17分04秒寫道: Dear Group, I am looking for a Python implementation of Maximum Likelihood Estimation. If any one can kindly suggest. With a google search it seems scipy,numpy,statsmodels have modules, but as I am not finding proper example workouts I am failing to use them. I am using Python 2.7 on Windows 7. Thanking You in Advance, Regards, Subhabrata I suggest you can google python and symbolic computation to get some package for your need first. Because it seems that you have to work out some math formula and verify some random process first of your data sources with noises . Dear Group, Thanks. I googled and found a new package named Sympy and could generate MLE graphs. Regards,Subhabrata. Well,just reveal more about your problems. But if you are concerned with some commercial problems, then it is not the novice apprentice level jokes. Then, maybe you can just give some outline of the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: advice, python for binary to xml
noydb於 2013年1月31日星期四UTC+8下午9時33分48秒寫道: I'm looking for knowlegde about how best to go about converting a binary file (from a GPS unit) to GPX/XML. I am completely clueless on this, so any start-from-the-beginning info would be greatly appreciated! I'm guessing the level of effort will be huge? Python 2.7, Windows 7 OK, since I was in charge of a project to retrieve the GPS with the RSA232 NMEA TEXT messages into a computer program before, I have not checked about the NMEA protocal (PUREASCII) for more than 10 years. But I worked with usb interfaces, too. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: Module access syntax
Chris Angelico於 2013年1月12日星期六UTC+8下午12時40分36秒寫道: On Sat, Jan 12, 2013 at 3:34 PM, Rick Johnson rantingrickjohn...@gmail.com wrote: *The problem:* ... is readability. The current dot syntax used ubiquitously in paths is not conveying the proper information to the reader, and in-fact obfuscating the code. Please explain how this is a problem. As Steven said, there is NO useful difference. I don't *care* whether it's a package, a module, or whatever. Module with class with static member? Fine. Package with module with class? Also fine. Imported special object that uses dunder methods to simulate either of the above? What's it matter to me, as long as I get my final result! Syntactic salt is seldom helpful. ChrisA This is somewhat like the following problem. Do we have to argue with people about the tastes of dishes in different restaurants ? Of course, I do because I love to enjoy fine dishes. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: Import resolution order
Ian於 2013年1月12日星期六UTC+8下午3時36分43秒寫道: On Fri, Jan 11, 2013 at 10:28 PM, Rick Johnson rantingrickjohn...@gmail.com wrote: On Friday, January 11, 2013 12:30:27 AM UTC-6, Chris Angelico wrote: Why is it better to import from the current directory first? Opps. I was not explicit enough with my explanation :). I meant, look in the current directory FIRST when in a package. Since many times (most all times) packages will contain many sub-modules that need to be imported into the package's main.py module, and sometimes these modules will have the same name as a stdlib module, then looking in the package FIRST makes sense. And again, in Python 2.x this is already the case. When importing in a package, it tries to do a relative import before it even looks at sys.path. I think if python where *strict* about full paths for non-builtins, then we would be in a better place. And again, in Python 3, where implicit relative imports have been removed from the language, it already is strict about using full paths. You can still do relative imports, but you have to be explicit about them. For instance you could create a package named chris and then have a module named math exist inside. Alternatively if you choose to be a non-professional and create a math module without a containing package, python would throw the module into the default lib package. The only way you could access your math module now would be by using the path lib.math. What if I create a package named math? Does that also automatically get renamed to lib.math? How is it decided what package names are proper; is it just because it happens to clash with a stdlib name that the package gets magically renamed? What if I create a package, and then later a module with the same name happens to be added to the stdlib? My program that uses the package just breaks because it no longer imports the correct thing? Damn i am full of good ideas! Your ideas might be better if you first spent some time gaining a better understanding of how the language works as is. OK, I think to develop a GUI with auto-code translations in an IDE with python as the CAD/CAM scripting language can be helpful. But usually this kind of sotware projects is in the commercial part. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANNOUNCE: Thesaurus - a recursive dictionary subclass using attributes
在 2013年1月10日星期四UTC+8下午7时34分23秒,Duncan Booth写道: Dave Cinege d...@cinege.com wrote: You will notice that the code is disgusting simple. However I have found that this has completely changed the way I program in python. I've re-written some exiting programs using Thesaurus, and often relized 15-30% code reduction. Additionally I find the new code much easier to read. And here's the same code written without your class but maintaining as far as possible the same structure. I find my version far easier to read then your's with all your spurious 'g.' 'L.' prefixes. - #!python2.7 from textwrap import dedent class Blob(object): pass prog = Blob() prog.VERSION = '1.0' # But isn't this so much cleaner? prog.NAME = 'Thesaurus' class TestClass: no = 'Class' way = 'this' def main (): tc = TestClass() l = ['Some', 'objects'] # Here's how you should create output without a fight. print dedent('''\ When programing python without {prog.NAME}, it is very easy to access your {l[1]}. {l[0]} people might say {prog.NAME} has no {tc.no}.''').format(prog=prog, l=l, tc=tc) if hasattr(prog, 'VERSION'): print 'But I challenge them to write code {tc.way} clean without it!'.format(**locals()) if __name__ == '__main__': main() - -- Duncan Booth http://kupuguy.blogspot.com An object can accquire new properties and methods in the run time without the limitations from the class definition of the object which belongs to. This is a true OOP language. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to call wget by python ?
Michael Torrie於 2013年1月10日星期四UTC+8上午11時04分31秒寫道: On 01/09/2013 07:11 PM, iMath wrote: can you give me an example code ? No but I can suggest some alternative ideas, such as using httplib (built into python), or libcurl. Or if you have to use wget, you run it the same way you run any external command from python. If it were my I'd plunk a few search terms in google, such as python run external process. Inherantly the python interpreter has a GC builtin to use pacakages like DLL by reference counting. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python programming philosophy
chaouche yacine於 2013年1月6日星期日UTC+8上午6時34分38秒寫道: The compiler reads your source code and parses it into parse trees. This is first step. It then takes the parse trees and transform them into abstract syntax trees, which are like a DOM tree in an HTML file, and then transform that AST into a control flow graph, and finally a bytecode is produced out of that control flow graph. The pyc files you see are this bytecode, so they are produced at the end. Anytime you edit your .py file, a new .pyc file is created if you invoke the python interpreter myfile.py on the former. If your .py file doesn't change, the .pyc file stays the same. Just like with java, this allows you to write a single .py file that can work on any platform without changing the source file, because all the cross platform issues are handled by the virtual machine. From: Nac Temha nacct...@gmail.com To: pytho...@python.org Sent: Saturday, January 5, 2013 11:05 PM Subject: Python programming philosophy Hello, I want to learn working principle of python as broadly. How to interpret the python? For example, what is pyc files and when does it occur? Can you explain them? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list Yes, check JYTHON tutorials to understand dynamic types. Java is still a fixed type computer language. -- http://mail.python.org/mailman/listinfo/python-list
Re: father class name
On Monday, December 31, 2012 12:18:48 PM UTC+8, contro opinion wrote: here is my haha class class haha(object): def theprint(self): print i am here The definition of a class named haha. haha().theprint() i am here haha(object).theprint() Traceback (most recent call last): File stdin, line 1, in module TypeError: object.__new__() takes no parameters why haha(object).theprint() get wrong output? You don't have to type the base class object. -- http://mail.python.org/mailman/listinfo/python-list
Re: dict comprehension question.
On Tuesday, January 1, 2013 11:10:48 AM UTC+8, Steven D'Aprano wrote: On Sat, 29 Dec 2012 18:56:57 -0500, Terry Reedy wrote: On 12/29/2012 2:48 PM, Quint Rankid wrote: Given a list like: w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1] I would like to be able to do the following as a dict comprehension. a = {} for x in w: a[x] = a.get(x,0) + 1 results in a having the value: {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1} Let me paraphrase this: I have nice, clear, straightforward, *comprehensible* code that I want to turn into an incomprehensible mess with a 'comprehension. That is the ironic allure of comprehensions. But... but... one liner! ONE LINNR Won't somebody think of the lines I'll save *wink* In case it's not obvious, I'm 100% agreeing with Terry here. List comps and dict comps are wonderful things, but they can't do everything, and very often even if they can do something they shouldn't because it makes the code inefficient or unreadable. There's nothing wrong with a two or three liner. -- Steven This is useful for not being choked in sorting a list by the notorious quick-sort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multi-dimensional list initialization
On Monday, November 5, 2012 3:07:12 PM UTC+8, Chris Rebert wrote: On Sun, Nov 4, 2012 at 10:27 PM, Demian Brecht demianbre...@gmail.com wrote: So, here I was thinking oh, this is a nice, easy way to initialize a 4D matrix (running 2.7.3, non-core libs not allowed): m = [[None] * 4] * 4 This is not clear in a name binding objective programming language. b=[1,2,3,4]*4 mb=[ b]*4 # check the behaviors and usages of reference copies # and shadow value copies and deep-value copies The way to get what I was after was: m = [[None] * 4, [None] * 4, [None] * 4, [None * 4]] (Obviously, I could have just hardcoded the initialization, but I'm too lazy to type all that out ;)) The behaviour I encountered seems a little contradictory to me. [None] * 4 creates four distinct elements in a single array while [[None] * 4] * 4 creates one distinct array of four distinct elements, with three references to it: Incorrect. In /both/ cases, the result is a list of length 4, whose elements are 4 (references to) the exact same object as the original list's element. Put simply, the list multiplication operator never copies objects; it just makes additional references to them. However, unlike a list object (as in your latter example), the object `None` is completely immutable (and what's more, a singleton value), so you just-so-happen *not to be able to* run into the same problem of mutating an object (assignment to an index of a list constitutes mutation of that list) that is referenced in multiple places, for you cannot mutate None in the first place!: x = None x.a = 42 Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'NoneType' object has no attribute 'a' # it doesn't overload any mutating operators: type(None).__dict__.keys() ['__hash__', '__repr__', '__doc__'] # and it obviously has no instance variables, # so, we can't modify it in any way whatsoever! (Lists, on the other hand, define item assignment, .pop(), .remove(), and a few other mutator methods.) a = [None] * 4 a[0] = 'a' a ['a', None, None, None] m = [[None] * 4] * 4 m[0][0] = 'm' m [['m', None, None, None], ['m', None, None, None], ['m', None, None, None], ['m', None, None, None]] Is this expected behavior Yes. It's also a FAQ: http://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list and if so, why? It's a general (albeit AFAIK unstated) principle that Python never copies objects unless you explicitly ask it to. You have encountered one example of this rule in action. In my mind either result makes sense, but the inconsistency is what throws me off. It is perfectly consistent, once you understand what list multiplication actually does. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: is implemented with id ?
On Wednesday, September 5, 2012 10:41:19 PM UTC+8, Steven D'Aprano wrote: On Wed, 05 Sep 2012 10:00:09 -0400, Dave Angel wrote: On 09/05/2012 09:19 AM, Franck Ditter wrote: Thanks to all, but : - I should have said that I work with Python 3. Does that matter ? - May I reformulate the queston : a is b and id(a) == id(b) both mean : a et b share the same physical address. Is that True ? Thanks, No, id() has nothing to do with physical address. The Python language does not specify anything about physical addresses. Some implementations may happen to use physical addresses, others arbitrary integers. And they may reuse such integers, or not. Up to the implementation. True. In principle, some day there might be a version of Python that runs on some exotic quantum computer where the very concept of physical address is meaningless. Or some sort of peptide or DNA computer, where the calculations are performed via molecular interactions rather than by flipping bits in fixed memory locations. But less exotically, Frank isn't entirely wrong. With current day computers, it is reasonable to say that any object has exactly one physical location at any time. In Jython, objects can move around; in CPython, they can't. But at any moment, any object has a specific location, and no other object can have that same location. Two objects cannot both be at the same memory address at the same time. So, for current day computers at least, it is reasonable to say that a is b implies that a and b are the same object at a single location. The second half of the question is more complex: id(a) == id(b) *only* implies that a and b are the same object at the same location if they exist at the same time. If they don't exist at the same time, then you can't conclude anything. -- Steven The function id(x) might not be implemented as an address in the user space. Do we need to distinguish archived objets and objects in the memory? -- http://mail.python.org/mailman/listinfo/python-list
Re: Negative array indicies and slice()
andrew...@gmail.com於 2012年10月29日星期一UTC+8上午11時12分11秒寫道: The slice operator does not give any way (I can find!) to take slices from negative to positive indexes, although the range is not empty, nor the expected indexes out of range that I am supplying. Many programs that I write would require introducing variables and logical statements to correct the problem which is very lengthy and error prone unless there is a simple work around. I *hate* replicating code every time I need to do this! I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't. Here's an example for Linux shell, otherwise remove /bin/env... {{{#!/bin/env python a=[1,2,3,4,5,6,7,8,9,10] print a[-4:3] # I am interested in getting [7,8,9,10,1,2] but I get []. }}} I'll suggest to use the reverse method to get what you want. Of course, the reverse method is not efficient for a list of a huge number of objects in python. -- http://mail.python.org/mailman/listinfo/python-list