Re: JUST GOT HACKED
On Wednesday, October 2, 2013 5:43:32 AM UTC-5, Ferrous Cranus wrote: > > I only re-ask the same thing if: > > > 1. Di not understood what was provided or proposed to me as being a solution > > 2. Still feel that that the solution provided to me doesn't meet my > needs and should have been re-written in a different way. Nevertheless > we are all improving, especially the newbies, by seeing alternative way, > best methods and wise practices of writing code for the specific problem > and pick the one that does the job best. > If you feel that the provided solution doesn't meet your needs then the *most likely* answer is that you have asked the wrong question. Rather than, say, posting a new thread (unless your new question is clearly different and mostly unrelated), the appropriate course of action is to say something like, "Hey, apparently I'm asking the wrong question, because all these answers are about frobnosticating, but I really wanted to foo the baz." If you don't acknowledge that you goofed up, you come across as arrogant or ignorant (or both). -W -- https://mail.python.org/mailman/listinfo/python-list
Re: JUST GOT HACKED
On Tuesday, October 1, 2013 5:06:38 PM UTC-5, Ben Finney wrote: > This is an unmoderated forum, so we have occasional spates of persistent > > nuisances, and those who respond with the maturity level and impulse > > control of an average six-year-old. Hey! That's so degrading! I don't know many six-year-olds (and certainly not mine, but maybe they're just not average) who would continue to respond in the same fashion that the OP of *this* thread did! ;-) -W -- https://mail.python.org/mailman/listinfo/python-list
Re: better and user friendly IDE recommended?
On Thu, 12 Sep 2013, Ben Finney wrote: Better to learn these once, in a single powerful tool that can be maintained independent of any one vendor for as long as its community is interested. And if you're a developer, even a community of one is enough ;) -W -- https://mail.python.org/mailman/listinfo/python-list
Re: Language design
On Tue, 10 Sep 2013, Ben Finney wrote: The sooner we replace the erroneous “text is ASCII” in the common wisdom with “text is Unicode”, the better. I'd actually argue that it's better to replace the common wisdom with "text is binary data, and we should normally look at that text through Unicode eyes". A little less catchy, but more accurate ;) -W-- https://mail.python.org/mailman/listinfo/python-list
Re: print function and unwanted trailing space
On Sat, 31 Aug 2013, candide wrote: # - for i in range(5): print(i, end=' ') # <- The last ' ' is unwanted print() # - Then why not define end='' instead? -W -- https://mail.python.org/mailman/listinfo/python-list
Re: Moving to Python for web
On Thu, 29 Aug 2013, Andreas Ecaz wrote: I've decided to go with Flask! It's now running on UWSGI with NGINX. Hopefully I can get some stuff done :) @Chris “Kwpolska” Warrick I just don't like the big frameworks, for me there is too much magic going on. I'm a huge fan of Flask - I also find that when you start to learn more and more about Flask you can see how Django would be super useful, if you need all the bells and whistles. -W-- https://mail.python.org/mailman/listinfo/python-list
Re: Python performance
On Fri, 2 Aug 2013, Schneider wrote: Hi list, I have to write a small SMTP-Relay script (+ some statistic infos) and I'm wondering, if this can be done in python (in terms of performance, of course not in terms of possibility ;) ). It has to handle around 2000 mails per hour for at least 8hours a day (which does not mean, that it is allowed not to respond the rest of the day. Can this be done? or should I better use some other programming language? My second choice would be erlang. Check out Kenneth Rietz's inbox.py[1] "It's quite quick. One instance should handle over one thousand emails per second." So it should be able to handle your hour's load in oh, say 2 seconds? ;) HTH, W [1]: https://crate.io/packages/inbox/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging help
On Thu, 1 Aug 2013, Joseph L. Casale wrote: I have a couple handlers applied to a logger for a file and console destination. Default levels have been set for each, INFO+ to console and anything to file. How does one prevent logging.exception from going to a specific handler when it falls within the desired levels? There is probably a better way, I'm not too familiar with the more advanced logging, but off the top of my head I'd suggest subclassing the Handler classes that you're interested in and overriding the Handle method (I think - you can check the source to be sure) and if the type of message is exception then just skip handling it. Alternatively, you could simply create a different logger, e.g. exc_logger = logging.getLogger('mything.exceptions') And use that to log exceptions. Oh hai - as I was reading the documentation, look what I found: http://docs.python.org/2/library/logging.html#filter Methinks that should do exactly what you want. HTH, W -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python 'enable' poke and hope programming?
On Thu, 1 Aug 2013, CM wrote: (My subject line is meant to be tongue and cheek inflammatory) I've been thinking about why programming for me often feels like ice skating uphill. I think part of the problem, maybe the biggest part, is what now strikes me as a Very Bad Habit, which is "poke and hope" (trial and error) programming (of several names this page provided, I kind of like that one): http://en.wikipedia.org/wiki/Programming_by_permutation It seems that if I can make a change to the code and then immediately test it by running the Python interpreter and finding out, in a few seconds, if it worked, I am going to be *much* more likely to use this trial-and-error approach than if I had to use a compiled language, since compiling takes so long. E.g. "Oh, that doesn't work? Maybe if I add this...no. OK, what about if I increment that? No...OK, wait, maybe this...AH! That worked." (obviously it is not quite that uninformed all the time). Instead, with a compiled language, because of the pain of having to wait for the newest version to compile, one would be encouraged to get the mechanism of how something works *clear* and robustly represented in one's mind (or on scrap paper/notes document) prior to testing through compiling and running. Basically this amounts to: with an interpreted language (so of course this is not really just about Python--I just think in terms of Python), it's easier to be mentally lazy. But, ironically, being lazy winds up creating *way* more work ultimately, since one winds up programming in this terribly inefficient way, and progress proceeds at an, at times, evolutionary (slow!) pace. And of course I am not really blaming it on Python or any interpreted language; I am blaming it fully on my own lame habits and attitude. I'm sick of this in my own work, and want to avoid this trap as much as I can from now on. Thoughts? I see that many others have had thoughts already - but rather than take the time to read their responses and either find out that they said the same thing (oops, sorry!) or become influenced by their arguments, I feel like I should respond to this with a clean slate. I don't think that Python enables the "poke and hope" style programming (I like the name!) any more than a compiled language does - if you're doing it right. Example: My brother had a kid in his C++ class that would go about randomly flipping >, <, <=, >= signs until he got the behavior that he wanted. There was no mental effort of thinking about the problem or applying the scientific method - i.e. form a hypothesis, test the hypothesis, check results. My experience is that people who go throughout their programming careers without this attitude will do it whether it requires several seconds (or minutes) of compile time or not. Whether or not it's a conscious choice I don't know - at least in your case you seem to desire to make a conscious choice in the direction of "wait a minute, this is a stupid way to program". Though "poke and hope" is headed in the right direction, I think it's a bit naive and misses the very essential nature of the better (best?) method - formulation of a /real/ hypothesis. For instance "I think my program will work" is a hypothesis of exactly the same quality of, "When I turn on my water faucet, it will rain." Of course the smaller the application, the more valid the original hypothesis. For instance, the "poke and hope" programmer might write this program: x = 3 if x > 3: print "x is less than 3" else: print "x is greater than 3" And then of course make the weak hypothesis "if I change my > to < then maybe my program will work" - or "if I change my x to 5 then maybe my program will work". The problem is that these are really just random guesses - flips of the coin that eventually might produce a correct result - but only because of the monkeys[1]. What you really want is to actually understand cause and effect at a more fundamental level (in programming) than what you may currently enjoy. And this is in fact something that, while makes it easier for the "poke and hope", also provides a much more enjoyable laboratory experience for the initiated. And when you combine that with the REPL (interactive interpreter) you get an embarassingly powerful laboratory in which to experiment to your heart's delight. For instance, say you want to really understand the previous example. You could do something like so: >>> x = 3 >>> x > 3 False >>> x < 3 False >>> x >= 3 True >>> x <= 3 True >>> x == 3 True And *this* type of "poke and hope" *is* actually valuable. This is where understanding is formed, and high-quality developers are forged. At your fingertips you begin to see "A hah! so *that's what this does!" You are free to explore and play and understand the rules of the system. And you can build on the previous experiments: >>> if x > 3: ... print("
Re: Simple Python script as SMTP server for outgoing e-mails?
On Thu, 1 Aug 2013, Gilles wrote: On Wed, 24 Jul 2013 10:38:52 -0400, Kevin Walzer wrote: Thanks. hMailServer was one of the apps I checked, and I was just making sure there weren't something simpler, considering my needs, ideally something like Mongoose MTA. Have you checked Kenneth Rietz's inbox.py[1]? It's fairly simple to use/extend and might fit your modest needs. -W [1]:https://crate.io/packages/inbox/ -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP8 79 char max
On Wed, 31 Jul 2013, Joshua Landau wrote: To explain, I tend to take the "HTML" form of alignment by wrapping: open stuff stuff stuff close to open stuff stuff stuff close Depending on how much 'stuff' I have, I, for one, prefer a third: open stuff stuff stuff close Which then makes it 1) fairly easy to read, 2) fairly easy to extend. Of course it could just be that I'm used to that style - our brains are wired weird. -W-- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Python 3 and web applications?
On Fri, 26 Jul 2013, Rui Maciel wrote: I'm currently learning Python, and I've been focusing on Python3. To try to kill two birds with one stone, I would also like to learn the basics of writing small web applications. These web applications don't need to do much more than provide an interface to a small database, and they may not even be required to be accessible outside of a LAN. Does anyone have any tips on what's the best way to start off this adventure? Take a look at the Python3 branch of Flask: https://github.com/mitsuhiko/flask.git And the werkzeug webserver: https://github.com/mitsuhiko/werkzeug.git If you download these you can install them with: python setup.py install (werkzeug first, then flask) Here's the most basic webserver you can create that way: from flask import Flask app = Flask(__name__) @app.route("/") def main(): return "Hello, Web!" if __name__ == "__main__": app.run() And yet flask is highly extensible with a lot of plugins. HTH, W -- http://mail.python.org/mailman/listinfo/python-list
Re: UTF-EBCDIC encoding?
On Mon, 15 Jul 2013, Kev Dwyer wrote: Joel Goldstick wrote: On Fri, Jul 12, 2013 at 3:12 PM, Skip Montanaro wrote: I can't help you. I'm astonished. Trying to imagine the work environment where this technology would be necessary http://www.iseriespython.com/app/ispMain.py/Start?job=Home Skip I remember the AS400 series.. although I never worked with one. What kind of business still use that stuff? Is it for large corporation accounting, MIS stuff? Some banks still run legacy systems on AS/400s, and I've seen them used for airline booking systems and retail POS. Sadly there are many larger corporations that have oodles of legacy code on the Mainframe. We run z/OS and IBM DB2 here. In my off time I fiddle around with Python in an attempt to make life more enjoyable - and one of these forays has led me to attempt to unpack some packed data. Which is also an interesting (if not terribly useful) project. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Dihedral
On Mon, 15 Jul 2013, Devyn Collier Johnson wrote: On 07/15/2013 08:36 AM, Steven D'Aprano wrote: On Mon, 15 Jul 2013 06:06:06 -0400, Devyn Collier Johnson wrote: On 07/14/2013 02:17 PM, 8 Dihedral wrote: [...] Do we want volunteers to speed up search operations in the string module in Python? It would be nice if someone could speed it up. Devyn, 8 Dihedral is our resident bot, not a human being. Nobody knows who controls it, and why they are running it, but we are pretty certain that it is a bot responding mechanically to keywords in people's posts. It's a very clever bot, but still a bot. About one post in four is meaningless jargon, the other three are relevant enough to fool people into thinking that maybe it is a human being. It had me fooled for a long time. Wow! Our mailing list has a pet bot. I bet other mailing lists are so jealous of us. Who ever created Dihedral is a genius! Artificial Intelligence developers put chatbots on mailing lists so that the program can learn. I use Python3 to program AI applications. If you see my Launchpad account, you will see my two AI projects - Neobot and Novabot. (https://launchpad.net/neobot Neo and Nova are still unstable) AI developers let their bots loose on the Internet to learn from people. Dihedral is learning from us. Dihedral only responses when it feels it has sufficient knowledge on the topic. Chatbots want to appear human. That is their goal. We should feel honored that Dihedral's botmaster feels that this mailinglist would benefit the development of Dihedral's knowledge. Are *you* a bot? ~_^ That post felt surprisingly like Dihedral... -W -- http://mail.python.org/mailman/listinfo/python-list
Re: GeoIP2 for retrieving city and region ?
On Sat, 13 Jul 2013, Νικόλας wrote: But then how do you explain the fact that http://www.maxmind.com/en/geoip_demo pinpointed Thessaloníki and not Athens and for 2 friends of mine that use the same ISP as me but live in different cities also accurately identified their locations too? If you bothered doing something as simple as read the Wikipedia article on Geolocation, you could answer this question yourself: Evidently you, and your friends have things like cookies, or some other helps that identify your location, which is why your addresses are close. -W-- http://mail.python.org/mailman/listinfo/python-list
Re: Ideal way to separate GUI and logic?
On Sat, 13 Jul 2013, fronag...@gmail.com wrote: Well, I'm a newcome to Python, but I'm developing a program with a GUI in tkinter, and I'm wondering what is the best, 'most pythonic' way of doing this? I could, obviously, write a monolithic block of code. True, you could, but don't do that. You should investigate strategies like model view presenter, and test or behavior driven development. My recommendation echos the other advice you've been given. Basically you think of your application in terms of two problems or domains. One is the what that you want no do. What information do you need? The other problem is how do you get that information from the user and retun to them information than they need? Regardless of which side you have driving, UI or Presenter, having a design such as this allows for much cleaner code. HTH -W -- http://mail.python.org/mailman/listinfo/python-list
Re: GeoIP2 for retrieving city and region ?
On Sat, 13 Jul 2013, Νικόλας wrote: But it works for me, How can it be impossible and worked for me at the same time? 2 + 2 = 4 2 + 6 = 8??? Why can't I make 2 and 6 equal 4? It worked for 2, so I know it's not impossible! I don't care what everyone says, I was able to make one case work so obviously I juat need to figure out how to make it work! Allegorically, W-- http://mail.python.org/mailman/listinfo/python-list
UTF-EBCDIC encoding?
Is anyone aware of a UTF-EBCDIC[1] decoder? While Python does have a few EBCDIC dialects in the codecs, it does not have the (relatively new?) UTF-EBCDIC one. Additionally, if anyone is aware of a Python tool that can unpack a mainframe PDS file, that would also be worthwhile. Thanks, Wayne [1]: https://en.wikipedia.org/wiki/UTF-EBCDIC -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 0: invalid start byte
On Thu, 4 Jul 2013, Νίκος Γκρ33κ wrote: Στις 4/7/2013 6:10 μμ, ο/η MRAB έγραψε: What do you mean "I don't know how to catch the exception with OSError"? You've tried "except socket.gaierror" and "except socket.herror", well just write "except OSError" instead! try: host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0] except OSError: host = "UnResolved" produces also an internal server error. Are you sure is just except OSError ? Have you ensured that 'REMOTE_ADDR' is actually a key in os.environ? I highly recommend using the logging module to help diagnose what the actual exception is. HTH, -W-- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On Fri, 5 Jul 2013, Chris Angelico wrote: Oh. Uhm... ahh... it would have helped to mention that it also has a commit() method! But yes, that's correct; if the object expires (this is C++, so it's guaranteed to call the destructor at that close brace - none of the Python vagueness about when __del__ is called) without commit() being called, then the transaction will be rolled back. If one wants to duplicate this kind of behavior in Python, that's what context managers are for combined with a `with` block, which does guarantee that the __exit__ method will be called - in this case it could be something as simple as: from contextlib import contextmanager @contextmanager def new_transaction(conn): tran = conn.begin_transaction() yield tran if not tran.committed: tran.rollback() Which you would then use like: conn = create_conn() with new_transaction(conn) as tran: rows_affected = do_query_stuff(tran) if rows_affected == 42: tran.commit() And then you get the desired constructor/destructor behavior of having guaranteed that code will be executed at the start and at the end. You can wrap things in try/catch for some error handling, or write your own context manager class. HTH, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Default scope of variables
On Thu, 4 Jul 2013, Steven D'Aprano wrote: [1] Based on empirical evidence that Python supports names with length at least up to one million characters long, and assuming that each character can be an ASCII letter, digit or underscore. The specification *does* state unlimited length: http://docs.python.org/release/2.5.2/ref/identifiers.html Though practicality beats purity. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS or not? [was Re: How to tell Script to use pythonw.exe ?]
On Wed, 3 Jul 2013, Dennis Lee Bieber wrote: Consider that the Powershell default is to /prevent/ execution of script files unless some security settings have been changed; even local script files need to be "signed" to be executed. Protip: No they don't - wrap it in a cmd/bat file and have it launch powershell[1]: powershell -ExecutionPolicy Bypass -File ... \o/ Microsoft "security" at it again! (reminds me a bit of just pushing "Cancel" to log into windows 98, I think it was) -W [1]: http://stackoverflow.com/q/728143/344286 -- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On Fri, 28 Jun 2013, Joel Goldstick wrote: On Fri, Jun 28, 2013 at 2:52 PM, Wayne Werner wrote: On Fri, 28 Jun 2013, 8 Dihedral wrote: 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. Best. Post. EVER. In the 'general' category? or by a 'bot'? I think generally - because Dihedral is a bot. I don't think it would be nearly as awesome if it were a person. -W-- http://mail.python.org/mailman/listinfo/python-list
Re: FACTS: WHY THE PYTHON LANGUAGE FAILS.
On Fri, 28 Jun 2013, 8 Dihedral wrote: 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. Best. Post. EVER. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine actually given command line arguments
On Wed, 15 May 2013, Henry Leyh wrote: Yes, I was trying that and it sort of works with strings if I use something sufficiently improbable like "__UNSELECTED__" as default. But it gets difficult with boolean or even number arguments where you just may not have valid "improbable" defaults. You could now say, so what, it's the default anyway. But in my program I would like to distinguish between given and not given arguments rather than between default and non-default. Have you looked into docopt? It's pretty awesome, and might really help in this case. HTH, -W -- http://mail.python.org/mailman/listinfo/python-list
Re: object.enable() anti-pattern
On Mon, 13 May 2013, Greg Ewing wrote: Wayne Werner wrote: On Fri, 10 May 2013, Gregory Ewing wrote: f = open("myfile.dat") f.close() data = f.read() To clarify - you don't want a class that has functions that need to be called in a certain order with *valid input* in order to not crash. Exactly what does happen - a ValueError is raised because you're(*) passing self into the file.read() function, and that input is invalid The same argument can be applied to: foo = Foo() foo.do_something() foo.enable() # should have done this first You're passing an invalid input to Foo.do_something, namely a Foo that hasn't been enabled yet. That is the crux of the argument - as designer of the class *you* need to ensure that when your constructor is done, your class is in a stable state. And that every other state transition (with valid input) results in your class then being in a stable state. If anything, the stronger argument is that `file.close()` is not a well designed function because it leaves your object in an unstable state. Which I would be inclined to agree with, but I couldn't give you the answer for what makes it better. Because the answer is the best one you can get in computer science: It depends. The reason that it depends, is because it depends on what you want to do. Do you want a program that seems purely functional? Do you want a program that's easy to maintain? Do you want a program that more accurately models the "real world"? Personally, I think the file object API in Python is about as good as it can get - but that's because it's working with "physical" things (i.e. files - bits on a platter, or flash/SSD drive...) which necessarily have a temporal nature. And it's much less badness to blow up on a call to `read` than it is to remove the `read` function and die with a NameError when the underlying file is in a closed state. At least in my opinion ;) -W -- http://mail.python.org/mailman/listinfo/python-list
Re: object.enable() anti-pattern
On Fri, 10 May 2013, Gregory Ewing wrote: Wayne Werner wrote: You don't ever want a class that has functions that need to be called in a certain order to *not* crash. That seems like an overly broad statement. What do you think the following should do? f = open("myfile.dat") f.close() data = f.read() To clarify - you don't want a class that has functions that need to be called in a certain order with *valid input* in order to not crash. Exactly what does happen - a ValueError is raised because you're(*) passing self into the file.read() function, and that input is invalid input - specifically: ValueError: I/O operation on closed file *where you actually means python, because when you call `your_instance.method()`, it works effectively like a call to `YourClass.method(your_instance)` -W -- http://mail.python.org/mailman/listinfo/python-list
Re: object.enable() anti-pattern
On Fri, 10 May 2013, Robert Kern wrote: On 2013-05-10 12:00, Steven D'Aprano wrote: But either way, that's fine. You've found an object where it does make sense to have an explicit "make it go" method: first one entity has permission to construct the object, but not to open the underlying file. Another entity has permission to open the underlying file, but not to create the object. I have no idea whether this is a reasonable security design or not, it actually sounds a bit rubbish to me but what do I know? So let's treat it as a reasonable design. As I've said, repeatedly, that's not what I'm talking about. When you DON'T have useful things that can be done with the object before calling "enable", then it is an anti-pattern to require a separate call to "enable" method, and the enable functionality should be moved into the object constructor. If you DO have useful things that can be done, like pass the object to another entity, for security, then that's a whole 'nuther story. I'd be curious to see in-the-wild instances of the anti-pattern that you are talking about, then. I think everyone agrees that entirely unmotivated "enable" methods should be avoided, but I have my doubts that they come up very often. Do programmers have a natural tendency to make an extra, completely unnecessary method? I would think that they have a natural tendency to the opposite. In my experience, everyone has a reason in mind when they follow a pattern/anti-pattern. It is pretty rare that someone just does some specific, nameable thing for no reason at all. There is no need to call out an anti-pattern for which no one has a reason to do it. But there is a continuum of reasons. Some reasons are better than others. Some reasons only apply in a small set of circumstances but seem like they would apply more generally, at least to novice programmers. Programmers can be wrong about what they think the (anti-)pattern actually achieves. The whole point of naming an anti-pattern is to discuss those reasons, show where they are misapplied, where YAGNI, why novices overuse it, other patterns that should be used instead, and also the circumstances where it is actually a good pattern instead. I'll share the anti-pattern that I've seen many times (not actually in Python) class CoolPresenter: def __init__(self): self.view = None self.some_property = None self.other_property = None def initialize(self): self.view.disable() data = self.load_data() self.view.data = data self.view.enable() def reload(self): if self.view is None: raise NotInitializedError("Error: Please setup class") self.view.disable() data = self.load_data() self.view.data = data self.view.enable() Then you would see code like this: presenter = CoolPresenter() presenter.view = CoolView() This is just plain silly for a few reasons: - It's ambiguous. I don't know what's required for the CoolPresenter to function properly. - The temporal coupling mentioned earlier. I can create an instance of a class and then call a function (say `reload`) and then boom! My program crashes. There is *no possible* use case of this class where you can use it without a view. The motivation behind this anti-pattern that I've seen is the desire to not have a constructor that "does too much". So you end out with an empty constructor and temporal coupling, and a terrible API that doesn't clearly explain the requirements of the class. Your class constructor should *require* everything that is necessary to have a stable state when the class is created (i.e. you should be able to properly call any function, set any property without an exception happening) Why? Less bugs, easier to comprehend, change/update your code. Easier to use the class. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: object.enable() anti-pattern
On Wed, 8 May 2013, Steven D'Aprano wrote: I'm looking for some help in finding a term, it's not Python-specific but does apply to some Python code. This is an anti-pattern to avoid. The idea is that creating a resource ought to be the same as "turning it on", or enabling it, or similar. For example, we don't do this in Python: I'm not entirely sure what the name of it is, but the basic concept is that you should never partially create, or create a class that can be in an unstable state. Which isn't to say you should prevent invalid input, only that with every valid input or single operation (including construction) your class should be valid. Ah, that's it - the problem is that it introduces /Temporal Coupling/ to one's code: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling/ You don't ever want a class that has functions that need to be called in a certain order to *not* crash. That's fine if you have to call them in a certain sequence in order to get the correct data - that's what programming is all about, after all. But if you provide me a class with a constructor you better make sure that when I do this: thing = YourSuperAwesomeClass() thing.do_stuff() that I don't get some horrid stack trace ending with InvalidStateError: initialize() needs to be called before do_stuff() Or something worse. HTH, Wayne p.s. I'm interested in reading whatever is evenually written on the topic -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding NaN in JSON
On Sat, 20 Apr 2013, Chris “Kwpolska” Warrick wrote: On Fri, Apr 19, 2013 at 9:42 PM, Grant Edwards wrote: The OP asked for a string, and I thought you were proposing the string 'null'. If one is to use a string, then 'NaN' makes the most sense, since it can be converted back into a floating point NaN object. I infer that you were proposing a JSON null value and not the string 'null'? Not me, Wayne Werner proposed to use the JSON null value. I parsed the backticks (`) used by him as a way to delimit it from text and not as a string. That was, in fact, my intention. Though it seems to me that you'll have to suffer between some sort of ambiguity - in Chrome, at least, `Number(null)` evaluates to `0` instead of NaN. But `Number('Whatever')` evaluates to NaN. However, a JSON parser obviously wouldn't be able to make the semantic distinction, so I think you'll be left with whichever API makes the most sense to you: NaN maps to null or NaN maps to "NaN" (or any other string, really) Obviously you're not limited to these particular choices, but they're probably the easiest to implement and communicate. HTH, -W-- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding NaN in JSON
On Wed, 17 Apr 2013, Miki Tebeka wrote: I'm trying to find a way to have json emit float('NaN') as 'N/A'. No. There is no way to represent NaN in JSON. It's simply not part of the specification. I know that. I'm trying to emit the *string* 'N/A' for every NaN. Why not use `null` instead? It seems to be semantically more similar... -W -- http://mail.python.org/mailman/listinfo/python-list
Re: anyone know pandas ? Don't understand error: NotImplementedError...
On Wed, 17 Apr 2013, someone wrote: File "/usr/lib/pymodules/python2.7/pandas/tseries/offsets.py", line 214, in rule_code raise NotImplementedError NotImplementedError Can anyone tell why this error appears and how to fix it? I don't know anything about pandas, but my recommendation? $ vim /usr/lib/pymodules/python2.7/pandas/tseries/offsets.py (or nano or emacs - whatever editor you're comfortable with). Go to line 214, and take a look-see at what you find. My guess is it will be something like: def rule_code(): raise NotImplementedError() Which is terribly unhelpful. HTH, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: dynamic forms generation
On Tue, 16 Apr 2013, andrea crotti wrote: This is not really scalable, and we want to make the whole thing more generic. So ideally there could be a DSL (YAML or something else) that we could define to then generate the forms, but the problem is that I'm quite sure that this DSL would soon become too complex and inadeguate, so I'm not sure if it's worth since noone should write forms by hands anyway. Between the things that we should be able to do there are: - dependent fields - validation (both server and client side, better if client-side auto-generated) - following DRY as much as possible Any suggestions of possible designs or things I can look at? I would highly recommend a look at Flask, and Flask-WTF in particular. It's fairly easy to write forms, and with only a bit of setup you can end out with some fairly generic systems. I don't think that by default it does any client-side validation generation, but as the HTML for the forms are completely generated, extending the form and adding validation logic to the output wouldn't be too difficult. Example: # form.py from flask.ext.wtf import Form, TextField, Required class MyBasicForm(Form): some_text = TextField("Put some text here:", validators=[Required()]) # View/HTML {% extends 'base.html' %} {{ form.some_text.label() }}{{ form.some_text(size=40) }} # Server code @app.route("/basic_form", methods=['GET', 'POST']) def basic(): form = MyBasicForm() if form.validate_on_submit(): do_the_needful(form.some_text.data) return redirect(url_for('main')) return render_template('basic_form.html', form=form) Obviously a really basic example. Check out Flask here: http://flask.pocoo.org/ And Flask WTF here: http://pythonhosted.org/Flask-WTF/ HTH, Wayne-- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with sockets and threads
On Thu, 11 Apr 2013, Dexter Deejay wrote: Yeah, that seems to be problem. Waiting for message is in theory infinite. But why doesn't this separate thread leave processor while it is sleeping? As far as I've been able to tell? Magic ;) But I haven't really dug into it. If you're really doing some waiting stuff you might want to look into some other type of message passing mechanism, e.g. launch a subprocess to do ths listening and then writing to a file and checking that from within Tkinter. I expect there are other possibilities that more advanced people may be able to recommend and are probably better. But that seems like it would work. HTH, -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems with sockets and threads
On Thu, 11 Apr 2013, Dexter Deejay wrote: When i try to run this code and to connect to server (server is written in java that part of code is ok) everything stalls. Thread that i created here occupies processor all the time and GUI freezes. It's supposed to be waiting for message from server. (asynchronous one) Is there something that i did wrong here, or is there better way to do this? from tkinter import * from threading import * Everything I've read or used suggests to me that threading+tkinter is a dangerous combination. Mainly because tkinter already has an event loop, so when you start mixing threads things tend to go sideways. Instead what you'll want to do is put processing in the .after or .after_idle callbacks - just make sure that whatever is doing is quick (or can do a portion of the activity quickly). HTH, -W -- http://mail.python.org/mailman/listinfo/python-list
Re: "monty" < "python"
On Thu, 21 Mar 2013, Roy Smith wrote: In article , Terry Reedy wrote: On 3/20/2013 10:03 AM, franzferdinand wrote: Ok, thanks everybody! Threads are like the Sorcerer's Apprentice. You can start 'em, but you cannot stop 'em ;-) Of course you can stop threads. Just call _exit(). No more threads! Thank you for making me laugh this morning - I found that extremely amusing. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Jinja2 installation help
On Fri, 8 Feb 2013, Robert Iulian wrote: Hello, I recently started learning Python. Just finished learning the basis of it, and now I think I'm ready to start working on a simple website but I am having some difficulties installing Jinja2. Can anyone post a dummy guide on how to install it, and what to do step by step? I am using the lastest Python version 3.3 . Do you have easy_install or pip installed? If you do, $ pip install jinja2 And that's it! HTH, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: The best, friendly and easy use Python Editor.
On Thu, 24 Jan 2013, Tim Chase wrote: On 01/24/13 13:34, Leonard, Arah wrote: All true (especially the holy wars bit!). OP didn't (as far as I can see) even say which OS he is using. Anyway, my suggestion is generally that people use the editor with which they are already comfortable. Sound advice. [snip] Whatever works is what works. It's just a text file after all. So even "ed" or "edlin" or even "cat" would do ;-) ? -tkc ? wq ed *is* the standard editor. Also, I see what you did there ;) -w . wq -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On Fri, 4 Jan 2013, Roy Smith wrote: In article , Cameron Simpson wrote: On 01/04/13 01:34, Anssi Saari wrote: | Just curious since I read the same thing in a programming book recently | (21st century C). So what's the greatness that terminal multiplexors | offer over tabbed terminals? Especially for software development? There's no doubt that you need access to multiple terminal sessions. Whether you achieve that with multiple terminal windows on your desktop, multiple desktops, tabbed terminals, or something like screen is entirely personal preference. +1 I use a tiling WM (awesomewm), but I still find that tmux has its place. Usually I'll have a terminal per box that I'm working on, and a tmux session within that. This allows me to detach and reattach from any system I'm on. In addition, if I lose my connection, I don't have to figure out which processes I had in bg. There's also the neat ability (at least with tmux - I haven't used screen for a while now) to work across sessions - so I might have a personal session (with things like alpine and irssi), a dev session (with Vim, a python prompt, and a shell) - and I can either keep them separate if I need to focus, or join the windows if I need some help. One thing that I've noticed that tmux does poorly is handle the mouse for selecting. And as I haven't yet written or found a cross-platform/machine clipboard manager, using the tmux copy or xclip doesn't really help that much :P I'd say the main benefit (aside from tiling) is the attach/detach. Unless your machine powers off or you kill tmux/screen, your sessions will stay around. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On Tue, 1 Jan 2013, Ramchandra Apte wrote: On Friday, 28 December 2012 01:31:16 UTC+5:30, mogul wrote: 'Aloha! I'm new to python, got 10-20 years perl and C experience, all gained on unix alike machines hacking happily in vi, and later on in vim. Now it's python, and currently mainly on my kubuntu desktop. Do I really need a real IDE, as the windows guys around me say I do, or will vim, git, make and other standalone tools make it the next 20 years too for me? Oh, by the way, after 7 days I'm completely in love with this python thing. I should have made the switch much earlier! /mogul %-) I use Eclipse only because it has PEP 8 and Pylint integration. Ezio Melotti, core Python developer, said in personal chat, that he uses Kate. IDEs aren't that useful when coding in Python. I concur. I think it's because with a language that has 43(?) keywords and I believe it's 12 different statement types, you can easily fit it all in your head. What you can't fit in your head is found in the docstrings of whatever you're using. Give me an interactive interpreter, vim, and a web browser, and I'm more than fine. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On Tue, 1 Jan 2013, Mitya Sirenef wrote: On 01/01/2013 02:02 PM, Roy Smith wrote: That's true with Vim, as well, especially when I'm making a custom mapping and I can NEVER remember what some combination does, even though if I actually needed to use it, it pops right out, so to find out, I have to try it and then I say, "of course, dammit, I use this command 50 times every single day!"; so it's a curious case of one-directional memory. I've found writing macros helps me a lot in this regard. I do qaq"aP fairly frequently. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: New to python, do I need an IDE or is vim still good enough?
On Wed, 2 Jan 2013, Michael Torrie wrote: On 01/01/2013 11:43 AM, Mitya Sirenef wrote: Therefore, deleting 3 WORDs is 3daW (mnemonic: del a WORD 3 times). Interesting. I typically use just d3w. 3daW seems to delete 3 lines for me, the same result as d3. Another favorite command is d or c followed by a number and then the right arrow key, for manipulating letters instead of words. Right arrow and not l? Surely you jest! ;) In any case, I can be way more productive with just a few commands (maybe 3 or 4 commands or concepts) in Vim than in almost any GUI editor. In my experience, Vim users almost always find this to be true for them as well. Vim really hits the sweet spot for productivity and usability. The only thing about Vim that I find clunky is how code folding macros work, and also code completion hacks (which I have never needed anyway). Yep. That's how I feel. I had used ViEmu in Visual Studio for coding in .NET at work - but I found that the buffers & macros were more powerful. So now I do most of my programming in Vim, and only head to VS if I need autocomplete or some of it's auto-generation tools. (I'm even writing this email in Vim as my external editor from alpine ;) -W -- http://mail.python.org/mailman/listinfo/python-list
Re: context aware execution
On Thu, 20 Dec 2012, Chris Angelico wrote: On Thu, Dec 20, 2012 at 2:57 AM, Bart Thate wrote: I want in a function or method determine the context of my caller and adapt the functionality accordingly. First off, please don't! Your code will be *extremely* confusing. Usually, the best way to adapt to your caller's environment is to be passed a parameter that specifies the change. Or assume that the caller is smart enough to determine which one of the functions to call, and provide them, with good names. -W -- http://mail.python.org/mailman/listinfo/python-list
Re: Why Doesn't This MySQL Statement Execute?
On Tue, 18 Dec 2012, Tom Borkin wrote: Hi; I have this test code: if i_id == "1186": sql = 'insert into interactions values(Null, %s, "Call Back", "%s")' % (i_id, date_plus_2) cursor.execute(sql) db.commit() print sql It prints the sql statement, but it doesn't execute. If I copy and paste the sql into the mysql command line it does execute without warnings or errors. What gives? Does date_plus_2 contain "Robert"); DROP TABLE interactions; -- By any chance? -W-- http://mail.python.org/mailman/listinfo/python-list
Re: Posix call (execve) breaks mercurial?
On Thu, 11 Oct 2012, Wayne Werner wrote: So here's where things got weird. I could call `subprocess.check_output(['hg', 'root'])`, and things worked just fine. But when I added the env parameter, I got the untrusted issues. So if I did: import os, subprocess # Works just fine subprocess.check_output(['hg', 'root']) # Gives untrusted issues subprocess.check_output(['hg', 'root'], env=os.environ) So... curiouser and curiouser - it looks like it's not *actually* execve's fault after all. I just compiled the code from the man page, tweaked it to run 'hg root', and passed it a new environment. No problems. Well, then I manually called the posix one from Python and thing worked fine. *Then* I actually tried the above code, and *it* worked fine. However I *still* get problems with the post-review code. So it looks like when I get back to work on Monday I'll be looking to see what the difference in environment is there. -Wayne -- http://mail.python.org/mailman/listinfo/python-list
Posix call (execve) breaks mercurial?
So... this is certainly the deepest I've got to dig into any source code. I'm experimenting with Review Board for code reviews, and trying to get it set up/working here at work. When using post-review, however, I started getting issues with untrusted users - even though they were set to trusted in my ~/.hgrc and things worked fine otherwise. So here's where things got weird. I could call `subprocess.check_output(['hg', 'root'])`, and things worked just fine. But when I added the env parameter, I got the untrusted issues. So if I did: import os, subprocess # Works just fine subprocess.check_output(['hg', 'root']) # Gives untrusted issues subprocess.check_output(['hg', 'root'], env=os.environ) Long story short, I dug around the source code and ended up at the POSIX execve function. I've been reading the manpages, but nothing seems to pop out at me as "hey, this should/shouldn't work!". Does anyone know what's going on here, or where I should go for more help? Thanks, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: print or write on a text file ?
On Fri, 28 Sep 2012, Franck Ditter wrote: Hi ! Here is Python 3.3 Is it better in any way to use print(x,x,x,file='out') or out.write(x) ? Any reason to prefer any of them ? There should be a printlines, like readlines ? Thanks, The print function automatically appends newlines to the end of what it prints. So if you had text = 'Hello!' and you did: print(text, file=outfile) then outfile would contain 'Hello!\n' In contrast, outfile.write(text) would only write 'Hello!'. No newline. There are lots of other handy things you can do with the print function: values = [1,2,3,4] print(*values, sep='\n', file=outfile) I'll leave it to you to experiment. HTH, Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Article on the future of Python
On 9/27/2012 9:05 PM, Jason Friedman wrote: Fair enough, but it's the M in the LAMP stack I object to. I'd much rather have P. +1 I know this isn't the list for database discussions, but I've never gotten a decent answer. I don't know much about either, so I'm kind of curious why postgresql over mysql? I'll try not to get too OT... I had previously just used MySQL (and SQLite), but have been reaading some PostGres stuff lately. I took a look around and basically... you and I won't know or notice a difference probably ever. There's all sorts of crazy tweaks you can get for reliability, speed, and backups depending on what you use. So the only advice I can give on that is just learn to use both. And even better yet, just use SQLAlchemy if you're ever touching a database from Python because it handles all the mucky SQL for you - you just define the ORM. (Hey look! A Python module!) My $0.02 -Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: Who's laughing at my responses, and who's not?
On Tue, 25 Sep 2012, Dwight Hutto wrote: It sounds pretentious, but over the past several days, I've been slammed on every post almost. All because of an argument over me not posting a little context in a conversation, that seemed short and chatty. Your being slammed has nothing to do with your lack of context, and everything to do with the fact that the way you responded to it was through ad hominem attacks, and the fact that most of your responses read like a transcript from kids I remember in junior high. It's annoying to most people - the same way pretentious teenage nitwits annoy most people who are interested in talking about Python code, and not who did what to who. -Wayne -- http://mail.python.org/mailman/listinfo/python-list
Re: One of my joomla webpages has been hacked. Please help.
On Sun, 23 Sep 2012, Dwight Hutto wrote: We're the borg. Oh, so you *are* a robot. That does explain your posts ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: One of my joomla webpages has been hacked. Please help.
On Sat, 22 Sep 2012, Νίκος Γκρεεκ wrote: Okey i'll ask this to the officila joomla forum, one last thing though. Is there a way to somehow embed(or utilize) python code, for example my python counter code script you have seen last week inside my Joomla/WordPress cms sites? For example: http://superhost.gr/ is my main website utilizing python counter script. http://superhost.gr/html/?show=log is my own way(i prefer it over awstats - don't ask why) for viewing my visitors. in my other sites which are CMS sites, like http://varsa.gr and http://thessalonik.wordpress.com/ is there a possible way to embed(if thats the term) my python counter script there too? so i can keep track of visitors info for each page i have there? Sure, but why create a counter (ugh) when you can use something like Google Analytics for free and get much more interesting and useful metrics? -Wayne-- http://mail.python.org/mailman/listinfo/python-list
Re: Algorithms using Python?
On Fri, 21 Sep 2012, Dennis Lee Bieber wrote: On Fri, 21 Sep 2012 14:26:04 +0530, Mayuresh Kathe declaimed the following in gmane.comp.python.general: Is there a good book on foundational as well as advanced algorithms using Python? Depends on what you mean by "foundational"... Since Python has dynamic lists and dictionaries, I suspect you won't find any textbook focusing on linked-list or hashed lookup algorithms using Python. You can probably implement them, but they're not going to be very efficient. (And never "remove" an element from the linked-list implementation because Python would shift all the other elements, hence your "links" become invalid). It's quite inefficient, but it would be fairly trivial to create a LL implementation like this: class Link: def __init__(self): self.next = None self.value = None class LinkedList: def __init__(self): self.head = None def add(self, value): node = Link() node.value = value self.append(node) def append(self, node): # Write some code It's fairly easy to use reference types as one would use pointers in . But it might actually require understanding pointers and such in the first place... I'm not really aware of any algorithm that's impossible/harder to implement in Python - Python just makes most things a lot easier so you never have to deal with the lower level algorithms. Which makes *me* happy :) -Wayne -- http://mail.python.org/mailman/listinfo/python-list