Re: Idle
[EMAIL PROTECTED] wrote: > If you are compiling python and you want to build idle/tkinter, you > need to have the development packages for tcl and tk. The python build > scripts will only build tkinter should they find the libraries > (libtk8.4.so and libtcl8.4.so) and the header files (tk.h and tcl.h). > If you don't have the development packages installed, you most likely > do not have the header files. > > If you install the development packages and recompile, test by > importing _tkinter. If that is successful, idle should run just fine. > Thanks. After installing new versions of Tcl/Tk, python compilation did work. What is surprising is that although Python is bundled with most (all?) Linux distros, Idle does not work on most??? -- Hrvoje -- http://mail.python.org/mailman/listinfo/python-list
Re: Turn $6 into $6.000
Hello, Happy Harmony is the fastest growing matrimonial portal for Indians. You can email and IM other members without paying anything on this site. The amazing thing is that this site is totally free. Absolutely free. Cannot believe? Then click on this link to visit and register Happy Harmony. http://www.happyharmony.com/?idAff=14 Background check is the new facility they have added now. You can do a free background check including age, address, phone numbers, property owneship information etc of anybody in the US. Regards, Resh -- http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
yes, to generete core dump is the best way, but the command "$ ulimit -c 50" don't make python to generete core dump in the time of crush. I would like to know how to run python script so if it crushes than core dump will be genereted. Thanks Pierre Barbier de Reuille wrote: > Maksim Kasimov a écrit : > >>Hello, >> >>my programm sometime gives "Segmentation fault" message (no matter how >>long the programm had run (1 day or 2 weeks). And there is nothing in >>log-files that can points the problem. >>My question is how it possible to find out where is the problem in the >>code? Thanks for any help. >> >>Python 2.2.3 >>FreeBSD >> > > > Well, your best bet is to generate a core file ! > To do so, in the shell launching the program, you need to accept core > files. The command is : > > $ ulimit -c > > For example: > $ ulimit -c 50 > > For a 500MB max file. > > Then, if your program crash, you should see a file named "core." > where is the PID of the process. You can know exactly where the > program crashed using gbd : > > $ gdb --core=core. > > Then, depending on the debug information you have in your executables > you may (or may not) be able to know what happened :) > > Pierre -- Best regards, Maksim Kasimov mailto: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: While and If messing up my program?
hi, to get howmany element list appear you can code: ttllst=[4,3,45,3] for x in ttllst: print x, ttllst.count(x) pass to get non duplicate element list you can code: ttllst=[4,3,45,3] print list(set(ttllst)) Cheers, pujo -- http://mail.python.org/mailman/listinfo/python-list
Re: python plotting with greek symbols within labels recommendations?
[EMAIL PROTECTED] wrote:
> hello all,
>
> this message is geared toward those of you in the scientific community.
> i'm looking for a python plotting library that can support rendering
> greek symbols and other various characters on plot axes labels, etc. I
> would prefer something that adheres to tex formatting (as implemented
> in latex, matlab, etc and has the form $\alpha$ to represent the greek
> character alpha for example).
>
> thus far, i've found that matplotlib
> (http://matplotlib.sourceforge.net/) can do this, albeit the
> implementation is so poor that you cannot mix standard text with
> symbols on the same plot element.
>
>
If you already have installed matplotlib, have a look at
matplotlib-0.X.Y/examples/tex_demo.py
It shows you how to mix text and symbols.
The other examples in the directory could also be useful.
Essentially you need to remember
matplotlib.rc('text', usetex=True)
before plotting.
If you need complex stuff (fractions, sums, integrals) try
putting an r before the string: pylab.ylabel(
r"Density $\left(\rho =\frac{x^2+\frac{x+1}{x-1}}{\kappa(x)K_{ij}}\right)")
works fine, at least on my system.
--
http://mail.python.org/mailman/listinfo/python-list
Re: While and If messing up my program?
"CJ" wrote:
>What does worry me, is that I can't seem to get the program by a
> certain spot. It keeps giving me the same error, and I don't know why.
quite often, exception messages means exactly what they say; if
you get an index error, it's because you're trying to fetch an item
that doesn't exist.
for simple debugging, the "print" statement is your friend:
> ttllst=[4,3,45,3]
> cnto=0
> cntt=1
> rept=-1
>
> print cnto
> print cntt
> print ttllst[cnto]
> print ttllst[cntt]
> choice=raw_input("Begin? ")
> if choice == "yes" or choice == "y":
> while cnto<>len(ttllst)+1:
print cnto, cntt, len(ttllst)
> if ttllst[cnto]==ttllst[cntt]:
> rept=rept+1
> if cntt==len(ttllst):
> print ttllst[cnto],"appears in the list",rept,"times."
> cntt=-1
> cnto=cnto+1
> rept=-1
> cntt=cntt+1
> print "done."
with that in place, I get
Begin? y
0 1 4
0 2 4
0 3 4
0 4 4
Traceback (most recent call last):
File "test.py", line 14, in ?
if ttllst[cnto]==ttllst[cntt]:
IndexError: list index out of range
which means that your second list index (cntt) is too large.
figuring out how to fix that is left as an etc etc.
PS. when you've sorted this out, you might wish to check out the
"count" method on list objects:
>>> help(list.count)
Help on method_descriptor:
count(...)
L.count(value) -> integer -- return number of occurrences of value
--
http://mail.python.org/mailman/listinfo/python-list
Re: While and If messing up my program?
The specific error in your code, is that when cnto == len(ttllst), then doing ttllst[cnto] will give you that error. The list is indexed from 0 to len-1, which means that doing list[len(list)] will give that error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed in OOP-Python
Toufeeq Hussain wrote:
> My coding is really really bad,that's why I changed the names to more human
> readable form(Module1,2.. etc).
the problem is that when you do that (and post using a tool that's not
smart enough to preserve leading whitespace), anyone who wants to help
will basically have to recreate your program -- and once they've done that,
chances are that they won't get the same error as you do.
consider this:
$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in ?
import module3
File "module3.py", line 4, in ?
class Option1_Rule1(declaration.Option1):
NameError: name 'declaration' is not defined
oops. looks like you forgot to rename something. that's easy to fix.
$ python test.py
Traceback (most recent call last):
File "test.py", line 3, in ?
Test_Case = module3.Option1_Rule1()
File "module3.py", line 6, in __init__
module2.Option1.__init__(self)
File "module2.py", line 5, in __init__
module1.OptionClass.__init__('Blah Blah','OR0001','','')
TypeError: unbound method __init__() must be called with OptionClass instance as
first argument (got str instance instead)
aha. that sure looks like a bug. when you call the baseclass init method,
you must pass in the object instance as the first argument. that's easy to
fix.
$ python test.py
Traceback (most recent call last):
File "test.py", line 4, in ?
Test_Case.Option1_constraint()
AttributeError: Option1_Rule1 instance has no attribute 'Option1_constraint'
oops. looks like I got the indentation wrong when I fixed up that module.
that's easy to fix.
$ python test.py
condition satisfied
Traceback (most recent call last):
File "test.py", line 4, in ?
Test_Case.Option1_constraint()
File "module3.py", line 11, in Option1_constraint
self.FOO_warning.Fire()
AttributeError: Option1_Rule1 instance has no attribute 'FOO_warning'
FOO_warning? there's no FOO_warning anywhere in the code.
:::
so, after four attempts, I've found four problems, three of which was present
in your posted code, but I still haven't seen the problem you reported:
Traceback (most recent call last):
File "test_case.py", line 7, in ?
TH = constraint.Option1_Rule1()
File "constraint.py", line 13, in __init__
declaration.Option1.__init__(self)
TypeError: __init__() takes no arguments (1 given)
which, in itself, looks like you've forgotten the self argument in some init
method somewhere (but the code you posted doesn't have that problem).
if you want to post code, 1) try to reduce the problem to as little code as you
possibly can, and 2) make sure that the code you post really has the problem
you're seeing... (i.e. run it at least once before you post it)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help needed in OOP-Python
Fredrik, sigh! I see the problem you mention and I agree. Should have posted the orginal code without edits. :( Anyway I'll try to fill in whereever required.On 10/5/05, Fredrik Lundh <[EMAIL PROTECTED]> wrote: $ python test.pycondition satisfiedTraceback (most recent call last): File "test.py", line 4, in ?Test_Case.Option1_constraint() File "module3.py", line 11, in Option1_constraintself.FOO_warning.Fire()AttributeError: Option1_Rule1 instance has no attribute 'FOO_warning' FOO_warning? there's no FOO_warning anywhere in the code. FOO_warning is "Option1_warning" from Module3. And, in Module1 comment out the line: "common_subs.write_to_out_file( 'FOO_OUT',self.Warn_text)" :::so, after four attempts, I've found four problems, three of which was present in your posted code, but I still haven't seen the problem you reported:Traceback (most recent call last): File "test_case.py", line 7, in ?TH = constraint.Option1_Rule1() File " constraint.py", line 13, in __init__declaration.Option1.__init__(self)TypeError: __init__() takes no arguments (1 given) But the script when given as individual commands works fine in IDLE. While executing the script it throws that error. :( which, in itself, looks like you've forgotten the self argument in some initmethod somewhere (but the code you posted doesn't have that problem). Yes,I've doubled checked this. if you want to post code, 1) try to reduce the problem to as little code as you possibly can, and 2) make sure that the code you post really has the problemyou're seeing... (i.e. run it at least once before you post it) All points noted and will follow the same. Thanks and my sincere apologies. -toufeeq-- Get Firefox:http://www.mozilla.org/products/firefox/The fastest, safest and best Browser !! -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Op 2005-10-04, Mike Meyer schreef <[EMAIL PROTECTED]>: > Antoon Pardon <[EMAIL PROTECTED]> writes: >> Op 2005-10-03, Steven D'Aprano schreef <[EMAIL PROTECTED]>: >>> On Mon, 03 Oct 2005 13:58:33 +, Antoon Pardon wrote: >> Declarations also allow easier writable closures. Since the declaration >> happens at a certain scope, the run time can easily find the correct >> scope when a variable is rebound. > > If it happens at runtime, then you can do it without declarations: > they're gone by then. That depends on how they are implemented. "declarations" can be executable statements. It is not about can we do without or not. It is about are they helpfull or not. Python would be a whole different language if it never adapted something it could do without. > Come to think of it, most functional languages - > which are the languages that make the heaviest use of closures - don't > require variable declarations. But AFAIK they don't work like python which makes any variable that is assigned to in a function, local. Which is a problem if you want a writable closure. >> They also relieve a burden from the run-time, since all variables >> are declared, the runtime doesn't has to check whether or not >> a variable is accesible, it knows it is. > > Not in a dynamic language. Python lets you delete variables at run > time, so the only way to know if a variable exists at a specific > point during the execution of an arbitrary program is to execute the > program to that point. It is not perfect, that doesn't mean it can't help. How much code deletes variables. >> And if you provide type information with the declaration, more >> efficient code can be produced. > > Only in a few cases. Type inferencing is a well-understood > technology, and will produce code as efficient as a statically type > language in most cases. I thought it was more than in a few. Without some type information from the coder, I don't see how you can infer type from library code. >> I think language matters shouldn't be setlled by personal preferences. > > I have to agree with that. For whether or not a feature should be > included, there should either be a solid reason dealing with the > functionality of the language - meaning you should have a set of use > cases showing what a feature enables in the language that couldn't be > done at all, or could only be done clumsily, without the feature. I think this is too strict. Decorators would IMO never made it. The old way to do it, was certainly not clumsy IME. I think that a feature that could be helpfull in reduction errors, should be a candidate even if it has no other merrits. > Except declarations don't add functionality to the language. They > effect the programing process. It would be one way to get writable closures in the language. That is added functionality. > And we have conflicting claims about > whether that's a good effect or not, all apparently based on nothing > solider than personal experience. Which means the arguments are just > personal preferences. Whether the good effect is good enough is certainly open for debate. But the opponents seem to argue that since it is no absolute guarantee, it is next to useless. Well I can't agree with that kind of argument and will argue against it. > Antoon, at a guess I'd say that Python is the first time you've > encountered a dynamnic language. Being "horrified" at not having > variable declarations, which is a standard feature of such languages > dating back to the 1950s, is one such indication. No I'm not horrified at not having variable declarations. I'm in general very practical with regard to programming, and use what features a language offers me. However that doesn't stop me from thinking: Hey if language X would have feature F from language Y, that could be helpfull. Now if the developers think such a feature is not important enough fine, by me. It is however something different if people start arguing that feature F is totally useless. Now my impression is that a number of people regard python or at least some aspects of it as holy and that suggesting that some specific features could be usefull is considered sacriledge. > Dynamic languages tend to express a much wider range of programming > paradigms than languages that are designed to be statically > compiled. Some of these paradigms do away with - or relegate to the > level of "ugly performance hack" - features that someone only > experienced with something like Pascal would consider > essential. Assignment statements are a good example of that. I think we should get rid of thinking about a language as static or dynamic. It is not the language which should determine a static or dynamic approach, it is the problem you are trying to solve. And if the coder thinks that a static approach is best for his problem, why shouldn't he solve it that way. That a language allows a static approach too, doesn't contradict that it can work dynamically. Everytime a static feature
2 class with same name in different module
I have a class in a module which is getting imported in main module. How do you differentiate between the 2 class regards prasad chandrasekaran This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Paul Rubin wrote:
> Brian Quinlan <[EMAIL PROTECTED]> writes:
>> Have those of you who think that the lack of required declarations in
>> Python is a huge weakness given any thought to the impact that adding
>> them would have on the rest of the language? I can't imagine how any
>> language with required declarations could even remotely resemble
>> Python.
>
> What's the big deal? Perl has an option for flagging undeclared
> variables with warnings ("perl -w") or errors ("use strict") and Perl
> docs I've seen advise using at least "perl -w" routinely. Those
> didn't have much impact. Python already has a "global" declaration;
> how does it de-Pythonize the language if there's also a "local"
> declaration and an option to flag any variable that's not declared as
> one or the other?
The difference is that perl actually needs 'use strict' to be useful for
anything more than trivial scripts. Without 'use strict' you can reference
any variable name without getting an error. Python takes a stricter
approach to begin with by throwing an exception if you reference an
undefined variable.
This only leaves the 'assigning to a different name than the one we
intended' problem which seems to worry some people here, and as has been
explained in great detail it incurs a cost to anyone reading the code for
what most Python users consider to be a very small benefit.
If you think variable declarations should be required, then you presumably
want that to cover class attributes as well as local and global
variables. After all assigning to 'x.i' when you meant 'x.j' is at least as
bad as assigning to 'i' instead of 'j'. But unless you know the type of
'x', how do you know whether it has attributes 'i' or 'j'? So do we need
type declarations, or perhaps we need a different syntax for 'create a new
attribute' vs 'update an existing attribute', both of which would throw an
exception if used in the wrong situation, and would therefore require lots
of hasattr calls for the cases where we don't care.
--
http://mail.python.org/mailman/listinfo/python-list
Re: 2 class with same name in different module
Iyer, Prasad C wrote: > I have a class in a module which is getting imported in main module. > How do you differentiate between the 2 class import foo import bar foo.TheClass().dostuff() bar.TheClass().dostuff() -- http://mail.python.org/mailman/listinfo/python-list
Re: 2 class with same name in different module
"Iyer, Prasad C" wrote: > I have a class in a module which is getting imported in main module. > How do you differentiate between the 2 class if you have one class in a module, why do you need to differentiate between it? assuming that you do in fact have *two* classes with the same name in two different modules, you just have to import them as usual, and access them via their modules: import module1 import module2 o1 = module1.Class() o2 = module2.Class() if this is not what you mean, please post a short example that shows what the problem really is. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to get any available port
[EMAIL PROTECTED] wrote:
> Apparently, calling bind() with a zero "port" will choose some available port
> number, as demonstrated by this program:
>
> import socket
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind(("", 0))
> print s.getsockname()
>
> Here's how it behaved over several runs:
> $ python soc.py
> ('0.0.0.0', 34205)
> $ python soc.py
> ('0.0.0.0', 34206)
> $ python soc.py
> ('0.0.0.0', 34207)
>
> I don't know for sure whether this is standard behavior for sockets, or
> whether
> it's a special behavior of linux.
>
It's been standard behaviour ever since the Berkeley socket interface
was defined, as far as I know.
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: "no variable or argument declarations are necessary."
Op 2005-10-04, Ron Adam schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: >> Op 2005-10-03, Steven D'Aprano schreef <[EMAIL PROTECTED]>: >>> >>>And lo, one multi-billion dollar Mars lander starts braking either too >>>early or too late. Result: a new crater on Mars, named after the NASA >>>employee who thought the compiler would catch errors. >> >> >> Using (unit)tests will not guarantee that your programs is error free. >> >> So if sooner or later a (unit)tested program causes a problem, will you >> then argue that we should abondon tests, because tests won't catch >> all errors. > > Maybe you need to specify what kind of errors you want to catch. > Different types of errors require different approaches. I want to catch all errors of course. I know that nothing will ever guarantee me this result, but some things may help in getting close. So if a language provides a feature that can help, I generally think that is positive. That such a feature won't solve all problems shouldn't be considered fatal as some counter arguments seem to suggest. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
[EMAIL PROTECTED] wrote: > Some people just don't get the simple fact that declarations are > essentially kind of unit test you get for free (almost), and the compiler > is a testing framework for them. It seems you've missed the entire point of using a dynamically typed language. It's not just about saving typing time and making your methods take up fewer lines of code. It's about writing generic code. Just look at C++ with all that mess with complex templates, silly casting and dangerous void pointers etc that are needed to achieve a fraction of the genericity that Python provides with no effort from the programmer. With properly written tests, you can be reasonably that the program does what you want. Type declarations are extremely limited in this aspect, and they often give programmers a false sense of security. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Duncan Booth <[EMAIL PROTECTED]> writes: > If you think variable declarations should be required, I don't think they should be required. I think there should optional declarations along with a compiler flag that checks for them if the user asks for it, like Perl has. > then you presumably want that to cover class attributes as well as > local and global variables. After all assigning to 'x.i' when you > meant 'x.j' is at least as bad as assigning to 'i' Yes, lots of people mistakenly use __slots__ for exactly that purpose. Maybe the function they think __slots__ is supposed to implement is a legitimate one, and having a correct way to do it is a good idea. > But unless you know the type of 'x', how do you know whether it > has attributes 'i' or 'j'? If the compiler knows (through declarations, type inference, or whatever) that x is a certain type of class instance, then it knows what attributes x has. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Magnus Lycka <[EMAIL PROTECTED]> writes: > It seems you've missed the entire point of using a dynamically > typed language. It's not just about saving typing time and making > your methods take up fewer lines of code. It's about writing generic > code. Just look at C++ with all that mess with complex templates, > silly casting and dangerous void pointers etc that are needed to > achieve a fraction of the genericity that Python provides with no > effort from the programmer. So where are the complex templates and dangerous void pointers in ML? -- http://mail.python.org/mailman/listinfo/python-list
Confused with module and .py files
Actually I am bit confused between the modules and .py file How do I differentiate between the 2. For example I have a file import1.py, import2.py file Which has few functions and classes And if I have a class with same name "BaseClass" in both the file How would I use it if I declare it as given below in my 3rd class from import1.py import * from import2.py import * regards prasad chandrasekaran --- Cancer cures smoking #-Original Message- #From: [EMAIL PROTECTED] #[mailto:[EMAIL PROTECTED] On #Behalf Of [EMAIL PROTECTED] #Sent: Wednesday, October 05, 2005 1:32 PM #To: [email protected] #Subject: Python-list Digest, Vol 25, Issue 65 # #Send Python-list mailing list submissions to # [email protected] # #To subscribe or unsubscribe via the World Wide Web, visit # http://mail.python.org/mailman/listinfo/python-list #or, via email, send a message with subject or body 'help' to # [EMAIL PROTECTED] # #You can reach the person managing the list at # [EMAIL PROTECTED] # #When replying, please edit your Subject line so it is more specific #than "Re: Contents of Python-list digest..." This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message. -- http://mail.python.org/mailman/listinfo/python-list
Re: Does any one recognize this binary data storage format
On Wed, 10 Aug 2005 13:23:22 GMT, rumours say that [EMAIL PROTECTED] (Bengt
Richter) might have written:
>BTW, my second post was doing ''.join(chr(int(h[i:i+2],16)) for i in
>xrange(0,16,2))
>to undo the hexlify you had done (I'd forgotten that there's a
>binascii.unhexlify ;-)
And there's also str.decode('hex'), at least after 2.3 .
--
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
--
http://mail.python.org/mailman/listinfo/python-list
Re: Confused with module and .py files
Iyer, Prasad C wrote: >Actually I am bit confused between the modules and .py file >How do I differentiate between the 2. > > > A module 'name' is the same as the name of your file without the '.py' extension. >For example >I have a file import1.py, import2.py file >Which has few functions and classes >And if I have a class with same name "BaseClass" in both the file > >How would I use it if I declare it as given below in my 3rd class > >from import1.py import * >from import2.py import * > > > > You should say : from import1 import * from import2 import * If according to your earlier question, you have a class with the same name in two different modules, the better thing then (as others on the list have already pointed out) is to do the following: import import1, import2 c1 = import1.MyClass() c2 = import2.MyClass() regards, Satchit Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions > > >regards >prasad chandrasekaran > > > > > > > > > > >--- Cancer cures smoking > >#-Original Message- >#From: [EMAIL PROTECTED] >#[mailto:[EMAIL PROTECTED] On >#Behalf Of [EMAIL PROTECTED] >#Sent: Wednesday, October 05, 2005 1:32 PM >#To: [email protected] >#Subject: Python-list Digest, Vol 25, Issue 65 ># >#Send Python-list mailing list submissions to ># [email protected] ># >#To subscribe or unsubscribe via the World Wide Web, visit ># http://mail.python.org/mailman/listinfo/python-list >#or, via email, send a message with subject or body 'help' to ># [EMAIL PROTECTED] ># >#You can reach the person managing the list at ># [EMAIL PROTECTED] ># >#When replying, please edit your Subject line so it is more specific >#than "Re: Contents of Python-list digest..." > >This message contains information that may be privileged or confidential and >is the property of the Capgemini Group. It is intended only for the person to >whom it is addressed. If you are not the intended recipient, you are not >authorized to read, print, retain, copy, disseminate, distribute, or use this >message or any part thereof. If you receive this message in error, please >notify the sender immediately and delete all copies of this message. > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Op 2005-10-05, Tom Anderson schreef <[EMAIL PROTECTED]>:
> On Tue, 4 Oct 2005, Robert Kern wrote:
>
>> Antoon Pardon wrote:
>>
>>> class Tree:
>>>
>>> def __lt__(self, term):
>>> return set(self.iteritems()) < set(term.iteritems())
>>>
>>> def __eq__(self, term):
>>> return set(self.iteritems()) == set(term.iteritems())
>>>
>>> Would this be a correct definition of the desired behaviour?
>>
>> No.
>>
>> In [1]: {1:2} < {3:4}
>> Out[1]: True
>>
>> In [2]: set({1:2}.iteritems()) < set({3:4}.iteritems())
>> Out[2]: False
>>
>>> Anyone a reference?
>>
>> The function dict_compare in dictobject.c .
>
> Well there's a really helpful answer. I'm intrigued, Robert - since you
> know the real answer to this question, why did you choose to tell the
> Antoon that he was wrong, not tell him in what way he was wrong, certainly
> not tell him how to be right, but just tell him to read the source, rather
> than simply telling him what you knew? Still, at least you told him which
> file to look in. And if he knows python but not C, or gets lost in the
> byzantine workings of the interpreter, well, that's his own fault, i
> guess.
>
> So, Antoon, firstly, your implementation of __eq__ is, i believe, correct.
>
> Your implementation of __lt__ is, sadly, not. While sets take "<" to mean
> "is a proper subset of", for dicts, it's a more conventional comparison
> operation, which constitutes a total ordering over all dicts (so you can
> sort with it, for example). However, since dicts don't really have a
> natural total ordering, it is ever so slightly arbitrary.
>
> The rules for ordering on dicts are, AFAICT:
>
> - If one dict has fewer elements than the other, it's the lesser
> - If not, find the smallest key for which the two dicts have different
> values (counting 'not present' as a value)
> -- If there is no such key, the dicts are equal
> -- If the key is present in one dict but not the other, the dict in which
> it is present is the lesser
> -- Otherwise, the dict in which the value is lesser is itself the lesser
>
> In code:
>
> def dict_cmp(a, b):
> diff = cmp(len(a), len(b))
> if (diff != 0):
> return diff
> for key in sorted(set(a.keys() + b.keys())):
> if (key not in a):
> return 1
> if (key not in b):
> return -1
> diff = cmp(a[key], b[key])
> if (diff != 0):
> return diff
> return 0
>
Thanks for the explanation, but you somehow give me too much.
I have been searching some more and finally stumbled on this:
http://docs.python.org/ref/comparisons.html
Mappings (dictionaries) compare equal if and only if their sorted
(key, value) lists compare equal. Outcomes other than equality are
resolved consistently, but are not otherwise defined.
This seems to imply that the specific method to sort the dictionaries
is unimported (as long as it is a total ordering). So I can use whatever
method I want as long as it is achieves this.
But that is contradicted by the unittest. If you have a unittest for
comparing dictionaries, that means comparing dictionaries has a
testable characteristic and thus is further defined.
So I don't need a full implementation of dictionary comparison,
I need to know in how far such a comparison is defined and
what I can choose.
--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Antoon Pardon <[EMAIL PROTECTED]> writes: > But that is contradicted by the unittest. If you have a unittest for > comparing dictionaries, that means comparing dictionaries has a > testable characteristic and thus is further defined. No, I don't think so. The unittest makes sure that a particular implementation works as intended. That doesn't mean that every part of the of how that particular implementation works is required by the language definition. It can have some non-required (but non-forbidden) characteristics and those could still get tested. -- http://mail.python.org/mailman/listinfo/python-list
Re: IDLE dedent/unindent key bindings for non-us keybord?
On 2 Oct 2005 08:52:53 -0700, [EMAIL PROTECTED] wrote: >Hi. > >I use Idle 1.1.1 on Python 2.4.1. > >The "Ctrl-[" and "Ctrl-]" key bindings for indenting do not work on >non-us keyboards where brackets are accessed by the "Alt Gr" key. > >The Tab key seem to work for indenting a selected textblock on my >swedish keyboard, but Shift-tab does not dedent as you would have >expected. > >If I try to redefine key bindings in "options->Configure IDLE->Keys" so >that Shift-Tab is bound to dedent, things seem to get really weird. > >After creating a "Custom key set" >- the "Ok"-button does not close the options window, I have to use >"Cancel" to get out. > I'v seen this also: this must be a bug. Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\lib\idlelib\configDialog.py", line 1197, in Apply self.ActivateConfigChanges() File "C:\Python24\lib\idlelib\configDialog.py", line 1185, in ActivateConfigCh anges instance.ResetKeybindings() File "C:\Python24\lib\idlelib\EditorWindow.py", line 585, in ResetKeybindings self.apply_bindings() File "C:\Python24\lib\idlelib\EditorWindow.py", line 837, in apply_bindings text.event_add(event, *keylist) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1299, in event_add self.tk.call(args) TclError: bad event type or keysym "tab" Exception in Tkinter callback Traceback (most recent call last): File "C:\Python24\lib\lib-tk\Tkinter.py", line 1345, in __call__ return self.func(*args) File "C:\Python24\lib\idlelib\configDialog.py", line 1192, in Ok self.Apply() File "C:\Python24\lib\idlelib\configDialog.py", line 1197, in Apply self.ActivateConfigChanges() File "C:\Python24\lib\idlelib\configDialog.py", line 1185, in ActivateConfigCh anges instance.ResetKeybindings() File "C:\Python24\lib\idlelib\EditorWindow.py", line 585, in ResetKeybindings self.apply_bindings() File "C:\Python24\lib\idlelib\EditorWindow.py", line 837, in apply_bindings text.event_add(event, *keylist) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1299, in event_add self.tk.call(args) TclError: bad event type or keysym "tab" next time, I start: C:\Python24\Lib\idlelib>idle.py error reading package index file C:/Python24/tcl/tix8.1/pkgIndex.tcl: invalid co mmand name "lt}]}" Traceback (most recent call last): File "C:\Python24\Lib\idlelib\idle.py", line 21, in ? idlelib.PyShell.main() File "C:\Python24\lib\idlelib\PyShell.py", line 1355, in main if not flist.open_shell(): File "C:\Python24\lib\idlelib\PyShell.py", line 275, in open_shell self.pyshell = PyShell(self) File "C:\Python24\lib\idlelib\PyShell.py", line 793, in __init__ OutputWindow.__init__(self, flist, None, None) File "C:\Python24\lib\idlelib\OutputWindow.py", line 16, in __init__ EditorWindow.__init__(self, *args) File "C:\Python24\lib\idlelib\EditorWindow.py", line 108, in __init__ self.apply_bindings() File "C:\Python24\lib\idlelib\EditorWindow.py", line 837, in apply_bindings text.event_add(event, *keylist) File "C:\Python24\lib\lib-tk\Tkinter.py", line 1299, in event_add self.tk.call(args) _tkinter.TclError: bad event type or keysym "tab" (On Windows) I discovered, looking in C:\.idlerc\config-keys.cfg there was the entry dedent-region = with an editor you can change it to uppercase: dedent-region = then it works again. HTH -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with module and .py files
Iyer, Prasad C wrote: > Actually I am bit confused between the modules and .py file > How do I differentiate between the 2. > > For example > I have a file import1.py, import2.py file > Which has few functions and classes > And if I have a class with same name "BaseClass" in both the file > > How would I use it if I declare it as given below in my 3rd class > > from import1.py import * > from import2.py import * Name conflicts like that are a good reason not to use from ... import *, but instead: import import1 import import2 bc1 = import1.BaseClass() bc2 = import2.BaseClass() (Note: don't include the extension .py in the import statements) Namespaces are great for preventing name conflicts; don't circumtvent them by blindly importing everything into the same namespace. As the Zen of Python says: "Namespaces are one honking great idea -- let's do more of those!" -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with module and .py files
"Iyer, Prasad C" wrote: > How would I use it if I declare it as given below in my 3rd class > > from import1.py import * > from import2.py import * thats a syntax error; I assume you meant from import1 import * from import2 import * which simply doesn't work if you need to access things that happens to have the same name in both modules. it's like typing a = 1 a = 2 and then asking how you can access the original 1 via the "a" variable. so unless you know *exactly* what you're doing, you should *never* use "from import *" -- unless you're using a module that someone else wrote, and the documentation for that module tells you do use it. see http://effbot.org/zone/import-confusion.htm for more on this. (see other replies for how to do what you want in a way that actually works). -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Op 2005-10-05, Duncan Booth schreef <[EMAIL PROTECTED]>:
> Paul Rubin wrote:
>
>> Brian Quinlan <[EMAIL PROTECTED]> writes:
>>> Have those of you who think that the lack of required declarations in
>>> Python is a huge weakness given any thought to the impact that adding
>>> them would have on the rest of the language? I can't imagine how any
>>> language with required declarations could even remotely resemble
>>> Python.
>>
>> What's the big deal? Perl has an option for flagging undeclared
>> variables with warnings ("perl -w") or errors ("use strict") and Perl
>> docs I've seen advise using at least "perl -w" routinely. Those
>> didn't have much impact. Python already has a "global" declaration;
>> how does it de-Pythonize the language if there's also a "local"
>> declaration and an option to flag any variable that's not declared as
>> one or the other?
>
> The difference is that perl actually needs 'use strict' to be useful for
> anything more than trivial scripts. Without 'use strict' you can reference
> any variable name without getting an error. Python takes a stricter
> approach to begin with by throwing an exception if you reference an
> undefined variable.
>
> This only leaves the 'assigning to a different name than the one we
> intended' problem which seems to worry some people here, and as has been
> explained in great detail it incurs a cost to anyone reading the code for
> what most Python users consider to be a very small benefit.
It also is one possibility to implement writable closures.
One could for instace have a 'declare' have the effect that
if on a more inner scope such a declared variable is (re)bound it
will rebind the declared variable instead of binding a local name.
--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
James A. Donald wrote: > What can one do to swiftly detect this type of bug? Unit tests. In my experience the edit - test cycle in Python is typically roughly as fast as the edit - compile cycle in e.g. C++, and much faster than the full edit - compile - link - test cycle in C++. You do use automated tests for your programs don't you? Otherwise I think you are sifting out gnats while you are are swallowing camels. There are also lint-like tools such as pylint and pychecker if you think static tests are useful for you. Here at Carmen, we've actually skipped the unit test step, and run functional tests at once, using the Texttest framework--and that fits well with our type of apps. See http://texttest.carmen.se/ -- http://mail.python.org/mailman/listinfo/python-list
Re: 2 class with same name in different module
> thats a syntax error; I assume you meant message = message.replace( "a syntax error", "almost always an import error (no module named py)" ) -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Antoon Pardon wrote:
> Op 2005-10-05, Tom Anderson schreef <[EMAIL PROTECTED]>:
>
>>On Tue, 4 Oct 2005, Robert Kern wrote:
>>
>>
>>>Antoon Pardon wrote:
>>>
>>>
class Tree:
def __lt__(self, term):
return set(self.iteritems()) < set(term.iteritems())
def __eq__(self, term):
return set(self.iteritems()) == set(term.iteritems())
Would this be a correct definition of the desired behaviour?
>>>
>>>No.
>>>
>>>In [1]: {1:2} < {3:4}
>>>Out[1]: True
>>>
>>>In [2]: set({1:2}.iteritems()) < set({3:4}.iteritems())
>>>Out[2]: False
>>>
>>>
Anyone a reference?
>>>
>>>The function dict_compare in dictobject.c .
>>
>>Well there's a really helpful answer. I'm intrigued, Robert - since you
>>know the real answer to this question, why did you choose to tell the
>>Antoon that he was wrong, not tell him in what way he was wrong, certainly
>>not tell him how to be right, but just tell him to read the source, rather
>>than simply telling him what you knew? Still, at least you told him which
>>file to look in. And if he knows python but not C, or gets lost in the
>>byzantine workings of the interpreter, well, that's his own fault, i
>>guess.
>>
>>So, Antoon, firstly, your implementation of __eq__ is, i believe, correct.
>>
>>Your implementation of __lt__ is, sadly, not. While sets take "<" to mean
>>"is a proper subset of", for dicts, it's a more conventional comparison
>>operation, which constitutes a total ordering over all dicts (so you can
>>sort with it, for example). However, since dicts don't really have a
>>natural total ordering, it is ever so slightly arbitrary.
>>
>>The rules for ordering on dicts are, AFAICT:
>>
>>- If one dict has fewer elements than the other, it's the lesser
>>- If not, find the smallest key for which the two dicts have different
>>values (counting 'not present' as a value)
>>-- If there is no such key, the dicts are equal
>>-- If the key is present in one dict but not the other, the dict in which
>>it is present is the lesser
>>-- Otherwise, the dict in which the value is lesser is itself the lesser
>>
>>In code:
>>
>>def dict_cmp(a, b):
>> diff = cmp(len(a), len(b))
>> if (diff != 0):
>> return diff
>> for key in sorted(set(a.keys() + b.keys())):
>> if (key not in a):
>> return 1
>> if (key not in b):
>> return -1
>> diff = cmp(a[key], b[key])
>> if (diff != 0):
>> return diff
>> return 0
>>
>
>
> Thanks for the explanation, but you somehow give me too much.
>
> I have been searching some more and finally stumbled on this:
>
> http://docs.python.org/ref/comparisons.html
>
> Mappings (dictionaries) compare equal if and only if their sorted
> (key, value) lists compare equal. Outcomes other than equality are
> resolved consistently, but are not otherwise defined.
>
> This seems to imply that the specific method to sort the dictionaries
> is unimported (as long as it is a total ordering). So I can use whatever
> method I want as long as it is achieves this.
>
> But that is contradicted by the unittest. If you have a unittest for
> comparing dictionaries, that means comparing dictionaries has a
> testable characteristic and thus is further defined.
>
> So I don't need a full implementation of dictionary comparison,
> I need to know in how far such a comparison is defined and
> what I can choose.
>
The dict unit tests are probably trying to ensure that the dictionary
ordering doesn't change from version to version, which is probably a
good idea in case someone (foolishly?) deciess to rely on it.
I can't help wondering, though, under what conditions it actually makes
sense to compare two dictionaries for anything other than equality.
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: New project coming up...stay with Python, or go with a dot net language??? Your thoughts please!
On 10/4/05, Cameron Laird <[EMAIL PROTECTED]> wrote: Python IS "a dot net language" http://ironpython.com/ >. . that is the site it was born at; but microsoft has actively adopted it here: IronPython 0.9.2 (9/22/2005) [EMAIL PROTECTED] http://www.microsoft.com/downloads/details.aspx?FamilyID=2C649E9E-CF43-41E0-9E22-6E6438924CAA&displaylang=en#additionalInfo Overview IronPython is the codename for an alpha release of the Python programming language for the .NET platform. It supports an interactive interpreter with fully dynamic compilation . It is well integrated with the rest of the framework and makes all .NET libraries easily available to Python programmers. . the active dev site [EMAIL PROTECTED] http://www.gotdotnet.com/workspaces/workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 . the IronPython mailing list [EMAIL PROTECTED] http://lists.ironpython.com/listinfo.cgi/users-ironpython.com -- American Dream Documentshttp://www.geocities.com/amerdreamdocs/home/"(real opportunity starts with real documentation) -- http://mail.python.org/mailman/listinfo/python-list
Re: Confused with module and .py files
Iyer, Prasad C wrote: > Actually I am bit confused between the modules and .py file > How do I differentiate between the 2. > > For example > I have a file import1.py, import2.py file > Which has few functions and classes > And if I have a class with same name "BaseClass" in both the file > > How would I use it if I declare it as given below in my 3rd class > > from import1.py import * > from import2.py import * > You can't do that. The "from module import *" mechanism explicitly defines names in the importing module's namespace, so if you use this technique to import two modules that define the same name you will inevitably find that the second import overwrites the duplicate name imported by the first import. Note also that the ".py" should not be included in the import statement - the interpreter finds the appropriate code from the module name, so you should anyway be doing something like from import2 import * from import2 import * It would be much better, though, to write: import import1 import import2 Then you can refer to import1.BaseClass and import2.baseClass without getting any naming conflicts. In general the "from module import *" form should only be used under specific conditions, which we needn't discuss here now. 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: Pygame: Filling the screen with tile images
I don't think PyGame will handle tiling for you, or any concept of a 'background image'. If you want something to appear multiple times on the screen, you need to draw it multiple times. If you do that onto a surface that is the same size as your screen, you can then consider that the background image and blit that to the screen at the start of every frame you draw. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Antoon Pardon wrote: > It also is one possibility to implement writable closures. > > One could for instace have a 'declare' have the effect that > if on a more inner scope such a declared variable is (re)bound it > will rebind the declared variable instead of binding a local name. That is one possibility, but I think that it would be better to use a keyword at the point of the assigment to indicate assignment to an outer scope. This fits with the way 'global' works: you declare at (or near) the assignment that it is going to a global variable, not in some far away part of the code, so the global nature of the assignment is clearly visible. The 'global' keyword itself would be much improved if it appeared on the same line as the assignment rather than as a separate declaration. e.g. something like: var1 = 0 def f(): var2 = 0 def g(): outer var2 = 1 # Assign to outer variable global var1 = 1 # Assign to global -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Op 2005-10-05, Paul Rubin schreef : > Antoon Pardon <[EMAIL PROTECTED]> writes: >> But that is contradicted by the unittest. If you have a unittest for >> comparing dictionaries, that means comparing dictionaries has a >> testable characteristic and thus is further defined. > > No, I don't think so. The unittest makes sure that a particular > implementation works as intended. That doesn't mean that every part > of the of how that particular implementation works is required by the > language definition. As far as I understand, unittest test for functionality clients should be able to rely on. They shouldn't be used to test a specific implementation feature. The idea is that if you change the implementation, you can quickly test the functionality is unharmed. But you can't do that if also specific implementation details are tested for. > It can have some non-required (but > non-forbidden) characteristics and those could still get tested. That doesn't seem to make sense. If it is not required it shouldn't be tested for, at least not in a unittest, because otherwise a new implementation that doesn't have the non-required characteristics will be rejected. My tree class is almost finished, but one unittest still fails, is this a failing of my class (as a replacement for a dictionary) or is this a non-required characteristic of dictionaries? -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Brian Quinlan <[EMAIL PROTECTED]> writes:
> > Python already has a "global" declaration;
>
> Which is evaluated at runtime, does not require that the actual global
> variable be pre-existing, and does not create the global variable if
> not actually assigned. I think that is pretty different than your
> proposal semantics.
Different how?
> Your making this feature "optional" contradicts the subject of this
> thread i.e. declarations being necessary.
They're necessary if you enable the option.
> But, continuing with your declaration thought experiment, how are
> you planning on actually adding optional useful type declarations to
> Python e.g. could you please rewrite this (trivial) snippet using
> your proposed syntax/semantics?
def do_add(x->str, y->str):
return '%s://%s' % (x, y)
def do_something(node->Node):
if node.namespace == XML_NAMESPACE:
return do_add('http://', node.namespace)
elif node.namespace == ...
--
http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Steve Holden <[EMAIL PROTECTED]> writes: > I can't help wondering, though, under what conditions it actually > makes sense to compare two dictionaries for anything other than > equality. You might want to sort a bunch of dictionaries to bring the equal ones together. -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Antoon Pardon <[EMAIL PROTECTED]> writes: > My tree class is almost finished, but one unittest still fails, > is this a failing of my class (as a replacement for a dictionary) > or is this a non-required characteristic of dictionaries? If it were me, I'd treat the language reference manual as authoritative. YMMV. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Paul Rubin wrote:
> Brian Quinlan <[EMAIL PROTECTED]> writes:
>
>>Have those of you who think that the lack of required declarations in
>>Python is a huge weakness given any thought to the impact that adding
>>them would have on the rest of the language? I can't imagine how any
>>language with required declarations could even remotely resemble
>>Python.
>
>
> Python already has a "global" declaration;
Which is evaluated at runtime, does not require that the actual global
variable be pre-existing, and does not create the global variable if not
actually assigned. I think that is pretty different than your proposal
semantics.
> how does it de-Pythonize the language if there's also a "local"
> declaration and an option to flag any variable that's not declared as
> one or the other?
Your making this feature "optional" contradicts the subject of this
thread i.e. declarations being necessary. But, continuing with your
declaration thought experiment, how are you planning on actually adding
optional useful type declarations to Python e.g. could you please
rewrite this (trivial) snippet using your proposed syntax/semantics?
from xml.dom import *
def do_add(x, y):
return '%s://%s' % (x, y)
def do_something(node):
if node.namespace == XML_NAMESPACE:
return do_add('http://', node.namespace)
elif node.namespace == ...
...
> There's been a proposal from none other than GvR to add optional
> static declarations to Python:
>
> http://www.artima.com/weblogs/viewpost.jsp?thread=85551
A few points:
1. making it work in a reasonable way is an acknowledged hard problem
2. it will still probably not involve doing type checking at
compile-time
3. it would only generate a warning, not an error
Cheers,
Brian
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python script to install network printers
These functions should get you started and probably finished...
def createprinterport(IPAddress,ServerName):
WBEM =
win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\"
+ ServerName + r"\root\cimv2")
WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege")
printerport = WBEM.Get("Win32_TCPIPPrinterPort").SpawnInstance_()
printerport.Properties_('Name').Value = 'IP_'+IPAddress
printerport.Properties_('Protocol').Value = 1
printerport.Properties_('HostAddress').Value = IPAddress
printerport.Properties_('PortNumber').Value = '9100'
printerport.Properties_('SNMPEnabled').Value = 'False'
printerport.Put_()
def
createprinter(PrinterName,DriverName,Location,ShareName,IPAddress,ServerName):
WBEM =
win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\"
+ ServerName + r"\root\cimv2")
WBEM.Security_.ImpersonationLevel = 3
WBEM.Security_.Privileges.AddAsString("SeLoadDriverPrivilege")
printer = WBEM.Get("Win32_Printer").SpawnInstance_()
printer.Properties_('DeviceID').Value = PrinterName
printer.Properties_('DriverName').Value = DriverName
printer.Properties_('Location').Value = Location
printer.Properties_('Network').Value = 'True'
printer.Properties_('Shared').Value = 'True'
printer.Properties_('ShareName').Value = ShareName
printer.Properties_('PortName').Value = 'IP_'+IPAddress
printer.Put_()
I also created one for migrating print drivers but had loads of
problems with it. If the driver doesn't pass Microsoft logo testing
the scripts fail even if it is signed by Microsoft. I never worked out
why there were 2 levels of protection.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python script to install network printers
The target OS needs to support WMI so 2000 or XP. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Brian Quinlan wrote: > Paul Rubin wrote: > >>Brian Quinlan <[EMAIL PROTECTED]> writes: >> >> >>>Have those of you who think that the lack of required declarations in >>>Python is a huge weakness given any thought to the impact that adding >>>them would have on the rest of the language? I can't imagine how any >>>language with required declarations could even remotely resemble >>>Python. >> >> >>Python already has a "global" declaration; > > > Which is evaluated at runtime, does not require that the actual global > variable be pre-existing, and does not create the global variable if not > actually assigned. I think that is pretty different than your proposal > semantics. > I believe that "global" is the one Python statement that isn't actually executable, and simply conditions the code generated during compilation (to bytecode). Hard to see why someone would want to use a global declaration unless they were intending to assign to it, given the sematnics of access. > [...] 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: Excel library with unicode support
[Mike] > Is there a python library, that is able to create Excel files with > unicode characters. pyExcelerator claims to do this, but I've never used it. http://sourceforge.net/projects/pyexcelerator/ -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
sos too long penis
I had in the past the most ridiculous erection in the world,4in.I'm not poor and then,I used all the supposed "miraculous products" to rectify.Vainly.Until one of my friends,who experimented it himself,advise me to use an african grass,in the way of tea.As long as I haven't obtain the desired size.I bought it. It tooks to me 2months to reach 9.5in. I fully enjoyed it 3years long. But now,I'ld like to loose 2in.I think I'ld had stop the grass-tea 2weeks earliers.9.5in is a little too long. Girls and men often run away when they see it.Too big bar. What is more ,at the beach,it is really umpleasant to be always remarked because of it. I am now exasperated,I'll really want to loose a little. Help me finding a way. Do some one know something who can help me or a good surgeon?(if it is possible and riskfree) Please help me I'm on [EMAIL PROTECTED] PS excuse my bad smelling english. Expecting you soon. Don't send me please any mail asking for what I used,take your self informations on www.geocities.com/tchwill85/PENIS.html Thinks -- http://mail.python.org/mailman/listinfo/python-list
Re: Help needed in OOP-Python
Thanks Fredrik. Went through the code to make sure "self" was used properly and one of the parent classes was missing a "self".It's fixed now. /me kicks self -toufeeqOn 10/5/05, Toufeeq Hussain <[EMAIL PROTECTED]> wrote: Fredrik, sigh! I see the problem you mention and I agree. Should have posted the orginal code without edits. :( Anyway I'll try to fill in whereever required.On 10/5/05, Fredrik Lundh < [EMAIL PROTECTED]> wrote: $ python test.pycondition satisfiedTraceback (most recent call last): File "test.py", line 4, in ?Test_Case.Option1_constraint() File "module3.py", line 11, in Option1_constraintself.FOO_warning.Fire()AttributeError: Option1_Rule1 instance has no attribute 'FOO_warning' FOO_warning? there's no FOO_warning anywhere in the code. FOO_warning is "Option1_warning" from Module3. And, in Module1 comment out the line: "common_subs.write_to_out_file( 'FOO_OUT',self.Warn_text)" :::so, after four attempts, I've found four problems, three of which was present in your posted code, but I still haven't seen the problem you reported:Traceback (most recent call last): File "test_case.py", line 7, in ?TH = constraint.Option1_Rule1() File " constraint.py", line 13, in __init__declaration.Option1.__init__(self)TypeError: __init__() takes no arguments (1 given) But the script when given as individual commands works fine in IDLE. While executing the script it throws that error. :( which, in itself, looks like you've forgotten the self argument in some init method somewhere (but the code you posted doesn't have that problem). Yes,I've doubled checked this. if you want to post code, 1) try to reduce the problem to as little code as you possibly can, and 2) make sure that the code you post really has the problemyou're seeing... (i.e. run it at least once before you post it) All points noted and will follow the same. Thanks and my sincere apologies. -toufeeq-- Get Firefox:http://www.mozilla.org/products/firefox/ The fastest, safest and best Browser !! -- Get Firefox:http://www.mozilla.org/products/firefox/The fastest, safest and best Browser !! -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Op 2005-10-05, Steve Holden schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>>
>> I have been searching some more and finally stumbled on this:
>>
>> http://docs.python.org/ref/comparisons.html
>>
>> Mappings (dictionaries) compare equal if and only if their sorted
>> (key, value) lists compare equal. Outcomes other than equality are
>> resolved consistently, but are not otherwise defined.
>>
>> This seems to imply that the specific method to sort the dictionaries
>> is unimported (as long as it is a total ordering). So I can use whatever
>> method I want as long as it is achieves this.
>>
>> But that is contradicted by the unittest. If you have a unittest for
>> comparing dictionaries, that means comparing dictionaries has a
>> testable characteristic and thus is further defined.
>>
>> So I don't need a full implementation of dictionary comparison,
>> I need to know in how far such a comparison is defined and
>> what I can choose.
>>
> The dict unit tests are probably trying to ensure that the dictionary
> ordering doesn't change from version to version, which is probably a
> good idea in case someone (foolishly?) deciess to rely on it.
I doubt that. Just to check I tried the following:
class Tree:
def __lt__(self, term):
return len(self) < len(term)
And the test passed.
> I can't help wondering, though, under what conditions it actually makes
> sense to compare two dictionaries for anything other than equality.
Yes that is part of the problem, because I can't think of such a
condition it is hard to think of what extra constraints could be
usefull here.
Anyway, I have searched the source of the test for all testing
with regards to < and after some browsing back and fore it seems
it all boils down to the following two tests.
self.assert_(not {} < {})
self.assert_(not {1: 2} < {1L: 2L})
--
Antoon Pardon
--
http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Op 2005-10-05, Duncan Booth schreef <[EMAIL PROTECTED]>: > Antoon Pardon wrote: > >> It also is one possibility to implement writable closures. >> >> One could for instace have a 'declare' have the effect that >> if on a more inner scope such a declared variable is (re)bound it >> will rebind the declared variable instead of binding a local name. > > That is one possibility, but I think that it would be better to use a > keyword at the point of the assigment to indicate assignment to an outer > scope. This fits with the way 'global' works: you declare at (or near) the > assignment that it is going to a global variable, not in some far away part > of the code, so the global nature of the assignment is clearly visible. As far as I understand people don't like global very much so I don't expect that a second keyword with the same kind of behaviour has any chance. > The > 'global' keyword itself would be much improved if it appeared on the same > line as the assignment rather than as a separate declaration. > > e.g. something like: > > var1 = 0 > > def f(): > var2 = 0 > > def g(): > outer var2 = 1 # Assign to outer variable > global var1 = 1 # Assign to global And what would the following do: def f(): var = 0 def g(): var = 1 def h(): outer var = 2 * var + 1 h() print var g() print var f() -- http://mail.python.org/mailman/listinfo/python-list
Quick help needed: how to format an integer ?
Hi ! I need to convert some integer values. "1622" ->"1 622" or "10001234" -> ""10.001.234"" So I need thousand separators. Can anyone helps me with a simply solution (like %xxx) ? Thanx for it: dd Ps: Now I use this proc: def toths(i): s=str(i) l=[] ls=len(s) for i in range(ls): c=s[ls-i-1] if i%3==0 and i<>0: c=c+"." l.append(c) l.reverse() return "".join(l) -- http://mail.python.org/mailman/listinfo/python-list
Re: Quick help needed: how to format an integer ?
One possible solution. Don't know how efficient it is though. :-)
>>> def put_decimal(s):
... return ''.join( [ [s[i], '.%s' % s[i]][(len(s)-i)%3 == 0] for i
in range(0, len(s))])
...
>>> put_decimal("10001234")
'10.001.234'
>>> put_decimal("12622")
'12.622'
thanks,
Satchit
[EMAIL PROTECTED] wrote:
>Hi !
>
>I need to convert some integer values.
>
>"1622" ->"1 622"
>
>or
>
>"10001234" -> ""10.001.234""
>
>So I need thousand separators.
>
>Can anyone helps me with a simply solution (like %xxx) ?
>
>Thanx for it: dd
>
>Ps:
>Now I use this proc:
>
>def toths(i):
>s=str(i)
>l=[]
>ls=len(s)
>for i in range(ls):
>c=s[ls-i-1]
>if i%3==0 and i<>0:
> c=c+"."
>l.append(c)
>l.reverse()
>return "".join(l)
>
>
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Quick help needed: how to format an integer ?
[EMAIL PROTECTED] wrote: > Hi ! > > I need to convert some integer values. > > "1622" ->"1 622" > > or > > "10001234" -> ""10.001.234"" > > So I need thousand separators. > > Can anyone helps me with a simply solution (like %xxx) ? The module locale does what you need, look at ist docs, especially locale.str locale.format Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Quick help needed: how to format an integer ?
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes: > "10001234" -> ""10.001.234"" > So I need thousand separators. > Can anyone helps me with a simply solution (like %xxx) ? I think you're supposed to do a locale-specific conversion (I've never understood that stuff). You could also do something like this: >>> def f(n): if n < 0: return '-' + f(-n) if n < 1000: return '%d' % n return f(n//1000) + '.' + '%03d' % (n%1000) >>> f(3900900090090909009) '39.009.000.900.909.090.000.009' >>> f(39802183) '39.802.183' >>> f(3008) '3.008' >>> f(0) '0' >>> f(-9898239839) '-9.898.239.839' >>> f(12345) '12.345' -- http://mail.python.org/mailman/listinfo/python-list
bug or feature?
Coming back from a bug hunt, i am not sure what to think of this python
behaviour. Here is a demo program:
class A:
def __init__(self, lst=[]):
self.lst = lst
a = A()
b = A()
b.lst.append("hallo")
print a.lst # output: ["hallo"]
The point seems to be, that lst=[] creates a class attribute (correct
name?), which is shared by all instances of A. So a.lst ist the same
object as b.lst, despite the fact, that object a is different to object
b.
--
http://mail.python.org/mailman/listinfo/python-list
Re: python plotting with greek symbols within labels recommendations?
Hi, [EMAIL PROTECTED] wrote: > this message is geared toward those of you in the scientific community. > i'm looking for a python plotting library that can support rendering > greek symbols and other various characters on plot axes labels, etc. I > would prefer something that adheres to tex formatting (as implemented > in latex, matlab, etc and has the form $\alpha$ to represent the greek > character alpha for example). You may want to have a look at PyX (pyx.sourceforge.net), which features a seamless TeX integration for all typesetting tasks and thus allows you to use TeX syntax all over the place. André -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
beza1e1> class A: beza1e1>def __init__(self, lst=[]): beza1e1> self.lst = lst Lists are mutable and default args are only evaluated once, at function definition. If you want independent default args use: class A: def __init__(self, lst=None): if lst is None: lst = [] self.lst = lst The same scheme would work for other mutable types (dicts, sets, etc). This same question gets asked once a month or so. I'm sure this is in the Python FAQ (check the website), but it was faster to reply than to look it up... Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary interface
Antoon Pardon wrote:
> Op 2005-10-05, Steve Holden schreef <[EMAIL PROTECTED]>:
[...]
>
> Anyway, I have searched the source of the test for all testing
> with regards to < and after some browsing back and fore it seems
> it all boils down to the following two tests.
>
>self.assert_(not {} < {})
>self.assert_(not {1: 2} < {1L: 2L})
>
So there isn't much to do, then! That's good. Seems you can pretty much
choose your own ordering.
It would seem sensible to test a third case, namely
self.assert_(not {1L: 2L} < {1: 2})
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: bug or feature?
beza1e1 wrote:
> Coming back from a bug hunt, i am not sure what to think of this python
> behaviour. Here is a demo program:
>
> class A:
>def __init__(self, lst=[]):
> self.lst = lst
>
> a = A()
> b = A()
> b.lst.append("hallo")
> print a.lst # output: ["hallo"]
>
> The point seems to be, that lst=[] creates a class attribute (correct
> name?), which is shared by all instances of A. So a.lst ist the same
> object as b.lst, despite the fact, that object a is different to object
> b.
>
It is an *instance attribute* by nature, since it does not reside in the
class object, but only in its instances. The truth is, that a.lst and
b.lst point to the same memory object, so it seems to behave much like
the class attribute :)
It is no more different from the simple fact, that two variables
(attributes) may point to the same memory object, like you see below:
a = b = []
a.append("hallo")
print b #output: ["hallo"]
In fact, it is usually a bad practice to assign instance attributes a
reference to the compound variable, existing in an external scope. Example:
aList = []
class A:
def __init__(self, lst): #no default attribute!
self.lst = lst
a = A(aList)
aList.append("hallo")
print a.lst #output: ["hallo"]
and your default value (, lst=[]) IS such an variable! The bad thing is,
that the value of the instance attribute 'lst' (example above) depends
on the external variable, which may be independently modified, thus
modifying unexpectedly the instance attribute. The safer approach, of
course is to write:
class A:
def __init__(self, lst): #no default attribute!
self.lst = lst[:] #take a copy
Summing up, is it an error, or a feature? I would say - a feature.
Everyone should be aware, that the argument default values are evaluated
once, and the same value (memory object) is reused at each instance
creation.
Best regards,
Tomasz Lisowski
--
http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
Python.org General FAQ 1.4.21: Why are default values shared between objects? (http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects) -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
beza1e1 wrote:
> Coming back from a bug hunt, i am not sure what to think of this python
> behaviour. Here is a demo program:
>
> class A:
>def __init__(self, lst=[]):
> self.lst = lst
>
> a = A()
> b = A()
> b.lst.append("hallo")
> print a.lst # output: ["hallo"]
>
> The point seems to be, that lst=[] creates a class attribute (correct
> name?), which is shared by all instances of A. So a.lst ist the same
> object as b.lst, despite the fact, that object a is different to object
> b.
>
Interestingly I couldn't find this in the FAQ, though it *is* a
frequently-asked question [note: my not finding it doesn't guarantee
it's not there]. The nearest I could get was in
http://www.python.org/doc/faq/programming.html#my-program-is-too-slow-how-do-i-speed-it-up
which says:
"""Default arguments can be used to determine values once, at compile
time instead of at run time."""
The point is that the value of the keyword argument is determined when
the def statement is executed (which is to say when the function body is
being bound to its name).
If the default argument is (a reference to) a mutable object (such as a
list instance) then if one call to the function modifies that mutable
object, subsequent calls see the mutated instance as the default value.
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: Python, Mysql, insert NULL
Python_it wrote:
>Python 2.4
>MySQL-python.exe-1.2.0.win32-py2.4.zip
>
>How can I insert a NULL value in a table (MySQL-database).
>I can't set a var to NULL? Or is there a other possibility?
>My var must be variable string or NULL.
>Becaus i have a if statement:
>if
> cursor.execute(".insert NULL ..")
>if
> cursor.execute(".insert "string" ..")
>
>
>
Use parameters! For example, did you try:
cursor.execute(" insert into tablename(fieldname) values (%s)",[value])
None will be converted to NULL, any other value will be quoted as neccesary.
BTW, you did not write which driver are you using.
Usage of parameters is different for each driver, but it is standardized.
If it is DB API 2.0 compatible, then parametrized queries should work as
desicribed in PEP 0249:
http://www.python.org/peps/pep-0249.html
Under 'cursor objects' section, look for the '.execute' method.
--
http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Antoon Pardon wrote: > Op 2005-10-04, Ron Adam schreef <[EMAIL PROTECTED]>: > >>Antoon Pardon wrote: >> >>>Op 2005-10-03, Steven D'Aprano schreef <[EMAIL PROTECTED]>: >>> And lo, one multi-billion dollar Mars lander starts braking either too early or too late. Result: a new crater on Mars, named after the NASA employee who thought the compiler would catch errors. >>> >>> >>>Using (unit)tests will not guarantee that your programs is error free. >>> >>>So if sooner or later a (unit)tested program causes a problem, will you >>>then argue that we should abondon tests, because tests won't catch >>>all errors. >> >>Maybe you need to specify what kind of errors you want to catch. >>Different types of errors require different approaches. > > > I want to catch all errors of course. Yes, of course, and so do other programmers. What I mean is to try and break it down into specific instances and then see what the best approach is for each one is. When I first started leaning Python I looked for these features as well, but after a while my programming style changed and I don't depend on types and names to check my data near as much now. But instead write better organized code and data structures with more explicit value checks where I need them. My concern now is having reusable code and modules I can depend on. And also separating my data and data management operations from the user interface. Having functions and names that don't care what type the objects are, makes doing this separation easier. Another situation where typeless names are useful is routines that explicitly check the type, then depending on the type does different things. For example if you have a list with a lot of different type objects stored in it, you can sort the contents into sublists by type. Looking at it from a different direction, how about adding a keyword to say, "from this point on, in this local name space, disallow new names". Then you can do... def few(x,y): a = 'a' b = 'b' i = j = k = l = None no_new_names # raise an error after here if a new name is used. ... for I in range(10): <-- error ... This is more suitable to Pythons style than declaring types or variables I think. Add to this explicit name-object locking to implement constants and I think you would have most of the features you want. so... no_new_names # limit any new names lock_name name # lock a name to it's current object Since names are stored in dictionaries, a dictionary attribute to disallow/allow new keys, and a way to set individual elements in a dictionary to read only would be needed. Once you can do that and it proves useful, then maybe you can propose it as a language feature. These might also be checked for in the compile stage and would probably be better as it wouldn't cause any slow down in the code or need a new dictionary type. An external checker could possibly work as well if a suitable marker is used such as a bare string. ... x = y = z = None "No_New_Names"# checker looks for this ... X = y/z # and reports this as an error return x,y and.. ... Author = "Fred" "Name_Lock Author"# checker sees this... ... Author = "John" # then checker catches this ... So there are a number of ways to possibly add these features. Finding common use cases where these would make a real difference would also help. Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Python, Mysql, insert NULL
Python 2.4
MySQL-python.exe-1.2.0.win32-py2.4.zip
How can I insert a NULL value in a table (MySQL-database).
I can't set a var to NULL? Or is there a other possibility?
My var must be variable string or NULL.
Becaus i have a if statement:
if
cursor.execute(".insert NULL ..")
if
cursor.execute(".insert "string" ..")
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python, Mysql, insert NULL
> > BTW, you did not write which driver are you using. Oh, you did. Sorry. :-( Import your DB module 'yourmodule' and then print yourmodule.paramstyle Description of paramstyle is also in PEP249: paramstyle String constant stating the type of parameter marker formatting expected by the interface. Possible values are [2]: 'qmark' Question mark style, e.g. '...WHERE name=?' 'numeric' Numeric, positional style, e.g. '...WHERE name=:1' 'named' Named style, e.g. '...WHERE name=:name' 'format'ANSI C printf format codes, e.g. '...WHERE name=%s' 'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s' Best, Les e.g. '...WHERE name=%(name)s' -- http://mail.python.org/mailman/listinfo/python-list
RE: Confused with module and .py files
Sorry guys for that .py in import. It was typing mistake. Extremely sorry regards prasad chandrasekaran --- Cancer cures smoking #-Original Message- #From: Steve Holden [mailto:[EMAIL PROTECTED] #Sent: Wednesday, October 05, 2005 2:43 PM #To: [email protected] #Subject: Re: Confused with module and .py files # #Iyer, Prasad C wrote: #> Actually I am bit confused between the modules and .py file #> How do I differentiate between the 2. #> #> For example #> I have a file import1.py, import2.py file #> Which has few functions and classes #> And if I have a class with same name "BaseClass" in both the file #> #> How would I use it if I declare it as given below in my 3rd class #> #> from import1.py import * #> from import2.py import * #> #You can't do that. The "from module import *" mechanism explicitly #defines names in the importing module's namespace, so if you use this #technique to import two modules that define the same name you will #inevitably find that the second import overwrites the duplicate name #imported by the first import. # #Note also that the ".py" should not be included in the import statement #- the interpreter finds the appropriate code from the module name, so #you should anyway be doing something like # # from import2 import * # from import2 import * # #It would be much better, though, to write: # # import import1 # import import2 # #Then you can refer to import1.BaseClass and import2.baseClass without #getting any naming conflicts. In general the "from module import *" form #should only be used under specific conditions, which we needn't discuss #here now. # #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/ # This message contains information that may be privileged or confidential and is the property of the Capgemini Group. It is intended only for the person to whom it is addressed. If you are not the intended recipient, you are not authorized to read, print, retain, copy, disseminate, distribute, or use this message or any part thereof. If you receive this message in error, please notify the sender immediately and delete all copies of this message. -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
Steve Holden wrote: > Interestingly I couldn't find this in the FAQ, though it *is* a > frequently-asked question [note: my not finding it doesn't guarantee > it's not there]. it's there: http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects (maybe "default values" should be changed to "default argument values") it's also mentioned in chapter 4 of the tutorial: http://docs.python.org/tut/node6.html#SECTION00671 "*Important warning*: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. " (the text then illustrates this with examples, and shows how to do things instead) and in the description of "def" in the language reference: http://docs.python.org/ref/function.html "*Default parameter values are evaluated when the function definition is executed*. This means that the expression is evaluated once, when the function is defined, and that that same "pre-computed" value is used for each call. This is especially important to understand when a default para- meter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified." (the text then shows how to do things instead) -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Antoon Pardon wrote: > As far as I understand people don't like global very much so I don't > expect that a second keyword with the same kind of behaviour has > any chance. That's why the behaviour I suggest is different than the current behaviour of global. Arguments against global (it is the only non-executable statement in Python & it is confusing because people don't understand the declaration goes inside the function instead of at global scope) don't apply. > >> The >> 'global' keyword itself would be much improved if it appeared on the >> same line as the assignment rather than as a separate declaration. >> >> e.g. something like: >> >> var1 = 0 >> >> def f(): >> var2 = 0 >> >> def g(): >> outer var2 = 1 # Assign to outer variable >> global var1 = 1 # Assign to global > > And what would the following do: > > def f(): > > var = 0 > > def g(): > > var = 1 > > def h(): > > outer var = 2 * var + 1 > > h() > print var > > g() > print var > > f() > It would follow the principle of least surprise and set the value of var in g() of course. The variable in f is hidden, and if you didn't mean to hide it you didn't need to give the two variables the same name. So the output would be: 3 0 (output verified by using my hack for setting scoped variables:) --- from hack import * def f(): var = 0 def g(): var = 1 def h(): assign(lambda: var, 2 * var + 1) h() print var g() print var f() --- -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Mysql, insert NULL
I know how to insert values in a database. That's not my problem! My problem is how i insert NULL values in de mysql-database. None is een object in Python and NULL not. None is not converted to NULL? Table shows None and not NULL! -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Paul Rubin wrote:
>>Which is evaluated at runtime, does not require that the actual global
>>variable be pre-existing, and does not create the global variable if
>>not actually assigned. I think that is pretty different than your
>>proposal semantics.
>
>
> Different how?
Aren't you looking for some of compile-time checking that ensures that
only declared variables are actually used? If so, how does global help?
>>Your making this feature "optional" contradicts the subject of this
>>thread i.e. declarations being necessary.
>
> They're necessary if you enable the option.
OK. Would it work on a per-module basis or globally?
> def do_add(x->str, y->str):
> return '%s://%s' % (x, y)
>
> def do_something(node->Node):
> if node.namespace == XML_NAMESPACE:
> return do_add('http://', node.namespace)
> elif node.namespace == ...
Wouldn't an error be generated because XML_NAMESPACE is not declared?
And I notice that you are not doing any checking that "namespace" is a
valid attribute of the node object. Aren't the typos class of error that
you are looking to catch just as likely to occur for attributes as
variables?
Cheers,
Brian
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
In case you missed it, I said I have windows XP. Windows XP pre-compiled python binaries are built on VS .NET 2003. In order to build extensions, you need the compiler the interpreter was built on, or at least that is what is reported to me by calling setup.py. If I was using linux, which I currently am not, it'd be a different story. Additionally, GCC isn't available for windows XP, only MinGW, the port, and I don't know that much about it to use it running on a Windows platform. Furthermore, I was asking for help on an extension, not an economical question about my programming environment. Thanks > > > On Oct 4, 2005, at 10:25 PM, Brandon Keown wrote: >> >>I have programmed a fractal generator (Julia Set/Mandelbrot Set) >> in python in the past, and have had good success, but it would run so >> slowly because of the overhead involved with the calculation. I >> recently purchased VS .NET 2003 (Win XP, precomp binary of python >> 2.4.2rc1) to make my own extensions. > > Why did you need to purchase anything when gcc is available for free? > > > --- > Andrew Gwozdziewycz > [EMAIL PROTECTED] > http://ihadagreatview.org > http://plasticandroid.org > > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
Thanks for you answer! This copy trick is the most elegant solution i think. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Mike Meyer wrote:
(snip)
> Antoon, at a guess I'd say that Python is the first time you've
> encountered a dynamnic language. Being "horrified" at not having
> variable declarations,
Mike, "being horrified" by the (perceived as...) lack of variable
declaration was the OP's reaction, not Antoon's.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
Maksim Kasimov a écrit : > > yes, to generete core dump is the best way, > > but the command "$ ulimit -c 50" don't make python to generete core > dump in the time of crush. > > I would like to know how to run python script so if it crushes than core > dump will be genereted. > > Thanks > > If it does not, that probably means the core file is larger ... try a larger value or even "unlimited" : $ ulimit -c unlimited Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
Brandon Keown wrote: >I have programmed a fractal generator (Julia Set/Mandelbrot Set) in > python in the past, and have had good success, but it would run so > slowly because of the overhead involved with the calculation. I > recently purchased VS .NET 2003 (Win XP, precomp binary of python > 2.4.2rc1) to make my own extensions. I was wondering if anyone could > help me figure out why I'm getting obscure memory exceptions (runtime > errors resulting in automatic closing of Python) with my extension. It > seems to run okay if imported alone, but when accompanied in a list of > instructions such as a function it crashes. a short script or interpreter session that illustrates how to get the errors would help. -- http://mail.python.org/mailman/listinfo/python-list
Re: While and If messing up my program?
On Wed, 05 Oct 2005 00:10:12 -0700, [EMAIL PROTECTED] wrote: > hi, > > to get howmany element list appear you can code: > ttllst=[4,3,45,3] > for x in ttllst: > print x, ttllst.count(x) > pass > > to get non duplicate element list you can code: > ttllst=[4,3,45,3] > print list(set(ttllst)) These are excellent things to use in Python, but for learning programming skills, they are terrible because they rely on black boxes to do everything. I remember once having to code a matrix division algorithm in "the language of your choice" for a comp sci course. So of course, being a smart arse, I programmed it in the HP-28S calculator programming language, which just happened to have matrices as a native object type, complete with division. I answered the question exactly, and learnt absolutely nothing from the exercise. (For the record, I failed that course.) It is good to tell the original poster how he should be implementing the code he is trying to write, but that is not as important as helping him work out where the code is going wrong. In this case, the problem is that C.J. carefully checks that his indexes are within the valid range for the list, but (s)he makes that check *after* attempting to use the indexes. So the code fails before it reaches the test. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Call C functions from Python
I used, myApp = CDLL("C:...") ...as I saw it in one of the ctypes
samples.
Anyhow, I tried...
myApp = cdll.LoadLibrary("C:\\myapp.dll")
myApp.AddNumbers(1, 4)
..I get an error...
AttributeError: function 'AddNumbers' not found
...myapp certainly has AddNumbers.
Grant Edwards wrote:
> On 2005-10-04, Java and Swing <[EMAIL PROTECTED]> wrote:
> > ok i got ctypes...now i try
> >
> >>> from ctypes import *
> >>> myApp = CDLL("C:\\myapp.dll")
>
> I've never seen that sort of usage before. I don't know what
> CDLL does, and I can't find it in the docs anywhere.
>
> Based on my reading of the tutorial, I would have tried eitehr
>
> myApp = cdll.myapp
> or
> myApp = cdll.LoadLibrary("C:/myapp.dll")
>
> > ..now how can I call functions on in myapp.dll? From the
> > tutorial I am not sure..
>
> Assuming CDLL did something equivalent to cdll.LoadLibrary(),
> I'd try:
>
>myApp.FuncName()
>
> I've always done it the way it's done in the tutorial:
>
> mylib = windll.Lib_Name
> mylib.myFuncName()
>
> > i try, dir(cdll.myApp) and dir(myApp)..but don't see my
> > functions listed.
>
> I don't think dir() works on dll's like that. I certainly
> don't see it mentioned in the tutorial. What happened when you
> tried calling the function the way the tutorial does?
>
> myapp = cdll.myapp
> myapp.MyFunc()
>
> --
> Grant Edwards grante Yow! Yow! Is my fallout
> at shelter termite proof?
>visi.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
Here's the Script it was being used in (forgive it if it seems a bit
messy, i have been tinkering with variables and such to try different
ideas and haven't really cleaned it up).
import ctest
import Tkinter
import threading
hue_map =
("#FF","#FEFEFF","#FDFDFF","#FCFCFF","#FBFBFF","#FAFAFF","#F9F9FF","#F8F8F8","#F7F7FF","#F6F6F6","#FF","#FF","#FF","#FF","#FF","#FF","#FF",\
"#FF","#FF","#FF","#FF","#FF","#FF","#FF","#FF")
class Mandelbrot_Set(Tkinter.Canvas):
def __init__(self,master,iters):
Tkinter.Canvas.__init__(self,master)
self.dims = {'x':500,'y':500}
self.config(height=self.dims['y'],width=self.dims['x'])
self.r_range = (-2.0,2.0)
self.i_range = (-2.0,2.0)
self.iters = iters
self.prec =
{'r':1.*(self.r_range[1]-self.r_range[0])/(self.dims['x']),'i':1.*(self.i_range[1]-self.i_range[0])/self.dims['y']}
self.escapemap
=
ctest.escapeMap(-1j,self.iters,(self.dims['x'],self.dims['y']),(self.r_range[0],self.r_range[1]),(self.i_range[0],self.i_range[1]))
self.select = False
self.select_event = (0,0)
self.sbox = None
self.bind("",self.selection_box)
self.bind("",self.select_update)
self.t_draw = threading.Thread(target=self.draw)
self.t_draw.start()
def draw(self):
for j in range(self.dims['y']):
i = 0
while i < self.dims['x']:
cur = 0;
try:
color = self.escapemap[j][i]
while self.escapemap[j][i+cur] == color:
cur+=1
except IndexError:
break;
hue_step = 1.*len(hue_map)/self.iters
if color == -1: f = "#00"
else: f = hue_map[int(hue_step*color)]
self.create_line(i,j,i+cur,j,fill=f)
i+=cur
def selection_box(self,event):
if not self.select:
self.select_event = (event.x,event.y)
self.select = True
else:
self.r_range = self.new_range(event.x,self.select_event[0])
self.i_range = self.new_range(event.y,self.select_event[1])
print self.r_range,self.i_range
self.select = False
self.delete(Tkinter.ALL)
self.t_draw.run()
self.select_update(event)
def new_range(self,x,y):
if x > y:
return (y,x)
else:
return (x,y)
def select_update(self,event):
if not self.select:
return
else:
if self.sbox != None:
self.delete(self.sbox)
self.sbox =
self.create_rectangle(self.select_event[0],self.select_event[1],event.x,event.y,fill=None,outline="#00")
else:
self.sbox =
self.create_rectangle(self.select_event[0],self.select_event[1],event.x,event.y,fill=None,outline="#00")
if __name__ == "__main__":
root = Tkinter.Tk()
c = Mandelbrot_Set(root,50)
c.pack()
root.mainloop()
The error occurs in the instantiation of the Mandelbrot_Set object.
Additionally in little mini timing scripts such as
import time
import ctest
t = time.time()
c = ctest.escapeMap(-1j,100,(500,500))
print time.time()-t
this will crash it too
however I found that just opening up the interpreter and typing
import ctest
ctest.escapeMap(-1j,100,(50,50)) #50 yields much
smaller output than 500x500
it generates a 2d tuple fine. So the error seems really obscure to me,
and I don't understand it.
Brandon Keown wrote:
I have programmed a fractal generator (Julia Set/Mandelbrot Set) in
python in the past, and have had good success, but it would run so
slowly because of the overhead involved with the calculation. I
recently purchased VS .NET 2003 (Win XP, precomp binary of python
2.4.2rc1) to make my own extensions. I was wondering if anyone could
help me figure out why I'm getting obscure memory exceptions (runtime
errors resulting in automatic closing of Python) with my extension. It
seems to run okay if imported alone, but when accompanied in a list of
instructions such as a function it crashes.
a short script or interpreter session that illustrates how to get the errors
would help.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Build spoofed IP packets
> Yes, give us the error. And know that you can't build raw IP packets > unless you're root. > > Sybren Sorry. I forgot to paste the error: Traceback (most recent call last): File "C:\test\client.py", line 156, in ? send_pkt() File "C:\test\client.py", line 96, in send_pkt s.sendto(ip.get_packet(), (dst, 0)) # send packet to server socket.error: (10004, 'Interrupted system call') Note: this only happens on Windows XP prof SP2. On Linux I got no problems. I run the program as Administrator. -- http://mail.python.org/mailman/listinfo/python-list
How to prevent logging warning?
I'm about to add some logging calls to a library I have. How can I prevent that the script that uses the library prints 'No handlers could be found for logger "comtypes.client"' when the script runs? I would like to setup the logging so that there is no logging when nothing is configured, and no warning messages are printed. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, Mysql, insert NULL
Python_it wrote:
> I know how to insert values in a database.
> That's not my problem!
> My problem is how i insert NULL values in de mysql-database.
> None is een object in Python and NULL not.
> None is not converted to NULL?
> Table shows None and not NULL!
As Laszlo wrote, "None will be converted to NULL" for the Python => SQL
direction. And also, NULL will be converted to None for SQL => Python
direction.
And to avoid unneccessary if-then-else you should follow his advice and
use parametrized queries. I. e.
cursor's execute method has two parameteres:
1) SQL query with placeholders
2) parameters
For example:
var1 = "Joe's dog"
cur.execute("insert into mytable(col1) values (%s)", (var1,))
var1 = None
cur.execute("insert into mytable(col1) values (%s)", (var1,))
if you use MySQLdb (the most sensible choice for a MySQL Python database
adapter).
Because MySQLdb uses the pyformat param style, you use the %s
placeholder always, no matter which type your parameter will be.
Also, the tip to read the DB-API specification
http://www.python.org/peps/pep-0249.html is a good one in my opinion.
It really pays off to learn how to do things the DB-API way.
HTH,
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python, Mysql, insert NULL
Python_it wrote:
> I know how to insert values in a database.
> That's not my problem!
> My problem is how i insert NULL values in de mysql-database.
So you *don't* know how to insert values in a database: as Laszlo wrote,
you might be best using parameterized queries.
> None is een object in Python and NULL not.
> None is not converted to NULL?
> Table shows None and not NULL!
>
If that's the case then perhaps the field isn't nullable? Or perhaps you
mader a mistake ...
Pay careful attention to the difference between
curs.execute(sql, data)
and
curs.execute(sql % data)
Let's suppose I create a MySQL table:
mysql> create table t1(
-> f1 varchar(10) primary key,
-> f2 varchar(20)
-> );
Query OK, 0 rows affected (0.44 sec)
Let's try and create a few records in Python:
>>> conn = db.connect("localhost", db="temp", user="root")
>>> curs = conn.cursor()
There's the obvious way:
>>> curs.execute("INSERT INTO t1 (f1, f2) VALUES ('row1', NULL)")
1L
Then there's the parameterised way:
>>> curs.execute("INSERT INTO t1 (f1, f2) VALUES (%s, %s)", ("row2", None))
1L
This is to be preferred because the data tuple can contain general
expressions, so you just have to ensure that the name bound to the
column value contains None rather than some string.
Then there's the wrong way"
>>> curs.execute("INSERT INTO t1 (f1, f2) VALUES ('%s', '%s')" %
("row3", None))
1L
>>>
This really executes
INSERT INTO t1 (f1, f2) VALUES ('row3', 'None')
What does MySQL have to say about all this?
mysql> select * from t1;
+--+--+
| f1 | f2 |
+--+--+
| row1 | NULL |
| row2 | NULL |
| row3 | None |
+--+--+
3 rows in set (0.00 sec)
And the moral of the story is to believe someone is actually trying to
help you unless you have definite evidence to the contrary. Otherwise
people will pretty soon stop trying to help you ...
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: Python, Mysql, insert NULL
Python_it wrote:
> I know how to insert values in a database.
> That's not my problem!
> My problem is how i insert NULL values in de mysql-database.
> None is een object in Python and NULL not.
> None is not converted to NULL?
> Table shows None and not NULL!
None is converted to mysql's NULL and vice versa. It sounds
you are passing the *string* "None" to mysql, with it isn't
the same thing.
Adapting the Laszlo's example already posted:
cursor.execute("insert into tablename(fieldname) values (%s)", [None])
HTH.
--
deelan, #1 fan of adriana lima!
--
http://mail.python.org/mailman/listinfo/python-list
Re: Confused with module and .py files
On Wed, 05 Oct 2005 13:46:30 +0530, Iyer, Prasad C wrote: > > Actually I am bit confused between the modules and .py file > How do I differentiate between the 2. > > For example > I have a file import1.py, import2.py file > > Which has few functions and classes > And if I have a class with same name "BaseClass" in both the file > > How would I use it if I declare it as given below in my 3rd class > > from import1.py import * > from import2.py import * You can't, because the BaseClass from the second import over-writes the BaseClass from the first. In general, "from module import *" is a bad idea, because you don't know what names you are importing: you can have name collisions, where a name in one module clashes with a name in your code, or another module. That is what is happening with your code. The way to prevent that is to use Python's namespaces: instead of "from module import name", use "import module", and then call module.name. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
On Wed, 05 Oct 2005 03:39:30 -0700, beza1e1 wrote: > Coming back from a bug hunt, i am not sure what to think of this python > behaviour. [snip code] > The point seems to be, that lst=[] creates a class attribute (correct > name?), which is shared by all instances of A. So a.lst ist the same > object as b.lst, despite the fact, that object a is different to object > b. Not a bug, but not really a feature as such, it is a side-effect of the way Python works. I guess that makes it a gotcha. Argument defaults are set at compile time. You set the argument default to a mutable object, an empty list. Every time you call the function, you are appending to the same list. This is not a problem if your argument default is a string, or a number, or None, since these are all immutable objects that can't be changed. I suppose someone might be able to come up with code that deliberately uses this feature for good use, but in general it is something you want to avoid. Instead of: def spam(obj, L=[]): L.append(obj) do this: def spam(obj, L=None): if L is None: L = [] L.append(obj) -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
Fredrik Lundh wrote: > it's also mentioned in chapter 4 of the tutorial: > > http://docs.python.org/tut/node6.html#SECTION00671 > > "*Important warning*: The default value is evaluated only once. This > makes a difference when the default is a mutable object such as a list, > dictionary, or instances of most classes. " Perhaps it would be a good idea if Python actually raised a warning (SyntaxWarning?) if you use an unnamed list or dict as a default argument. This would doubtless help quite a few beginners. And for people who really do want that behaviour, working around the warning should involve minimal extra code, with extra clarity thrown in for free. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Brian Quinlan <[EMAIL PROTECTED]> writes:
> Aren't you looking for some of compile-time checking that ensures that
> only declared variables are actually used? If so, how does global help?
You'd have to declare any variable global, or declare it local, or it
could be a function name (defined with def) or a function arg (in the
function scope), or maybe you could also declare things like loop
indices. If it wasn't one of the above, the compiler would flag it.
> >>Your making this feature "optional" contradicts the subject of this
> >> thread i.e. declarations being necessary.
> > They're necessary if you enable the option.
>
> OK. Would it work on a per-module basis or globally?
Whatever perl does. I think that means per-module where the option is
given as "use strict" inside the module.
> > def do_add(x->str, y->str):
> > return '%s://%s' % (x, y)
> > def do_something(node->Node):
> > if node.namespace == XML_NAMESPACE:
> > return do_add('http://', node.namespace)
> > elif node.namespace == ...
>
> Wouldn't an error be generated because XML_NAMESPACE is not declared?
XML_NAMESPACE would be declared in the xml.dom module and the type
info would carry over through the import.
> And I notice that you are not doing any checking that "namespace" is a
> valid attribute of the node object. Aren't the typos class of error
> that you are looking to catch just as likely to occur for attributes
> as variables?
The node object is declared to be a Node instance and if the Node
class definition declares a fixed list of slots, then the compiler
would know the slot names and check them. If the Node class doesn't
declare fixed slots, then they're dynamic and are looked up at runtime
in the usual way.
--
http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Paul Rubin wrote:
> You'd have to declare any variable global, or declare it local, or it
> could be a function name (defined with def) or a function arg (in the
> function scope), or maybe you could also declare things like loop
> indices. If it wasn't one of the above, the compiler would flag it.
OK. The Python compiler would check that the name is declared but it
would not check that it is defined before use? So this would be acceptable:
def foo():
local x
return x
>>OK. Would it work on a per-module basis or globally?
>
> Whatever perl does. I think that means per-module where the option is
> given as "use strict" inside the module.
>>>def do_add(x->str, y->str):
>>> return '%s://%s' % (x, y)
>>>def do_something(node->Node):
>>> if node.namespace == XML_NAMESPACE:
>>> return do_add('http://', node.namespace)
>>> elif node.namespace == ...
>>
>>Wouldn't an error be generated because XML_NAMESPACE is not declared?
>
>
> XML_NAMESPACE would be declared in the xml.dom module and the type
> info would carry over through the import.
Problems:
1. your type checking system is optional and xml.dom does not use it
1a. even if xml.dom did declare the type, what if the type were declared
conditionally e.g.
try:
unicode
except NameError:
XML_NAMESPACE = "..."
else:
XML_NAMESPACE = u"..."
2. the compiler does not have access to the names in other modules
anyway
>>And I notice that you are not doing any checking that "namespace" is a
>>valid attribute of the node object. Aren't the typos class of error
>>that you are looking to catch just as likely to occur for attributes
>>as variables?
>
>
> The node object is declared to be a Node instance and if the Node
> class definition declares a fixed list of slots, then the compiler
> would know the slot names and check them.
How would you find the class definition for the Node object at
compile-time? And by "slots" do you mean the existing Python slots
concept or something new?
> If the Node class doesn't
> declare fixed slots, then they're dynamic and are looked up at runtime
> in the usual way.
So only pre-defined slotted attributes would be accessable (if the
object uses slots). So the following would not work:
foo = Foo() # slots defined
foo.my_attribute = 'bar'
print foo.my_attribute
Cheers,
Brian
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
On Tue, 04 Oct 2005 19:13:10 +0300, Maksim Kasimov wrote: > my programm sometime gives "Segmentation fault" message (no matter how > long the programm had run (1 day or 2 weeks). And there is nothing in > log-files that can points the problem. My question is how it possible to > find out where is the problem in the code? Thanks for any help. > > Python 2.2.3 > FreeBSD you could start your program within a gdb session like so: $ gdb python GNU gdb 6.1.1 [FreeBSD] Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-marcel-freebsd"...(no debugging symbols found)... (gdb) r foo.py Starting program: /usr/bin/python foo.py ... once your progmam segfaults you can then inspect the stack through: (gdb) bt cheers, tamer. -- hardware, n: The parts of a computer system that can be kicked. -- http://mail.python.org/mailman/listinfo/python-list
Re: "no variable or argument declarations are necessary."
Paul Rubin wrote: > So where are the complex templates and dangerous void pointers in ML? You're right about that of course. There aren't any templates or pointers in COBOL either as far as I know, and COBOL has been used for lots of real world code (which ML hasn't). I don't know what your point is though. Sure, Python could have Perl-like declarations, where you just state that you intend to use a particular name, but don't declare its type. I don't see any harm in that. Type declarations or inferred types would, on the other hand, make Python considerably less dynamic, and would probably bring the need of additional featurs such as function overloading etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Call C functions from Python
Java and Swing wrote:
>I used, myApp = CDLL("C:...") ...as I saw it in one of the ctypes
> samples.
>
> Anyhow, I tried...
>
> myApp = cdll.LoadLibrary("C:\\myapp.dll")
> myApp.AddNumbers(1, 4)
>
> ..I get an error...
>
> AttributeError: function 'AddNumbers' not found
>
> ...myapp certainly has AddNumbers.
properly exported? what does
dumpbin /exports myapp.pyd
say?
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to debug when "Segmentation fault"
On Wed, 05 Oct 2005 14:53:45 +0200, Tamer Fahmy
<[EMAIL PROTECTED]> wrote:
>On Tue, 04 Oct 2005 19:13:10 +0300, Maksim Kasimov wrote:
>> my programm sometime gives "Segmentation fault" message (no matter how
>> long the programm had run (1 day or 2 weeks). And there is nothing in
>> log-files that can points the problem. My question is how it possible to
>> find out where is the problem in the code? Thanks for any help.
>>
>> Python 2.2.3
>> FreeBSD
>
>you could start your program within a gdb session like so:
>
>$ gdb python
>GNU gdb 6.1.1 [FreeBSD]
>Copyright 2004 Free Software Foundation, Inc. GDB is free software,
>covered by the GNU General Public License, and you are welcome to change
>it and/or distribute copies of it under certain conditions. Type "show
>copying" to see the conditions. There is absolutely no warranty for GDB.
>Type "show warranty" for details. This GDB was configured as
>"i386-marcel-freebsd"...(no debugging symbols found)...
>(gdb) r foo.py
>Starting program: /usr/bin/python foo.py ...
>
>once your progmam segfaults you can then inspect the stack through:
>
>(gdb) bt
>
>cheers,
> tamer.
Tamer, thanks for your tip.
I tried Jeff's code:
import marshal
f = lambda: None
code =
marshal.loads(marshal.dumps(f.func_code).replace('d\0\0S','d\xff\xffS'))
f.func_code = code
f()
saved it as foo.py, than
C:\Python24\Lib>gdb python
GNU gdb 5.1.1 (mingw experimental)
Copyright 2002 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you
are
welcome to change it and/or distribute copies of it under certain
conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for
details.
This GDB was configured as "mingw32"...(no debugging symbols found)...
(gdb) r foo.py
Starting program: C:\Python24/python.exe foo.py
Program received signal SIGSEGV, Segmentation fault.
0x1e027b23 in ?? ()
(gdb) bt
#0 0x1e027b23 in ?? ()
#1 0x00977240 in ?? ()
#2 0x1e1a82b8 in ?? ()
Cannot access memory at address 0x7
(gdb)
How can I interpret this results? ;)
Am I right, that I need a debug build of python built with mingw or
cygwin in Windows?
--
Franz Steinhaeusler
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent logging warning?
may be this you will find usefull:
def getLog(logName, fileName = None):
if fileName:
hdl = logging.FileHandler(fileName)
else:
hdl = logging.StreamHandler()
fmt =
logging.Formatter("%(name)s:\t%(levelname)s:\t%(asctime)s:\t%(message)s")
hdl.setFormatter(fmt)
log = logging.getLogger(logName)
log.addHandler(hdl)
return log
Thomas Heller wrote:
> I'm about to add some logging calls to a library I have. How can I
> prevent that the script that uses the library prints
> 'No handlers could be found for logger "comtypes.client"' when the
> script runs?
>
> I would like to setup the logging so that there is no logging when
> nothing is configured, and no warning messages are printed.
>
> Thomas
--
Best regards,
Maksim Kasimov
mailto: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
10060, Operation timed out Error
Hi,
I am trying to upload zip files using ftplib module. The server has
Vsftpd 2.0.3 installed on it.
I was able to succesfully upload files using ftplib and Vsftpd on the
server locally connected.
Now, I want to transfer files to remote server using the same script.
I am getting the following error:
Traceback (most recent call last):
File "", line 1, in -toplevel-
ftp.retrlines('LIST')
File "C:\Python23\lib\ftplib.py", line 396, in retrlines
conn = self.transfercmd(cmd)
File "C:\Python23\lib\ftplib.py", line 345, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "C:\Python23\lib\ftplib.py", line 324, in ntransfercmd
conn.connect(sa)
File "", line 1, in connect
error: (10060, 'Operation timed out')
If I transfer the files without using python script from the prompt, the
file is successfully transfered.
Please help me to understand whether the problem is with the script,
ftplib or Vsftpd.
Thanks in advance.
Ajay
--
http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
beza1e1:
> Coming back from a bug hunt, i am not sure what to think of this python
> behaviour. Here is a demo program:
>
> class A:
>def __init__(self, lst=[]):
> self.lst = lst
>
> a = A()
> b = A()
> b.lst.append("hallo")
> print a.lst # output: ["hallo"]
>
> The point seems to be, that lst=[] creates a class attribute (correct
> name?), which is shared by all instances of A. So a.lst ist the same
> object as b.lst, despite the fact, that object a is different to object
> b.
>
Fredrik Lundh wrote:
> Steve Holden wrote:
>
>
>>Interestingly I couldn't find this in the FAQ, though it *is* a
>>frequently-asked question [note: my not finding it doesn't guarantee
>>it's not there].
>
>
> it's there:
>
>
> http://www.python.org/doc/faq/general.html#why-are-default-values-shared-between-objects
>
> (maybe "default values" should be changed to "default argument values")
>
I couldn't believe it wasn't, but you're right: it should be easier to
find, and a change of wording may do 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: While and If messing up my program?
On Wed, 05 Oct 2005 06:48:59 +, CJ wrote:
>
>Hey, I'm new to the Python world, but I do have experience in several
> other languages. I've been running through a tutorial, and I decided that
> I'd make a program that runs through a list, finds if there are any
> duplicates. The program, doesn't work, but since its a first build I
> wasn't too worried about it. I'd be highly impressed if I got the program
> to run correctly in the first build, I want to debug it myself later.
>
>What does worry me, is that I can't seem to get the program by a
> certain spot. It keeps giving me the same error, and I don't know why.
Here are some techniques for tracking down this sort of bug. The best
thing is, these techniques will help you write better code in the first
place, as well as easier to debug.
Firstly, encapsulate your code. Instead of writing one big lump of code,
break it into small digestible functions.
def run_test():
choice=raw_input("Begin? ")
return choice == "yes" or choice == "y"
# or better still:
# choice.lower() in ("yes", "y", "begin"):
def do_test(ttllst):
# initialise variables
cnto=0
cntt=1
rept=-1
# loop through the list, counting duplicates
while cnto<>len(ttllst)+1:
print "debugging...", cnto, cntt
if ttllst[cnto]==ttllst[cntt]:
rept=rept+1
if cntt==len(ttllst):
print ttllst[cnto],"appears in the list",rept,"times."
cntt=-1
cnto=cnto+1
rept=-1
cntt=cntt+1
print "done."
def main():
if run_test():
ttllst=[4,3,45,3]
do_test(ttllst)
if __name__ == "__main__":
# only happens when *running* the file,
# not when *importing* it
main()
Now you have separated your user interface from the business end of your
code, and you can isolate more simply where the error lies.
Continue to encapsulate your code: the while loop is a good candidate. It
runs through the list comparing each character to one known character. So
I would change do_test to look like this:
def do_test(L):
"""Run our item-counting test on list L."""
# loop through the list, counting duplicates
for index in range(len(L)):
current_item = L[index]
item_count = item_counter(L, current_item)
print current_item, "appears in the list", item_count, "times."
# or better still
# print "%s appears in the list %d times." % (current_item,item_count)
print "done"
def item_counter(L, obj):
"""Return the number of times obj is in list L."""
counter = 0
for item in L:
if item == obj:
counter = counter + 1
return counter
Now that you (hopefully) have bug-free code, you can continue to improve
and optimize your program. For example, instead of creating your own
item_counter function, you will soon learn that Python lists have their
own much quicker version.
In general, you want to make your code as general as practical, without
being too specific. You started with the problem "How can I count the
number of times each item in list ttllst exists in ttllst?" A more general
question is "How do I count the number of items *any* object exists in
*any* list?", and then use that code to answer your first question.
Hope this helps,
--
Steven.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Help with chaos math extensions.
Brandon K" wrote:
> Here's the Script it was being used in (forgive it if it seems a bit
> messy, i have been tinkering with variables and such to try different
> ideas and haven't really cleaned it up).
the C compiler does in fact provide you with some clues:
c:\test\c_lib.cpp(22) : warning C4700: local variable 'c' used without having
been initialized
here's the culprit:
Py_complex *c;
Complex* cplx;
if(!PyArg_ParseTuple(args,"D",c)) return NULL;
PyArg_ParseTuple expects a pointer to a Py_complex object, but you're
passing in an initialized pointer. this works better:
Py_complex c;
Complex* cplx;
if(!PyArg_ParseTuple(args,"D",&c))
return NULL;
cplx = new Complex(&c);
return Py_BuildValue("D",cplx->toOld());
here's the next warning:
c:\test\complex.cpp(50) : warning C4700: local variable 'c' used without having
been initialized
this is your toOld function, which has a similar problem:
Py_complex* Complex::toOld(void)
{
Py_complex* c;
c->real = this->real;
c->imag = this->imag;
return c;
}
since c isn't initialized, you'll overwrite some random memory locations when
you assign things to it. here's a brute-force hack:
Py_complex* Complex::toOld(void)
{
static Py_complex c;
c.real = this->real;
c.imag = this->imag;
return &c;
}
here's a better fix:
Py_complex Complex::toOld(void)
{
Py_complex c;
c.real = this->real;
c.imag = this->imag;
return c;
}
which requires you to change
return Py_BuildValue("D",cplx->toOld());
to
return Py_BuildValue("D",&cplx->toOld());
I only got this far before I ran out of time; there might be more bugs in there.
--
http://mail.python.org/mailman/listinfo/python-list
Re: bug or feature?
Ben Sizer wrote: > Fredrik Lundh wrote: > > >>it's also mentioned in chapter 4 of the tutorial: >> >>http://docs.python.org/tut/node6.html#SECTION00671 >> >> "*Important warning*: The default value is evaluated only once. This >>makes a difference when the default is a mutable object such as a list, >>dictionary, or instances of most classes. " > > > Perhaps it would be a good idea if Python actually raised a warning > (SyntaxWarning?) if you use an unnamed list or dict as a default > argument. This would doubtless help quite a few beginners. And for > people who really do want that behaviour, working around the warning > should involve minimal extra code, with extra clarity thrown in for > free. > This would have to be extended to any mutable object. How does the compiler know which objects are mutable? This would not be a good change. 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: how to debug when "Segmentation fault"
[EMAIL PROTECTED] wrote:
> I've rewritten your middle example to be clearer.
> $ python2.4
> Python 2.4.1 (#1, May 16 2005, 15:15:14)
> [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
type("Y", (type,), {"mro": lambda x: [float]})("X", (), {})
on my machines:
>>> type("Y", (type,), {"mro": lambda x: [float]})("X", (), {})
>
>
> and here's another one for you to enjoy:
>
import marshal
f = lambda: None
code =
marshal.loads(marshal.dumps(f.func_code).replace('d\0\0S','d\xff\xffS'))
f.func_code = code
f()
just no any output
>>> dir(code)
['__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__new__', '__reduce__', '__repr__', '__setattr__',
'__str__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename',
'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name',
'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
Python 2.2.3 (#1, Oct 22 2004, 03:10:44)
[GCC 2.95.4 20020320 [FreeBSD]] on freebsd4
--
Best regards,
Maksim Kasimov
mailto: [EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
regarding python and c++ interaction
hi i am new to python.i hav to call function of c++ .so file(shared library)on linux. any how i am not able to do that. i had made one zoo.so file.when i import it this gives the following error... >>> import zoo Traceback (most recent call last): File "", line 1, in ? ImportError: ./zoo.so: undefined symbol: _Znwj can u plz help me in that matter rdgs parul -- http://mail.python.org/mailman/listinfo/python-list
How to get the output from os.system() into a variable?
Hi,
I would like to execute some command in python on the bash, e.g.
os.system('globus-job-run mike4.cct.lsu.edu/jobmanager-pbs -l
/bin/date')
and want the result of the output in a vector, so something like:
result=python_command(' command_on_the_bash ')
Is that possible? And how to do that?
Thanks
Alexander Dietz
--
http://mail.python.org/mailman/listinfo/python-list
Re: How to get the output from os.system() into a variable?
"alexLIGO" <[EMAIL PROTECTED]> writes:
> I would like to execute some command in python on the bash, e.g.
>
> os.system('globus-job-run mike4.cct.lsu.edu/jobmanager-pbs -l
> /bin/date')
>
> and want the result of the output in a vector, so something like:
>
> result=python_command(' command_on_the_bash ')
>
> Is that possible? And how to do that?
Check out the commands module.
http://docs.python.org/lib/module-commands.html
--
Björn Lindström <[EMAIL PROTECTED]>
Student of computational linguistics, Uppsala University, Sweden
--
http://mail.python.org/mailman/listinfo/python-list
