Re: Fatal Python error: Py_EndInterpreter: thread still has a frame
Thomas Korimort wrote: > Hi! > > Does anyone know the precise circumstances when the error > > "Fatal Python error: Py_EndInterpreter: thread still has a frame" > > does occur. I checked the source code of pythonrun.c, which tells me > that this error message is thrown in Py_EndInterpreter, when > thread->frame is checked for being NULL. Does anyone know, when this > pointer is not NULL at the time where Py_EndInterpreter() is called? Please create a test case and file a bug report, here: http://sourceforge.net/tracker/?group_id=5470&atid=105470 n -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding Python into C/C++ applications
On 2/3/06, John Dean <[EMAIL PROTECTED]> wrote: > Hi > > Could somebody, please tell me where I can find information about embedding > Python into a C/C++ application. The example in the docs is rather simple. I > am looking for something a bit more complex and longer For my opinion: Boost.Python is the way to go: http://boost.org/libs/python/doc/tutorial/doc/html/python/embedding.html There is also an other project: http://cxx.sourceforge.net/PyCXX.html > -- > Best Regards > John > -- > http://mail.python.org/mailman/listinfo/python-list > -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -- http://mail.python.org/mailman/listinfo/python-list
Does Python support a peek like method for its file objects?
Hello: Does Python support a peek like method for its file objects? I'd like to be able to look at the next byte in a disk file before deciding whether I should read it with, say, the read() method. Is it possible to do so in Python? Your answer would be much appreciated. Thanks. Avi Kak -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive function going infinite and I can't see why.
Ok, I finally got it working! See below On 2/4/06, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sat, 04 Feb 2006 02:18:27 -0500, Gregory Piñero wrote: > > class Node: > > def __init__(self): > > self.arg0=0 > > self.arg1=0 > > self.arg2=0 > > self.arg3=0 > > You appear to be iterating over these attributes. Hint: as soon as you > have more than two pieces of data with names like foo0, foo1, foo2... > you probably want something like this: > > def __init__(self): > self.trees = [0, 0, 0, 0] # they aren't args, they are sub-trees > > You are iterating over everything in __dict__ which is probably not what > you want. Your code has serious side-effects, because you are iterating > over ALL instance attributes, even the ones which are not nodes. > > for varname,value in node.__dict__.items(): > node.__dict__[varname] = value > # this touches all instance attributes > > This is safer: > > for index, value in enumerate(node.trees): > node.trees[index] = value > # this only touches what you want Yep, this is what fixed it. Thanks Steve. I turns out that there is a lot of other stuff in __dict__ that was messing me up and causing the infinite recursion. Terry was also kind of right in that I was never hitting my base case, since I was getting stuck on a var in __dict__ and recursing forever before I ever got to the base case. -Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Peter Hansen <[EMAIL PROTECTED]> wrote: > More precisely, the state of the function is *saved* when a yield > occurs, so you certainly don't *recreate* it from scratch, but merely > restore the state, and this should definitely be faster than creating it > from scratch in the first place. Right. Resuming a generator is faster than calling a function. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: fairly large webapp: from Java to Python. experiences?
Shalabh Chaturvedi wrote: > [EMAIL PROTECTED] wrote: > > A class-to-class and method-to-method rewrite will give some but likely > not the full benefit of moving to Python. A redesign might be necessary > - making it more 'Pythonic' in the process. In my experience, many cruft > classes that exist in a Java design simply disappear when ported to > Python. See also http://dirtsimple.org/2004/12/python-is-not-java.html > > Cheers, > Shalabh > Great link Shalabh. Thanks. :) Googling around, I'd also come across that one. ---J -- (remove zeez if demunging email address) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs C for a mail server
"Randall Parker" <[EMAIL PROTECTED]> writes: [...] > The code I'm writing in Python is a test executive to test embedded C > code. Then tests get written in Python that the test executive > processes. No, I'm not going to write yet another layer of tests in > order to compensate for shortcomings in the Python language. Yeah, despite being a fan of test-first, I don't write tests for tests either. That has been true when I've been testing numerical code written in both C and Python, for example. If I were writing any sort of test infrastructure code, however tiny, I would write tests for that code, regardless of the language. For those reasons, I don't see writing tests as compensating for shortcomings of Python. This discussion reminds me of statistics books that claimed that, just as a measurement without an error estimate was meaningless, so an error estimate without its own error estimate was also meaningless. By that logic, seems all measurement is meaningless :-) (please everybody note this is meant as a mildly amusing aside, not a point of argument!) > > It's also a pain to write unit tests, but it's much more rewarding > > than writing type declarations. Not only does it force you to think > > through the ramifications of changes, but you also document your > > intentions through your tests. > > I do not have time to write unit tests for the Python classes. I have > plenty of unit tests to write in Python for the embedded C modules. > When I run and hit a problem in Python I just debug it and fix it. > That's a lot faster than writing unit tests. As somebody who has worked in both test-first and 'a smattering of tests' styles, I'm quite sure you're right: when you don't have lots of unit tests, writing them slows you down. The benefit to be had comes when making *changes* to code with *good* unit test coverage. We all know people whose 'pragmatism' sometimes operates on, um, a strictly local basis and neglects the impact on a wider scale. I think we usually fall into that trap when we fail to write unit tests. I'm open to the idea that the benefits depend heavily on the sort of code you're writing, though. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread imbalance
Ivan Voras wrote: > Tuvas wrote: >>waits for a lul in the computing process. How can I ensure that this >>does not happen? This thread uses little processing power, so it could >>be set to a high priority, if there is a way to do this. Thanks! > > Python is bad for concurrently executing/computing threads, but it > shouldn't be that bad - do you have lots of compute-intensive threads? Just in case anyone coming along in the future reads this statement, for the record I'd like to say this is obviously a matter of opinion or interpretation, since in my view Python is *excellent* for threads (which are generally considered "concurrently executing", so I think that adjective is redundant, too). Ivan, what makes you say that Python is bad for threads? Did the qualifcation "concurrently executing/computing" have some significance that I missed? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Joseph Garvin wrote: > Wolfgang Keller wrote: >>If this is actually also true in the general case, and not due to eventual >>non-representativeness of the test mentioned above, is it simply due to a >>less-than-optimum implementation of generators in the current Pyython >>interpreter and thus likely to change in the future or is this a matter of >>principle and will consequently remain like this forever? > > I am not a CPython or PyPy hacker, but I would guess that it will always > be slower as a matter of principal. When resuming a generator you have > to resetup the state the function was in when it was last called, which > I think should always be more costly than calling the function with a > clean state. > > Someone want to correct me? Sure. "You have to resetup the state of the function"... depending on what "resetup" means (not a usual English word, so we might all imagine different meanings for it), either the first or the second part of the last sentence is false. More precisely, the state of the function is *saved* when a yield occurs, so you certainly don't *recreate* it from scratch, but merely restore the state, and this should definitely be faster than creating it from scratch in the first place. I haven't looked at the source, but this wouldn't have to involve much beyond a little memory copying, or even a few pointer changes, whereas the original could involve a lot of work, depending on how many arguments were passed, how many locals exist, and so on. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python vs C for a mail server
"Randall Parker" <[EMAIL PROTECTED]> writes: [...] > Also, a lot of C++'s flaws flow from the fact that it is old and grew > in lots of increments. That was a deliberate decision on the part of C++'s designers!-) I guess the same is true of Python in some respects: it's still incrementally changing (more than C++, I guess), and isn't all that much younger than C++ (around 15 and 23 years old respectively). > In my experience the overhead of explicitly deleting objects in C/C++ > is not the big burden that some argue here is the biggest reason to use > Python instead of C++. Should we be entirely surprised that from somebody from a engineering / numerical analysis background has that experience? Fortran 77 didn't even *have* a standard way to do dynamic memory allocation, did it? I certainly do think garbage collection is useful in that context, though... John -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric expression from string?
Brian Blais wrote: > I have a string input from the user, and want to parse it to a > number, and would like to know how to do it. I would like to be able > to accept arithmetic operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad > security problems (not that it's a big deal in my app, but still...) eval() is the preferred way unless you have serious security reasons: >>> def calc(s): ... try: ... return float(eval(s, dict(__builtins__=None))) ... except Exception, e: ... raise ValueError, "error during expression evaluation: %s" % e ... >>> calc("3**4") 81.0 >>> calc("58+34*4") 194.0 >>> calc("58+34*4+a") Traceback (most recent call last): File "", line 1, in ? File "", line 5, in calc ValueError: error during expression evaluation: name 'a' is not defined >>> calc("object.__class__") Traceback (most recent call last): File "", line 1, in ? File "", line 5, in calc ValueError: error during expression evaluation: name 'object' is not defined >>> calc("3.__class__") Traceback (most recent call last): File "", line 1, in ? File "", line 5, in calc ValueError: error during expression evaluation: unexpected EOF while parsing (line 1) >>> calc("type(3).__class__") Traceback (most recent call last): File "", line 1, in ? File "", line 5, in calc ValueError: error during expression evaluation: name 'type' is not defined Of course, one can still bring your system to its knees when "1000**1000"... -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread imbalance
Tuvas wrote: > waits for a lul in the computing process. How can I ensure that this > does not happen? This thread uses little processing power, so it could > be set to a high priority, if there is a way to do this. Thanks! Python is bad for concurrently executing/computing threads, but it shouldn't be that bad - do you have lots of compute-intensive threads? If you are running on a unix-like platform, see documentation for signal() and SIGALRM - maybe it will help your task. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Ivan Voras wrote: > Because "bar and aba happen to be parts of extension library" :) To end this disussion: I meant "doing it in C" as a colloquial expression, not a technical one. The expression holds true for every case where a function/class/module/etc is implemented in a lower-level language, and "C" was used only as an example. -- http://mail.python.org/mailman/listinfo/python-list
Re: would it be feasable to write python DJing software
Fredrik Lundh wrote: > > uhuh? so why did you just argue that > > if foo.bar(): > bar.aba() > > means "doing it in C" if bar and aba happens to be parts of an extension > library ? Because "bar and aba happen to be parts of extension library" :) -- http://mail.python.org/mailman/listinfo/python-list
python port for iPod
Hi, Since May 2005 there is a port of python (v2.4.1) for Apple iPod. Porting was an 'easy' job, the only consideration was how you can write with a iPod, ipodlinux [1] people did an interface called iPodRead that allows you type into iPod scrolling left or right on the wheel. (This affects to the file Parser/myreadline.c, line 47). Furthermore, is necessary run configure with options: --without-threads, --without-shared and --with-cxx and build it in a cross-compile environment for ARM architecture. Running make the only problem was the function hypot (umm, like ipod :) in the math module (I don't remember the problem) but i had to change hypot(x,y) to sqrt(x*x+y*y). You can see the differences between python original and python ported source in [2]. First announce about the port can be found in [3]. More info about this port, cool pictures and binaries & source code in [4]. [1] http://ipodlinux.org [2] http://www.ciberjacobo.com/en/diffs.html [3] http://ipodlinux.org/forums/viewtopic.php?t=1945 [4] http://www.ciberjacobo.com/en/linux_on_ipod.html#python -- Jacobo Avariento Gimeno http://ciberjacobo.com OpenPGP key: http://ciberjacobo.com/key.pem -- http://mail.python.org/mailman/listinfo/python-list
Re: fairly large webapp: from Java to Python. experiences?
[EMAIL PROTECTED] wrote: > I've got a fairly substantial webapp written in Java (plus Tomcat, > Hibernate, Struts, JSP, MySQL) that is a bit of a bear to work with. I > didn't write it. Much of it is only very sparsely documented (if at > all). No design docs anywhere. It's a large webapp with many classes > and fairly deep inheritance hierarchies. There seems to be JUnit test > cases in place. > > The possibility of re-writing it has come up, and I must say that, > although it would likely be a ton of work, it could also be a real > pythonic adventure. ;) > Any tips, stories, recommendations, and/or experiences are most > welcome. > A class-to-class and method-to-method rewrite will give some but likely not the full benefit of moving to Python. A redesign might be necessary - making it more 'Pythonic' in the process. In my experience, many cruft classes that exist in a Java design simply disappear when ported to Python. See also http://dirtsimple.org/2004/12/python-is-not-java.html Cheers, Shalabh -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Joseph Garvin wrote: > > I am not a CPython or PyPy hacker, but I would guess that it will always > be slower as a matter of principal. When resuming a generator you have > to resetup the state the function was in when it was last called, which > I think should always be more costly than calling the function with a > clean state. > > Someone want to correct me? In cases where there are thousands of (large) values to return, the list (as returned by the function) may be large enough to require memory paging, whereas the generator only returns one value at a time. > > Whether or not the difference is that significant though I am unsure. It > may be small enough that for most applications no one cares. I just wrote an application which retrieves values from a 300mb database, and got a significant speedup using iterators. --Max -- http://mail.python.org/mailman/listinfo/python-list
how to run BeautifulSoup in Jython
Hi, Anyone tries to use BeautifulSoup ( http://www.crummy.com/software/BeautifulSoup/ ) in Jython? I can not run that ,the error that Jython gives me is: unpack sequence too long. Sincerely, Erica __ 赶快注册雅虎超大容量免费邮箱? http://cn.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with some OO code.
TPJ wrote: > I understand your POV and I really appereciate your reply, but I doubt > that I could simplify my code to make it small *enough* to fit in one > post and not look too long. The pont of the exercise of taking non-working code and trying to cut away parts that aren't part of the problem is to isolate where the problem is. This is especially true in dynamic languages like Python, where problems usually consist of something not being what you expected it to be, but it's true in all other languages as well. Even if it means creating a standalone program that's a simplified version of the particular logic that's failing, this is good. It makes it easy for others to find where the problem is without having to tangle through your other (working) code. But in my view this is only the side benefit. The _real_ benefit is that a very significant fraction of the time, going through this exercise will actually help _you_ figure out your problem on your own. Taking a tangle of code that isn't working for reasons you don't understand and then pulling out threads to see where the problem is so you can show it to someone else to get help will usually allow _you_ to see where the problem was in the process. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis God said: "Let Newton be"; and all was light. -- Alexander Pope -- http://mail.python.org/mailman/listinfo/python-list
Re: Webmail with Python
Thomas Guettler wrote: > Hi, > > Is there an application like Squirrelmail[1] written in python? > > I want to access IMAP folder with a web-browser. > > Google shows me some dead projects. Most webmail applications > seem to be written in PHP. Is there a useable webmailer written > in python? > > > Thomas > Google turned up the following: http://bobomail.sourceforge.net/ Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Making Popen items terminate when program ends.
Peter Hansen wrote: > Please see this page: http://docs.python.org/ref/strings.html and read > about escape sequences in strings, and about raw strings. Thanks Peter. Forgot about that one. In a way, I wish it *would* have given me trouble, so I could have found it early rather than later. -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
pyluke wrote: > Scott David Daniels wrote: >> pyluke wrote: >>> I... want to find lines with ... "\[" but not instances of "\\[" >> >> If you are parsing with regular expressions, you are running a marathon. >> If you are doing regular expressions without raw strings, you are running >> a marathon barefoot. > I'm not sure what you mean by running a marathon. I'm referring to this quote from: http://www.jwz.org/hacks/marginal.html "(Some people, when confronted with a problem, think ``I know, I'll use regular expressions.'' Now they have two problems.)" > I do follow your statement on raw strings, but that doesn't seem > to be the problem. It is an issue in the readability of your code, not the cause of the code behavior that you don't like. In your particular case, this is all made doubly hard to read since your patterns and search targets include back slashes. > \[ > \nabla \cdot u = 0 > \] > > I don't want to find the following > > \begin{tabular}{c c} > a & b \\[4pt] > 1 & 2 \\[3pt] > \end{tabular} > how about: r'(^|[^\\])\\\[' Which is: Find something beginning with either start-of-line or a non-backslash, followed (in either case) by a backslash and ending with an open square bracket. Generally, (for the example) I would have said a good test set describing your problem was: re.compile(pattern).search(r'\[ ') is not None re.compile(pattern).search(r' \[ ') is not None re.compile(pattern).search(r'\\[ ') is None re.compile(pattern).search(r' \\[ ') is None --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Generators vs. Functions?
Wolfgang Keller wrote: >If this is actually also true in the general case, and not due to eventual >non-representativeness of the test mentioned above, is it simply due to a >less-than-optimum implementation of generators in the current Pyython >interpreter and thus likely to change in the future or is this a matter of >principle and will consequently remain like this forever? > > I am not a CPython or PyPy hacker, but I would guess that it will always be slower as a matter of principal. When resuming a generator you have to resetup the state the function was in when it was last called, which I think should always be more costly than calling the function with a clean state. Someone want to correct me? Whether or not the difference is that significant though I am unsure. It may be small enough that for most applications no one cares. -- http://mail.python.org/mailman/listinfo/python-list
Re: fairly large webapp: from Java to Python. experiences?
John M. Gabriele wrote: >> But once it is >> there, Python is a good choice for web apps. Java is slow > > Slow? They're both dynamic languages, but Java is statically > typed (with less work to do at runtime). For long-running processes, > I'd guess that Java bytecode executes faster than Python bytecode. It's not the raw computing performance that counts in this case. I got this joke in my mail today: Python: print "%10.2f" % x Java: java.text.NumberFormat formatter = java.text.NumberFormat.getNumberInstance(); formatter.setMinimumFractionDigits(2); formatter.setMaximumFractionDigits(2); String s = formatter.format(x); for (int i = s.length(); i < 10; i++) System.out.print(' '); System.out.print(s); Let alone the time it takes to write this routine, I'm hundered percent sure that the Python's version is also faster at runtime. Python lets you write pretty expressive code which is easy to maintain and where the computation cost is easily at the C level. Also Python code is pretty bare-metal, so that file.write or socket.write go to the syscall immediately. Try that in Java and you'll find 30 layers of complex abstractions for doubtful benefits and obvious slowness. -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Webmail with Python
Hi, Is there an application like Squirrelmail[1] written in python? I want to access IMAP folder with a web-browser. Google shows me some dead projects. Most webmail applications seem to be written in PHP. Is there a useable webmailer written in python? Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
> 2. Read the module's documentation. Several time. In your case read the > "negative lookbehind assertion" part "(? you understand how it may be of use to you. OK. lookbehind would be more useful/suitable here... -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive function going infinite and I can't see why.
Gregory Piñero wrote: > I want to walk down each tree and get a random subtree at a random > depth. Can you quantify that randomness? Should it be uniform at each level? Thinking about this may be fruitful. I don't yet know whether you need to see all leaves before you know which subtree to choose. Because I am a clueless American, so I don't know if Piñero is a common name or not. Are you perhaps related to the playwright? --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Generators vs. Functions?
Hello, in <[EMAIL PROTECTED]>, Magnus Lycka <[EMAIL PROTECTED]> posts the result of a short test that seems to indicate that resuming a generator takes more time than calling a function. If this is actually also true in the general case, and not due to eventual non-representativeness of the test mentioned above, is it simply due to a less-than-optimum implementation of generators in the current Pyython interpreter and thus likely to change in the future or is this a matter of principle and will consequently remain like this forever? TIA, Sincerely, Wolfgang Keller -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
> To add to what scott said, two advices: > 1. Use Kodos, it's a RE debugger and an extremely fine tool to generate > your regular expressions. Ok, just found this. Will be helpful. > 2. Read the module's documentation. Several time. In your case read the > "negative lookbehind assertion" part "(? you understand how it may be of use to you. Quite a teacher. I'll read it several times... Thanks anyway. -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
Scott David Daniels wrote: > pyluke wrote: >> I'm parsing LaTeX document and want to find lines with equations >> blocked by "\[" and "\]", but not other instances of "\[" like "a & b >> & c \\[5pt]" >> so, in short, I was to match "\[" but not "\\]" I've tried: >> check_eq = re.compile('(?!\%\s*)\[') > > check_eq.search(line) > > this works in finding the "\[" but also the "\\[" > > If you are parsing with regular expressions, you are running a marathon. > If you are doing regular expressions without raw strings, you are running > a marathon barefoot. > > Notice: len('(?!\%\s*)\[') == 13 > len(r'(?!\%\s*)\[') == 15 > >> so I would think this would work >> check_eq = re.compile('(?![\%\s*])\[') >> check_eq.search(line) >> >> but it doesn't. Any tips? > Give us examples that should work and that should not (test cases), > and the proper results of those tests. Don't make people trying to > help you guess about anything you know. > > --Scott David Daniels > [EMAIL PROTECTED] Alright, I'll try to clarify. I'm taking a tex file and modifying some of the content. I want to be able to identify a block like the following: \[ \nabla \cdot u = 0 \] I don't want to find the following \begin{tabular}{c c} a & b \\[4pt] 1 & 2 \\[3pt] \end{tabular} When I search a line for the first block by looking for "\[", I find it. The problem is, that this also find the second block due to the "\\[". I'm not sure what you mean by running a marathon. I do follow your statement on raw strings, but that doesn't seem to be the problem. The difference in your length example above is just from the two escaped slashes... not sure what my point is... Thanks Lou -- http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
Scott David Daniels wrote: > pyluke wrote: >> I'm parsing LaTeX document and want to find lines with equations blocked >> by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]" >> so, in short, I was to match "\[" but not "\\]" I've tried: >> check_eq = re.compile('(?!\%\s*)\[') > > check_eq.search(line) > > this works in finding the "\[" but also the "\\[" > > If you are parsing with regular expressions, you are running a marathon. > If you are doing regular expressions without raw strings, you are running > a marathon barefoot. > > Notice: len('(?!\%\s*)\[') == 13 > len(r'(?!\%\s*)\[') == 15 > >> so I would think this would work >> check_eq = re.compile('(?![\%\s*])\[') >> check_eq.search(line) >> >> but it doesn't. Any tips? > Give us examples that should work and that should not (test cases), > and the proper results of those tests. Don't make people trying to > help you guess about anything you know. > > --Scott David Daniels > [EMAIL PROTECTED] To add to what scott said, two advices: 1. Use Kodos, it's a RE debugger and an extremely fine tool to generate your regular expressions. 2. Read the module's documentation. Several time. In your case read the "negative lookbehind assertion" part "(?http://mail.python.org/mailman/listinfo/python-list
Re: re.search slashes
pyluke wrote: > I'm parsing LaTeX document and want to find lines with equations blocked > by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]" > so, in short, I was to match "\[" but not "\\]" I've tried: > check_eq = re.compile('(?!\%\s*)\[') > check_eq.search(line) > this works in finding the "\[" but also the "\\[" If you are parsing with regular expressions, you are running a marathon. If you are doing regular expressions without raw strings, you are running a marathon barefoot. Notice: len('(?!\%\s*)\[') == 13 len(r'(?!\%\s*)\[') == 15 > so I would think this would work > check_eq = re.compile('(?![\%\s*])\[') > check_eq.search(line) > > but it doesn't. Any tips? Give us examples that should work and that should not (test cases), and the proper results of those tests. Don't make people trying to help you guess about anything you know. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: OS.MKDIR( ) Overwriting previous folder created...
Ernesto <[EMAIL PROTECTED]> wrote: > NEVERMIND ! Here is the solution... > > # > if (os.path.isdir("C:\\MyNewFolder") == 0): > os.mkdir("C:\\MyNewFolder") > # - Maybe some other process creates C:\\MyNewFolder between the call of isdir and mkdir, or mkdir fails for some other reasons (e.g. no permission), so you have to catch exceptions anyway. But then there's no need for isdir. Florian -- Das ist ja das positive am usenet: man erfährt oft Dinge, nach denen gar nicht gefragt wurde. [Konrad Wilhelm in <[EMAIL PROTECTED]>] -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with some OO code.
At first I'd like to thank you for such a long answer. > (...) > You need to simplify the code as much as possible, cutting away everything > you can, to the SMALLEST amount of code that still experiences the problem. I understand your POV and I really appereciate your reply, but I doubt that I could simplify my code to make it small *enough* to fit in one post and not look too long. BTW: is there some safety way to show long piece of code on a group like comp.lang.python? Uploading my code to my website was the first (and the only one...) idea I had. > (...) > There is very little point in showing us test code > that works -- your problem isn't with code that works, it is with code > that doesn't work. You see - that's one of my problems. I'm working on my PyObject module (it is intended to be a base for more complex systems). For now there are no other modules, that use PyObject. So the test.py module, that consists of some test for my module, is the *only* piece of code that I could show you. That's all the story. > > All you need to know is that there are four classes. > > No, I'm sure we need to know much more than that. Yes, you're right. But I tried to explain my problem as easily as possible. And (as I thought) only four classes were involved. > > (Of course, you > > may generate all the documentation by typing just "./make_docs". All > > you need is Python with Epydoc installed.) > > Oh right, well just let me rush off and install Epydoc just for you, okay? It was not my intention to ask you to install anything for me. I just thought, that someone might be interested to read some documentation about the module, that causes the problem. I think it's easier to read documentation of more complex system, than just code. Perhaps it's about my English (I'm still studying) - a language easy to learn, but difficult to master. By "you may" I meant "you might, if you'd like to (for some reasons)", not "you are expected to do it". > > In the PyObject.py there are two classes: Object and OManager. When > > Object wants to know if some link is safe (in another words: it wants > > to know if some another object exists), > > What is a link in your application? What do you mean "another object"? > Like an int or a string? 1) In OO vocabulary, class is something like template for an object. But I think the word "object" has something different meaning in Python. In general I don't use the word "object" in the same meaning, that it is used by Python. I try to use words in the same way, that they are used in OO. Sometimes I use the word "class" to talk about template (for an object), and the word "instance" to talk about an object of some class, but the only reason I do it is to distinguish between OO-object and Python-object. 2) Link is something like address (like a post address). My module - in general - is just a template of a system of objects, that are able to communicate with each other. All that an object needs to communicate with an another object, is the name of that another object - it's adress (my assumption is that the names of the objects will be unique). "Link" to an another object is just the name of that object. > > it calls the proper method of > > its objects' manager (the OManager instance). Details are not important > > here, > > I bet the details are absolutely vital. Yes, they are - were. But I didn't want to describe my code in details in my post. I suspected, that there's some stupid mistake somewhere in my code. The truth is, all I wanted was someone else to take a look at this code. (BTW - I was right. My problem was caused by a spelling mistake, and someone found it. And it made me feel very stupid, but I think I deserved it.) > > so I'll just say, that if the link is safe, the objects' manager > > calls the proper method of the object, that sent him request. This > > method of the object just stores the information about that link (that > > it's safe), in the so-called private field (the fields used to store > > the information about the links are called __ls_existing_links and > > __ls_demanded_links). > > This is a terribly involved way of doing it, and I'm not even sure what > "it" is that you are trying to do. Are you trying to do some sort of > dispatch mechanism? My idea is as follows: 1) There's one objects' manager, that manages all the objects in some system. 2) Every object has its unique name, and is registered with the objects' manager. 3) When an object-sender wants to send a message to some object-receiver, all that the object-sender has to do is to tell the objects' manager, what's the name of the object-receiver. The only problem is that the object-sender has no idea if the object-receiver exists. A situation, when object-receiver doesn't exist, shouldn't happen, but as long as code is written by people, such a mistake can be done. Therefore I developed a mechanism, that may prevent such a situation. Every object-sender must create a link to the objec
Re: Recursive function going infinite and I can't see why.
Thanks for the advice guys. See below. On 2/4/06, Steven D'Aprano <[EMAIL PROTECTED]> wrote: > On Sat, 04 Feb 2006 02:18:27 -0500, Gregory Piñero wrote: > > > class Node: > > def __init__(self): > > self.arg0=0 > > self.arg1=0 > > self.arg2=0 > > self.arg3=0 > > You appear to be iterating over these attributes. Hint: as soon as you > have more than two pieces of data with names like foo0, foo1, foo2... > you probably want something like this: > > def __init__(self): > self.trees = [0, 0, 0, 0] # they aren't args, they are sub-trees I'll try this. > This is quite a complex function. It seems to me, and perhaps I'm wrong, > you are walking the nodes and ... doing what? When you call this function, > what are the initial arguments you give it? In other words, what are > oldnode and newnode, and where do they get set? > I posted the whole code, so that should be in there. > In another post, you wrote: > > "By the way, all I'm trying to do here is take two trees, randomly find > a sub-tree of each and swap the sub-trees. So if anyone has a simple > method for doing that I'm certainly open to that too." > > How about something like this? > > random.shuffle(node.trees) > > That does more than you ask, but maybe it is useful to you. If you only > want to swap two, maybe something like this: > > a, b = random.randint(0,3), random.randint(0,3) > node.trees[a], node.trees[b] = node.trees[b], node.trees[a] > That's not quite what I want. I want to walk down each tree and get a random subtree at a random depth. > I think what you really need to do here is spend some time building a > general tree class, before getting bogged down in the mechanics of your > application. For example, it would be really useful to print your Node, > and all its subtrees, so you can actually confirm that it contains what > you think it contains. I had a print method for the tree, but that was making an infinite recursion too! > Why is this important? Because if your tree of nodes contains a loop, such > that node 1 has a subtree with node 2 that has a subtree with node 3 that > has a subtree with node 1 again, most recursive algorithms will never > halt, just keep cycling through the tree forever. Could that be your > problem? There is no way for us to tell from the information we've got. This sounds like what must be happening. I don't know how else it could get caught up in an infinite recursion. The problem is, I don't really know how to tell either ;-0 I guess I need to rethink this whole algorithm. Maybe flatten the trees somehow and then do the swap? I'll let you guys know what I come up with. > -- > Steven. > > -- > http://mail.python.org/mailman/listinfo/python-list -- Gregory Piñero Chief Innovation Officer Blended Technologies (www.blendedtechnologies.com) -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Terry Hancock <[EMAIL PROTECTED]> wrote: > On Thu, 02 Feb 2006 19:27:55 -0600 > DH <[EMAIL PROTECTED]> wrote: > > But I think most people who don't like the extraneous > > 'self' in python just consider it a minor inconvenience > > and don't even notice it after using python for a while. > > After messing around with Javascript (many magical > variables that suddenly show up in your namespaces!), I > began to *seriously* appreciate Python's design. Having > self as an explicit parameter is beautiful self-documenting > design. I have to agree... Here is my experience with the same idea in C++... I've converted lots of C code written in an object oriented style into C++. In C you pass round a pointer to a struct, which gets transformed into the new class on conversion. Typically the code is then full of this->member = that, etc. This is the python equivalent of self.member = that. At this point I usually remove all the this-> from the code which then causes it to malfunction horribly at run-time (it compiles fine) because of all the name space clashes between the things in the class and the local variables. The compiler doesn't warn about this - its perfectly legal C++. In a lot of big C++ programs various conventions are used to try to help with this - naming all parameters to functions _name rather than name, or using this->member rather than member. The python way of enforcing self.member is much cleaner and never comes back to bite you! -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Extract contents of html cells
Dear all, I need to create a script which will extract the contents of 2 cells of an html that contains a specified number of cells.Then I need to put that contents in another cells of my own html page.How can i do that?Any samples, tutorials, advice? -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract contents of html cells
Robot <[EMAIL PROTECTED]> writes: > Dear all, > I need to create a script which will extract the contents of 2 cells > of an html that contains a specified number of cells.Then I need to > put that contents in another cells of my own html page.How can i do > that?Any samples, tutorials, advice? The tricky bit is parsing HTML. Chances are good that what you want for that is BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Take a look at the examples there and then feel free to ask more questions. Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract contents of html cells
Robot wrote: > Dear all, > I need to create a script which will extract the contents of 2 cells of > an html that contains a specified number of cells.Then I need to put > that contents in another cells of my own html page.How can i do that?Any > samples, tutorials, advice? > You should take a look at for the screen-scraping part: http://www.crummy.com/software/BeautifulSoup/ To put them in your html page all you need to do is to have some placeholders in your html and use python to replace the placeholders with the values you get from the other screen. -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Quoth [EMAIL PROTECTED]: ... | The first point is: Python has global functions, as well as methods. If | f(a) should look up f inside a first, that would shadow any global or | local f. That's bad, because python is dynamically typed, and you | sometimes down' know what "a" is. Things like "open(filename)" or | "tuple(a,b,c)" could behave completely unexpected, if "filename" had an | "open" or "a" a "tuple" attribute. Well, of course we have to assume as part of the proposal that it would documented and actually would be expected, to the extent that one is entitled to expect anything in Python. It seems to me that if you bring an even slightly open mind to the question, when we apply "open" to an object that supports "open" with its own function, what could be more appropriate than to call that function? I will allow that there is some potential for problems here, but there may be ways to finesse them. Haven't thought real hard about it. | The other point is: Python supports named arguments. The algorithm to | put positional and named arguments into the right parameters is rather | tricky, and it _must_ know the function that's being called to work. | So, you simply can't make function lookup depend on the parameters, | it's a hen-egg problem. Ah. I see no reason this system needs to support a named first parameter, though, so I suppose a function application like f(a=x,...) would be exempt from parameter lookup. This seems like an implementation detail. | > Of course the whole business is kind of a joke, since there is no way | > anyone in their right mind would wish to change Python's notation for | > such trivial reasons, but there actually are languages that resolve | > functions based on argument types. Overloading in C++ is somewhat | > like this, Haskell's typeclass mechanism, and there is a ``multiple | > dispatch'' model that I have no experience with but is not without its | > supporters. | | Yes, but both C++ and Haskell are statically typed, and neither | supports named arguments. | (We're talking about one function operating on one object, so I don't | see what multiple dispatch has to do with this) Come on, you know that in the unlikely event this idea were to be seriously considered, someone would be hot to extend it to multiple objects before it even got implemented on one, but in any case, single dispatch sounds like just a restricted case of multiple dispatch, so if the latter is feasible, so is the former. I've heard talk about a form of static typing for Python, and obviously that has the potential to considerably enhance the possibilities in this area. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Extract contents of html cells
Robot: >I need to create a script which will extract the contents of 2 cells of >an html that contains a specified number of cells.Then I need to put >that contents in another cells of my own html page.How can i do that? http://www.python.org/doc/lib/module-htmllib.html -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
re.search slashes
I'm parsing LaTeX document and want to find lines with equations blocked by "\[" and "\]", but not other instances of "\[" like "a & b & c \\[5pt]" so, in short, I was to match "\[" but not "\\]" to add to this, I also don't want lines that start with comments. I've tried: check_eq = re.compile('(?!\%\s*)\[') check_eq.search(line) this works in finding the "\[" but also the "\\[" so I would think this would work check_eq = re.compile('(?![\%\s*])\[') check_eq.search(line) but it doesn't. Any tips? -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Blair P. Houghton <[EMAIL PROTECTED]> wrote: ... > > It is (search for 'staticmethod' and 'classmethod'). But there's not > > much use for 'static methods' in Python - we usually just use plain > > functions ('classmethods' are another beast - much more useful than > > staticmethods) > > Does it make any noticeable difference in efficiency, or does nobody > care much about efficiency in Python? Some of us do, at few but crucial moments; that's why we have timeit.py to let you measure the performance of pieces of code you care about. helen:~ alex$ python -mtimeit -s'class X(object): > @staticmethod > def f(): pass > x=X()' 'x.f()' 100 loops, best of 3: 1.07 usec per loop helen:~ alex$ python -mtimeit -s'def f(): pass' 'f()' 100 loops, best of 3: 0.727 usec per loop helen:~ alex$ As you see, static methods have a small extra lookup cost (a couple hundred nanoseconds on my oldish laptop); normally, one would use a function instead. But if the body of the function/method did some significant, the lookup overhead would then matter little; clarity and organization and simplicity, OTOH, _always_ matter. "Premature optimization is the root of all evil in programming", as Knuth wrote quoting Hoare -- and anybody who's read Knuth's work knows he is anything BUT indifferent to real optimization; the key is avoiding that "premature" part!-) Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Daniel Nogradi <[EMAIL PROTECTED]> wrote: ... > So after all, what is a 'factory' or 'factory function'? A brief explanation in Python terms is at http://www.aleax.it/ep03_pydp.pdf -- "pages" (slides) 37-44 (the rest of the presentation is about an even more fundamental design pattern, "template method"). A far more extensive essay can be found, for example, at http://gsraj.tripod.com/design/creational/factory/factory.html -- it names the pattern "factory method", not "factory function" ("method" is probably a more widespread name for it) and presents examples in Java and Corba IDL. Anyway, trying to summarize: - "what": any function or method or other callable whose task it is to build and return new objects can be called "a factory"; - sometimes a factory may get away with returning an existing object for recycling "as if" it was a new one, saving some resources, and this is one advantage; - a factory may choose what exact type of object to build and return based on arguments or other circumstances, and this is a second advantage. "Program to an interface, not to an implementation" -- the key underlying principle ot the gang of 4's "Design Patterns" book. If you build an object of a specific given type ("new Foo" in Java or C++), you're hardwiring the choice of implementation (the exact concrete type); delegating the building to a method or function frees your application from such hardwiring and lets it be concentrated (if needed at all) in one spot (the factory). [[With the "registry" pattern you may even be able to remove any hardwiring, but that's a pretty advanced and subtle idea]]. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric expression from string?
> I have a string input from the user, and want to parse it > to a number, and would like to know how to do it. I > would like to be able to accept arithmetic operations, > like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead > to bad security problems (not that it's a big deal in my > app, but still...) I would use eval, as it does a whole lot of work for little cost. I would simply whitelist stuff with a regexp before passing it to eval(): import re tests = [('1*2', 2),('3+5/2', 5), ('8+5*21', 113),('3.14*2+20', 26.28), ('1/0', 0),('3**3yyp', 27), ('3*//+-p', 0)] exp = r'[^-*/+.eE0-9()]' r = re.compile(exp) print "Using regexp: %s" % exp for test, result in tests: s = r.sub('', test) try: print "%s -> %s = %s (should be %s)"% ( test, s,eval(s), result) except: print "invalid expression: %s" % test You can do more graceful handling of div-by-zero vs. general parsing errors here if you want, but you can get the general idea from this. If you wanted, you could include "i" in the regexp, in case you expect your users to use imaginary numbers. You could also include spaces if you wanted. Simply crank their expression through the r.sub() call to clean it of garbage (you can check and compare them if you want to see if anything was changed in the process). Then pass the results to eval() My early-Saturday-morning thoughts... -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with some OO code.
Thank you VERY much! These other errors are not so serious. I think I'll fix them soon. The most important thing is that now I'm ready to work on that code again. Life is beautiful again! Damn, I knew it is some very stupid mistake. I must learn how to use that pylint, instead of asking people on the web such a stupid questions. (The sad thing is that I'm the only one developer, who works on that code. I think I had just stuck before I sent the first message in this topic.) -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
Daniel Nogradi wrote: [...] > So after all, what is a 'factory' or 'factory function'? The name is intended to be indicative: it's a function that makes things - usually instances of some class. As has already been pointed out. Image is a module from PIL, so Image.open() is a function in that module. When you call it, it creates an instance of some suitable image class (which will depend on the type of the image) and returns that. The point here is that Image.open() returns a JpegImagePlugin.JpegImageFile instance for a .jpg file, a GifImagePlugin.GifImageFile instance for a .gif file, and so on. It wouldn't make sense to use a single class to represent all these different image types, so Image.open() just creates an instance of the appropriate class (whatever that may be, which will vary from call to call) and returns that. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric expression from string?
Brian Blais wrote: > Hello, > > I have a string input from the user, and want to parse it to a number, > and would like to know how to do it. I would like to be able to accept > arithmetic operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad security > problems (not that it's a big deal in my app, but still...) > > string.atof won't do the job. Is there a preferred way of doing this? > > > thanks, > > > Brian Blais > > I have no idea if it is the right thing for what you need, so it would be nice to get response if it is or not: http://www.strout.net/python/pythonica.html Claudio -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric expression from string?
On Sat, 04 Feb 2006 06:48:11 -0500, Brian Blais wrote: > Hello, > > I have a string input from the user, and want to parse it to a number, and > would like > to know how to do it. I would like to be able to accept arithmetic > operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad security > problems > (not that it's a big deal in my app, but still...) It is good to be cautious. Big thumbs up. But what exactly are you worried about? Do you think your users might enter something Evil and break their own system? I'd suggest that's not your problem, and besides, it is hard to think of anything they could do with eval that they couldn't do by exiting your app and running something Evil in their shell prompt. Are you running this script as a cgi script? Then remote users might use eval to break your system, and you are right to avoid it. Are you worried about angry customers calling you up with bizarre bugs, because they entered something weird into their input string? One possible way to avoid those problems is to validate the string before passing it to eval: goodchars = "0123456789+-/*()eE." for c in user_input: if c not in goodchars: raise ValueError("Illegal character detected!") result = eval(user_input) > string.atof won't do the job. Is there a preferred way of doing this? Look into PyParsing: http://cheeseshop.python.org/pypi/pyparsing/1.3.3 If you read back over the Newsgroup archives, just in the last week or so, there was a link to a PyParsing tutorial. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: numeric expression from string?
Brian Blais schrieb: > Hello, > > I have a string input from the user, and want to parse it to a number, > and would like to know how to do it. I would like to be able to accept > arithmetic operations, like: > > '5+5' > '(4+3)*2' > '5e3/10**3' > > I thought of using eval, which will work, but could lead to bad security > problems (not that it's a big deal in my app, but still...) > > string.atof won't do the job. Is there a preferred way of doing this? No. If you already know about the pro and cons of eval, either go for it - or if it bothers you, write a parser using pyparsing and evaluate the expressions yourself. Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Donn Cave wrote: > Quoth [EMAIL PROTECTED]: > | > Still see no problem. Of course, it goes without saying that > | > Python 2.4 doesn't work this way, but given that it's theoretically > | > possible for f(a) to be resolved similarly to a.f, then I really > | > do not see what you're seeing here. The kwargs parameter appears > | > irrelevant from where I'm sitting. > | > | Then either you didn't understand my answers, or I didn't understand > | your idea. Could you summarize how exactly "f(x,y=z)" should be > | resolved, i.e. where it should look for "f"? > > a.f ==> f(a) So, if the compiler recognizes the tokens "a.f", it should treat them as if it found the tokens "f(a)". But that wouldn't do what you want. You want it to do something different if it found the tokens "f(a)". > I would agree that I didn't understand your answers, but they weren't > really answers so much as questions, along the lines of ``well then, > how would this work?'' I seem to have missed what you were driving at, > but maybe if you were to just came out and explain the point? You do know what a rethorical question is? The first point is: Python has global functions, as well as methods. If f(a) should look up f inside a first, that would shadow any global or local f. That's bad, because python is dynamically typed, and you sometimes down' know what "a" is. Things like "open(filename)" or "tuple(a,b,c)" could behave completely unexpected, if "filename" had an "open" or "a" a "tuple" attribute. The other point is: Python supports named arguments. The algorithm to put positional and named arguments into the right parameters is rather tricky, and it _must_ know the function that's being called to work. So, you simply can't make function lookup depend on the parameters, it's a hen-egg problem. > Of course the whole business is kind of a joke, since there is no way > anyone in their right mind would wish to change Python's notation for > such trivial reasons, but there actually are languages that resolve > functions based on argument types. Overloading in C++ is somewhat > like this, Haskell's typeclass mechanism, and there is a ``multiple > dispatch'' model that I have no experience with but is not without its > supporters. Yes, but both C++ and Haskell are statically typed, and neither supports named arguments. (We're talking about one function operating on one object, so I don't see what multiple dispatch has to do with this) -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem with some OO code.
On Sat, 04 Feb 2006 04:21:50 -0800, TPJ wrote: > Help me please, because I really don't get it. I think it's some stupid > mistake I make, but I just can't find it. I have been thinking about it > for three days so far and I still haven't found any solution. > > My code can be downloaded from here: > http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some > scripts for GNU/Linux system (bash to be precise). Hint: when asking strangers to help you, at THEIR time and expense, with no offer to recompense them for their efforts, it is up to YOU to make their job as easy as possible. That means don't expect people to download some untrusted, potentially dangerous, piece of code from a stranger on Usenet, go to the trouble of extracting it from an archive, and then debug it for you. You need to simplify the code as much as possible, cutting away everything you can, to the SMALLEST amount of code that still experiences the problem. I've made some comments based on the information in your post. If they don't help, you will need to spend some time creating a short example that has the same problem. There is very little point in showing us test code that works -- your problem isn't with code that works, it is with code that doesn't work. > All you need to know is that there are four classes. No, I'm sure we need to know much more than that. > (Of course, you > may generate all the documentation by typing just "./make_docs". All > you need is Python with Epydoc installed.) Oh right, well just let me rush off and install Epydoc just for you, okay? > In the PyObject.py there are two classes: Object and OManager. When > Object wants to know if some link is safe (in another words: it wants > to know if some another object exists), What is a link in your application? What do you mean "another object"? Like an int or a string? This is the normal Python idiom for testing whether an object exists (strictly speaking, whether a name is bound to an object). try: some_object except NameError: print "some_object does not exist" Is that what you mean? > it calls the proper method of > its objects' manager (the OManager instance). Details are not important > here, I bet the details are absolutely vital. > so I'll just say, that if the link is safe, the objects' manager > calls the proper method of the object, that sent him request. This > method of the object just stores the information about that link (that > it's safe), in the so-called private field (the fields used to store > the information about the links are called __ls_existing_links and > __ls_demanded_links). This is a terribly involved way of doing it, and I'm not even sure what "it" is that you are trying to do. Are you trying to do some sort of dispatch mechanism? I see you have a line "i = self.__ls_demanded_links.index( s_object )". It looks like you are storing your data in a chunk of text, and then running index on that text to find the bit you want to work with. If you wanted to do that much work, just write your script in bash and be done with it! Python has lists and dicts and other advanced data structures. Use them. You will be glad. > And now the tests. In the test.py file this is a class called Obj. That > class is just an Object. So Obj is an alias for Object? What's an Object? Is it the same as the Python built-in type "object"? But later on you say: "All these methods are the methods of the Object class (defined in PyObject.py), not of the Obj class (defined in test.py)." So Object and Obj are not the same. > This is also a class called System1 - this > class is used only to create a more complex system composed of many > objects and one objects' manager. > > You can run all the tests by just typing "./test" in console (or a > terminal emulator). I'm still getting the same error: > > -- > Traceback (most recent call last): > File "test.py", line 142, in test04CreateSystems > system1 = System1() > File "test.py", line 81, in __init__ > self.objA.demandNewLink( 'B' ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 503, in demandNewLink > s_object ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 800, in _makeNewLink > o_srcobj._makeLinkSafe( s_target ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 608, in _makeLinkSafe > self.__makeLinkSafe( s_object ) > File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", > line 582, in __makeLinkSafe > i = self.__ls_demanded_links.index( s_object ) > AttributeError: 'Obj' object has no attribute > '_Object__ls_demanded_links' [snip] > Perhaps I'll explain what's going on there. First, the objects' manager > is created, and then also some objects are created. After doing that, > the object called "objA" demands a new link to the other object, called > "objB" (this is the line 81 i
Re: A problem with some OO code.
> AttributeError: 'Obj' object has no attribute > '_Object__ls_demanded_links' > -- > > Perhaps I'll explain what's going on there. First, the objects' manager > is created, and then also some objects are created. After doing that, > the object called "objA" demands a new link to the other object, called > "objB" (this is the line 81 in the error message above). As the result, > the "demandNewLink" method of the object "objA" is called. This method > calls the "_makeNewLink" method of the objects' manager, and this > method calls the "_makeLinkSafe" method of the object, that demanded a > new link. The last method, called "__makeNewLink" (so this is a > so-called private method), is called then. This last method is supposed > to check if the link was really demanded and then make it "safe" by > placing the information about this link in the proper dictionary > (__ls_existing_links). > > All these methods are the methods of the Object class (defined in > PyObject.py), not of the Obj class (defined in test.py). According to > my knowledge about the OO programming Python should be able to realize, > that the so-called private fields, that are being referred from these > Object class methods, are the private fields of the *Obj class > instance*, not of the *Object class one*. I didn't find any place where you create your __ls_demanded_links-list. So - how do you expevct it to be found, __-semantics or not? But I _did_ find a self.__ls_demandedLinks. So I guess you got confused in your variable names. After changing that, I got some other errors. So basically this boils down to some simple spelling errors. You migt want to think about using pychecker or pylint or both, and a auto-completion-capable editor like eric or (x)emacs. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Making Popen items terminate when program ends.
Roy Smith wrote: > In article <[EMAIL PROTECTED]>, > Peter Hansen <[EMAIL PROTECTED]> wrote: > >>You should >>either prefix your string with an "r" (just before the opening quotation >>mark) or escape the backslashes (as in use "C:\\Folder..." instead of >>just "C:\Folder"). > > Of the two alternatives, raw stings are much preferable to escaping > backslashes (IMHO). No, it's definitely preferable to avoid being slashed than it is to get stung. -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphical introspection utilities?
Oops. http://www.activestate.com/_images/screenshots/ss_Komodo_rails_large.gif is the debugger screenshot for Ruby (Komodo supports more than one language). Python's debugger in Komodo looks exactly the same. -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
n.estner wrote: > Yes, I 100% agree to that point! > But the point is, the current situation is not newbie-friendly (I can > tell, I am a newbie): I declare a method with 3 parameters but when I > call it I only pass 2 parameters. That's confusing. If I declare a > member variable, I write: "self.x = ValueForX", why can't I be equally > explicit for declaring member functions? For someone new to OO in general it might as well be something good, so he realises that there actually really is a hidden parameter. After all, there is something to understand with "self", and this discrapency between the number of arguments and parameters puts newbies to it. Jens -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphical introspection utilities?
> as it would be so obviously a good thing to have a graphical (or maybe > curses-base) browser through the dynamic state of a Python program, it's > probably there. > > Can someone point me to something? If you mean graphical debuggers, most Python specific IDEs have them. Few examples .. PythonWin SPE PyDev WingIDE Komodo http://pydev.sourceforge.net/images/screenshot/screenshot6.gif http://www.activestate.com/_images/screenshots/ss_Komodo_rails_large.gif If it is something else that you want, give an example of something similar available for another language/platform. -- http://mail.python.org/mailman/listinfo/python-list
Re: OO conventions
> > Actually, this way of creating a class instance is good OO practice in > > many places: The Image.open() method acts as a factory-function for > > creating Image objects. > > You don't know, until you inspect the return value, if the created > > object is actually an instance of class Image or something which just > > happens to behave like one... > > It could for instance be a sub-class of Image, JpegImage, if that > > better suits the class library designers. > > In general, factory-functions allow greater uncoupling between > > interface and implementation. > > > > From all the enlightening replies it seems to me that my next task > should be to look into what 'factory functions' are. Whenever I've > seen the word 'factory' I just skipped it, knowing that if I really > need to know what it is, I'll come back to it later. Apparently it's > just about time, thanks all for the comments. > I've been looking around for what factory functions are, but honestly I've been grepping and googling but couldn't find a clear definition of the concept of 'factory', 'factory function' or 'class factory'. As I've said I'm relatively new to OOP and the reason is that for too long I thought that there is no need for it, ordinary C will do. But once the concepts became clear, it started to become useful. That's why I'm not particularly interested in examples and code snippets but rather the general ideas and their definitions, but for these 'factories' I really couldn't find a clear explanation anywhere only how to use them, example code and such. Perhaps because I was only searching in the context of Python. So after all, what is a 'factory' or 'factory function'? -- http://mail.python.org/mailman/listinfo/python-list
numeric expression from string?
Hello, I have a string input from the user, and want to parse it to a number, and would like to know how to do it. I would like to be able to accept arithmetic operations, like: '5+5' '(4+3)*2' '5e3/10**3' I thought of using eval, which will work, but could lead to bad security problems (not that it's a big deal in my app, but still...) string.atof won't do the job. Is there a preferred way of doing this? thanks, Brian Blais -- - [EMAIL PROTECTED] http://web.bryant.edu/~bblais -- http://mail.python.org/mailman/listinfo/python-list
A problem with some OO code.
Help me please, because I really don't get it. I think it's some stupid mistake I make, but I just can't find it. I have been thinking about it for three days so far and I still haven't found any solution. My code can be downloaded from here: http://www.tprimke.net/konto/PyObject-problem.tar.bz2. There are some scripts for GNU/Linux system (bash to be precise). All you need to know is that there are four classes. (Of course, you may generate all the documentation by typing just "./make_docs". All you need is Python with Epydoc installed.) In the PyObject.py there are two classes: Object and OManager. When Object wants to know if some link is safe (in another words: it wants to know if some another object exists), it calls the proper method of its objects' manager (the OManager instance). Details are not important here, so I'll just say, that if the link is safe, the objects' manager calls the proper method of the object, that sent him request. This method of the object just stores the information about that link (that it's safe), in the so-called private field (the fields used to store the information about the links are called __ls_existing_links and __ls_demanded_links). And now the tests. In the test.py file this is a class called Obj. That class is just an Object. This is also a class called System1 - this class is used only to create a more complex system composed of many objects and one objects' manager. You can run all the tests by just typing "./test" in console (or a terminal emulator). I'm still getting the same error: -- Traceback (most recent call last): File "test.py", line 142, in test04CreateSystems system1 = System1() File "test.py", line 81, in __init__ self.objA.demandNewLink( 'B' ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 503, in demandNewLink s_object ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 800, in _makeNewLink o_srcobj._makeLinkSafe( s_target ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 608, in _makeLinkSafe self.__makeLinkSafe( s_object ) File "/home/tpj/opt/Praca/Programy/PyObject/workdir/PyObject.py", line 582, in __makeLinkSafe i = self.__ls_demanded_links.index( s_object ) AttributeError: 'Obj' object has no attribute '_Object__ls_demanded_links' -- Perhaps I'll explain what's going on there. First, the objects' manager is created, and then also some objects are created. After doing that, the object called "objA" demands a new link to the other object, called "objB" (this is the line 81 in the error message above). As the result, the "demandNewLink" method of the object "objA" is called. This method calls the "_makeNewLink" method of the objects' manager, and this method calls the "_makeLinkSafe" method of the object, that demanded a new link. The last method, called "__makeNewLink" (so this is a so-called private method), is called then. This last method is supposed to check if the link was really demanded and then make it "safe" by placing the information about this link in the proper dictionary (__ls_existing_links). All these methods are the methods of the Object class (defined in PyObject.py), not of the Obj class (defined in test.py). According to my knowledge about the OO programming Python should be able to realize, that the so-called private fields, that are being referred from these Object class methods, are the private fields of the *Obj class instance*, not of the *Object class one*. I even wrote a simple program to test the usage of the so-called private fields in Python classes: -- class A( object ): def __init__( self ): self.__a = 1 def _add( self ): print "self.__a =", self.__a self.__a += 1 def print_a( self ): print self.__a class B( A ): def __init__( self ): A.__init__( self ) self.__b = 2 def print_b( self ): print self.__b def test(): o = B() o.print_a() o.print_b() o._add() o.print_a() o.print_b() -- The code works just as I thought it should work: all is fine here. The B class instance (the b object) is able to refer to the so-called private field of the A class (through a A-class method, that was inherited by the class B). Why I can't do the same thing in test.py and in PyObject.py? I just don't get it. (And sorry for the subject of this topic. I really had no better idea...) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python on Windows
Grant Edwards wrote: > Definitely. Nobody does single .exe file windows programs > anymore. A single-file installer is almost as easy. > uTorrent, Process Explorer or Media Player Classic are single .exe windows programs. Granted, most of them are under-150kb-works-of-arts, but MPC isn't (well it's a work of art, but it's well over 5Mb now), but even then, some people STILL do single .exe windows programs, and some of these are the best programs in their fields (utorrent certainly is one of the best Torrent programs on windows, and it clearly has the very best features/exe size and features/ram consumption ratios, and I haven't seen anything that could even remotely close on to Process Explorer, RegMon or FileMon) -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive function going infinite and I can't see why.
On Sat, 04 Feb 2006 02:18:27 -0500, Gregory Piñero wrote: > Hi, > > Would anyone be able to tell me why my function below is getting stuck > in infinite recusion? > Maybe I'm just tired and missing something obvious? Your code is quite confusing, especially since there is very little documentation. But I'll make a few comments: > #This is the code that's causing my problem: > #-- > > import random > import sys > > class Test_Class: > pass > class Node: > def __init__(self): > self.arg0=0 > self.arg1=0 > self.arg2=0 > self.arg3=0 You appear to be iterating over these attributes. Hint: as soon as you have more than two pieces of data with names like foo0, foo1, foo2... you probably want something like this: def __init__(self): self.trees = [0, 0, 0, 0] # they aren't args, they are sub-trees You are iterating over everything in __dict__ which is probably not what you want. Your code has serious side-effects, because you are iterating over ALL instance attributes, even the ones which are not nodes. for varname,value in node.__dict__.items(): node.__dict__[varname] = value # this touches all instance attributes This is safer: for index, value in enumerate(node.trees): node.trees[index] = value # this only touches what you want Now people (and you!) can subclass your Node class without breaking it. > def snip(node): > prob_of_returning_this_node=.4 > if random.random()<=prob_of_returning_this_node: > return node > else: > if hasattr(node,'__dict__') and len(node.__dict__)>0: > return snip(random.choice(node.__dict__.values())) > else: > return node This becomes: def snip(node): prob_of_returning_this_node = 0.4 if random.random() <= prob_of_returning_this_node: return node else: return snip(random.choice(node.trees)) > def replace_within_node(node,oldnode,newnode): > if node is oldnode: > return newnode > else: > if hasattr(node,'__dict__'): > for varname,value in node.__dict__.items(): > node.__dict__[varname]=replace_within_node(value,oldnode,newnode) > return node becomes: def replace_within_node(node, oldnode, newnode): if node is oldnode: return newnode else: for indx, nd in node.trees: node.trees[indx] = replace_within_node(nd, oldnode, newnode) return node This is quite a complex function. It seems to me, and perhaps I'm wrong, you are walking the nodes and ... doing what? When you call this function, what are the initial arguments you give it? In other words, what are oldnode and newnode, and where do they get set? In another post, you wrote: "By the way, all I'm trying to do here is take two trees, randomly find a sub-tree of each and swap the sub-trees. So if anyone has a simple method for doing that I'm certainly open to that too." How about something like this? random.shuffle(node.trees) That does more than you ask, but maybe it is useful to you. If you only want to swap two, maybe something like this: a, b = random.randint(0,3), random.randint(0,3) node.trees[a], node.trees[b] = node.trees[b], node.trees[a] I think what you really need to do here is spend some time building a general tree class, before getting bogged down in the mechanics of your application. For example, it would be really useful to print your Node, and all its subtrees, so you can actually confirm that it contains what you think it contains. Why is this important? Because if your tree of nodes contains a loop, such that node 1 has a subtree with node 2 that has a subtree with node 3 that has a subtree with node 1 again, most recursive algorithms will never halt, just keep cycling through the tree forever. Could that be your problem? There is no way for us to tell from the information we've got. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: fairly large webapp: from Java to Python. experiences?
John M. Gabriele wrote: > [EMAIL PROTECTED] wrote: >> But once it is >> there, Python is a good choice for web apps. Java is slow > > Slow? They're both dynamic languages, but Java is statically > typed (with less work to do at runtime). For long-running processes, > I'd guess that Java bytecode executes faster than Python bytecode. Well, perhaps yes, but not so if you count the fact that recoding is so easy that you can race several implementations of the same thing to see which trade-offs work. Java may run the one algorithm you decide to write faster than Python will run the same thing, but in Python you may race five algorithms and keep the fastest. Using programmer resources effectively is Python's secret sauce. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Starting terminal applications from within python
On 2 Feb 2006 09:41:20 -0800, sleepylight <[EMAIL PROTECTED]> wrote: > Ah! I see now. That makes prefect sense. I guess I was thinking that > python was simply going to pass a whole command string to the program > rather than give each argument as individual strings. Seeing this > makes the documentation seem much more sensible. Thank you! [offtopic] You might also want to look into using the screen(1) utility. I have found that doing "screen foo" (from within a screen session) is often a superior way to achieve the things people often use "xterm -e foo" for. Especially if they have scripts pop up lots of applications in separate terminals. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Graphical introspection utilities?
Hello, as it would be so obviously a good thing to have a graphical (or maybe curses-base) browser through the dynamic state of a Python program, it's probably there. Can someone point me to something? Cheers, Jens -- http://mail.python.org/mailman/listinfo/python-list
Re: python's library support
Robert Kern>And several others if you google a bit. Yes: http://sourceforge.net/projects/pynetwork/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression query
Martin Biddiscombe wrote: > "parameter=12ab" > "parameter=12ab foo bar" > "parameter='12ab'" > "parameter='12ab' biz boz" > "parameter="12ab"" > "parameter="12ab" junk" >>> import shlex >>> def extract(s): ... s = s.split("=")[1] ... s = shlex.split(s)[0] ... return s ... >>> extract("parameter=12ab") '12ab' >>> extract("parameter=12ab foo bar") '12ab' >>> extract("parameter='12ab'") '12ab' >>> extract("parameter='12ab' biz boz") '12ab' >>> extract('parameter="12ab"') '12ab' >>> extract('parameter="12ab" junk') '12ab' -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive function going infinite and I can't see why.
>Would anyone be able to tell me why my function below is getting stuck >in infinite recusion? >def replace_within_node(node,oldnode,newnode): >if node is oldnode: >return newnode Without looking further, the most likely reason is that the base case is never true: ie, node is never oldnode. I would probably add print node, oldnode, newnode at the top (and maybe another print later) and then run the code on a small tree where I thought I knew what should be printed and then see where my expectation diverges from the actual. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
"Jean-Paul Calderone" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I'm not sure I follow. Surely you're not suggesting that this doesn't > work: > >>>> class X: >... def foo(self): >... print 'X.foo', self >... >>>> class A(X): >... pass >... >>>> o = A() >>>> A.foo(o) >X.foo <__main__.A instance at 0xb7cab64c> >>>> Either things have changed or I was misinformed and neglected to verify ;-( -- http://mail.python.org/mailman/listinfo/python-list