dict.has_key(x) versus 'x in dict'
Hello,
I've always been using the has_key() method to test if a dictionary
contains a certain key. Recently I tried the same using 'in', e.g.
d = { ... }
if k in d:
...
and found that it seems to perform a lot better when lots of key-tests
are to be performed. I also noticed that has_key() is scheduled to be
removed from future (C)Python versions.
Does the 'in' way of testing have an optimized implementation compared
to has_key()? Is that the reason has_key() is being phased out?
Thanks,
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: dict.has_key(x) versus 'x in dict'
Bjoern Schliessmann wrote:
> Peter Otten wrote:
>
>> No, 'k in d' is equivalent to 'd.has_key(k)', only with less
>> (constant) overhead for the function call.
>
> Ah, thx. Thought the "x in d" syntax might search in d.values() too.
I don't think it does
Python 2.4.3 (#1, Nov 19 2006, 13:16:36)
[GCC 3.4.5 (Gentoo 3.4.5-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d={1:'a',2:'b'}
>>> 1 in d
True
>>> 'a' in d
False
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
[EMAIL PROTECTED] wrote: > I will try later with python 2.5 under linux, but as far as I can see, > it's the same problem under my windows python 2.5 > After reading this document : > http://evanjones.ca/memoryallocator/python-memory.pdf > > I think it's because list or dictionnaries are used by the parser, and > python use an internal memory pool (not pymalloc) for them... I tried the f.readlines() approach and with 2.5 on linux the list is freed. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Help a C++ escapee!
Hello, Simon Pickles wrote: > Can someone help me leave the murky c++ world and enter shiny pythonland? Welcome! > I have a problem with importing and global variables, here's my code: > > [...] > > When run, I come unstuck here: > >self.clientSocket, self.clientAddress = network.accept() > > I get a nameError on 'network', yet it is one in the global namespace, > defined in server.py before CServerThread.Listen() is called. That won't work (as you found out :)). You need to make 'network' available within socketManager.py. Each module on its own has a namespace, there isn't such a thing as a global namespace that is accessible from all modules, like you are used to in C or C++. So when you access the variable 'network' in module socketManager it is looked up in that module's namespace. When you read through socketManager.py (without looking at any other code) you will see that 'network' isn't being defined anywhere. I would solve it like this: Pass it as a parameter to CNetworkManager's and CServerThread's constructor and store it as an instance variable, i.e. for CNetworkManager: class CNetworkManager: def __init__(self, network): self.network = network ... and then later pass it again to the thread you're creating. Another way to have something a bit more like a global namespace would be to create a new module, say we name it globals.py. - # globals.py # initially, no network set network = None - Each module that needs access to globals would then import the globals module and access its variables. So, server.py would do import globals globals.network = CNetworkManager() globals.network.Listen() and socketManager.py would do import globals ... self.clientSocket, self.clientAddress = globals.network.accept() (You could also selectively import the network variable of course with "from globals import network"). Hope this helps, Paul -- http://mail.python.org/mailman/listinfo/python-list
Properties on old-style classes actually work?
Hello, The python library docs read in section 2.1 (http://docs.python.org/lib/built-in-funcs.html): " ... property( [fget[, fset[, fdel[, doc) Return a property attribute for new-style classes (classes that derive from object). ... " But in 2.4 at least properties also seem to work for old-style classes: class O: def __init__(self): self._x = 15 def get_x(self): return self._x x = property(get_x) o = O() print o.x outputs "15" as expected for the property. Regards, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to choose between python and java
Anthony Irwin wrote: > Hi All, > > I am currently trying to decide between using python or java and have a > few quick questions about python that you may be able to help with. > > #1 Does python have something like javas .jar packages. A jar file > contains all the program files and you can execute the program with java > -jar program.jar > > I am sort of hoping python has something like this because I feel it > makes it easier to distribute between platforms e.g. linux, mac windows > etc. It depends on what you see as the benefit of jar's. If it is purely a matter of packing your whole application up into a single file that you can distribute then there are a number of tools to do that, each with their limits. Search for cx_freeze or py2exe (win32 only). > #2 What database do people recommend for using with python that is easy > to distribute across linux, mac, windows. You could use sqlite, which comes included with Python 2.5. The database files it creates are cross-platform usable and using sqlite saves you the trouble of having to set up a database server > #4 If I write a program a test it with python-wxgtk2.6 under linux are > the program windows likely to look right under windows and mac? Likely yes, but guaranteed no. You'll simply have to test to see how your program comes out on the other platforms. You could use a GUI toolkit that draws its own widgets instead of one that uses the native controls, like wxPython does. PyGTK comes to mind, not sure if it is available on the Mac. > #5 someone said that they used to use python but stopped because the > language changed or made stuff depreciated (I can fully remember which) > and old code stopped working. Is code written today likely to still work > in 5+ years or do they depreciate stuff and you have to update? The changes I can remember from the last couple of years seem to be mostly addition of new features to the language and more standard modules being included in the standard Python distribution. Of course, some things were deprecated, but I think actual code-breaking changes were not that common. But with Python 3.0 (still a long time to go) there will definitely be some incompatibilities, but a lot can probably be fixed automatically using an included conversion tool. Here's a description of the changes in the last 3 releases (2.5, 2.4, 2.3). These span a bit more than 3 years, as 2.3.0 was released on July 29th, 2003, with 2.5.0 on September 19th, 2006. Perhaps you can get a feel for the kind of changes from one release to the next. http://docs.python.org/whatsnew/whatsnew25.html http://www.python.org/doc/2.4/whatsnew/whatsnew24.html http://www.python.org/doc/2.3/whatsnew/ > Also does anyone else have any useful comments about python vs java > without starting a flame war. I guess it all depends on what you're going to use it for and what your goals and restrictions are. I've never seriously used Java (only a bit of C#), but I've been developing a GUI app with wxPython for the last couple of months and am pretty happy with it. Before that, I did lots of tooling with Python (conversion scripts, small computational stuff, etc) and was happy as well. So overall, I'm happy with Python :) It's pretty powerful for a wide variety of applications, comes with a large collection of modules for everything from networking to file compression to encryption to xml parsing to database handling to ... (see http://docs.python.org/lib/lib.html). I find code in Python to be more easily readable because of the absence of unneeded brackets and the fact that code that forms a block is always aligned properly (eeek, possible flame-war subject here). And it saves on the number of type strokes as well. Overall, great stuff! Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting a quoted string.
Paul Melis wrote:
> Hi,
>
> mosscliffe wrote:
>
>> I am looking for a simple split function to create a list of entries
>> from a string which contains quoted elements. Like in 'google'
>> search.
>>
>> eg string = 'bob john "johnny cash" 234 june'
>>
>> and I want to have a list of ['bob', 'john, 'johnny cash', '234',
>> 'june']
>>
>> I wondered about using the csv routines, but I thought I would ask the
>> experts first.
>>
>> There maybe a simple function, but as yet I have not found it.
>
>
> Here a not-so-simple-function using regular expressions. It repeatedly
> matched two regexps, one that matches any sequence of characters except
> a space and one that matches a double-quoted string. If there are two
> matches the one occurring first in the string is taken and the matching
> part of the string cut off. This is repeated until the whole string is
> matched. If there are two matches at the same point in the string the
> longer of the two matches is taken. (This can't be done with a single
> regexp using the A|B operator, as it uses lazy evaluation. If A matches
> then it is returned even if B would match a longer string).
Here a slightly improved version which is a bit more compact and which
removes the quotes on the matched output quoted string.
import re
def split_string(s):
pat1 = re.compile('[^" ]+')
pat2 = re.compile('"([^"]*)"')
parts = []
m1 = pat1.search(s)
m2 = pat2.search(s)
while m1 or m2:
if m1 and m2:
if m1.start(0) < m2.start(0):
match = 1
elif m2.start(0) < m1.start(0):
match = 2
else:
if len(m1.group(0)) > len(m2.group(0)):
match = 1
else:
match = 2
elif m1:
match = 1
else:
match = 2
if match == 1:
part = m1.group(0)
s = s[m1.end(0):]
else:
part = m2.group(1)
s = s[m2.end(0):]
parts.append(part)
m1 = pat1.search(s)
m2 = pat2.search(s)
return parts
print split_string('bob john "johnny cash" 234 june')
print split_string('"abc""abc"')
--
http://mail.python.org/mailman/listinfo/python-list
Re: Splitting a quoted string.
Hi,
mosscliffe wrote:
> I am looking for a simple split function to create a list of entries
> from a string which contains quoted elements. Like in 'google'
> search.
>
> eg string = 'bob john "johnny cash" 234 june'
>
> and I want to have a list of ['bob', 'john, 'johnny cash', '234',
> 'june']
>
> I wondered about using the csv routines, but I thought I would ask the
> experts first.
>
> There maybe a simple function, but as yet I have not found it.
Here a not-so-simple-function using regular expressions. It repeatedly
matched two regexps, one that matches any sequence of characters except
a space and one that matches a double-quoted string. If there are two
matches the one occurring first in the string is taken and the matching
part of the string cut off. This is repeated until the whole string is
matched. If there are two matches at the same point in the string the
longer of the two matches is taken. (This can't be done with a single
regexp using the A|B operator, as it uses lazy evaluation. If A matches
then it is returned even if B would match a longer string).
import re
def split_string(s):
pat1 = re.compile('[^ ]+')
pat2 = re.compile('"[^"]*"')
parts = []
m1 = pat1.search(s)
m2 = pat2.search(s)
while m1 or m2:
if m1 and m2:
# Both match, take match occurring earliest in the
string
p1 = m1.group(0)
p2 = m2.group(0)
if m1.start(0) < m2.start(0):
part = p1
s = s[m1.end(0):]
elif m2.start(0) < m1.start(0):
part = p2
s = s[m2.end(0):]
else:
# Both match at the same string position, take
longest match
if len(p1) > len(p2):
part = p1
s = s[m1.end(0):]
else:
part = p2
s = s[m2.end(0):]
elif m1:
part = m1.group(0)
s = s[m1.end(0):]
else:
part = m2.group(0)
s = s[m2.end(0):]
parts.append(part)
m1 = pat1.search(s)
m2 = pat2.search(s)
return parts
>>> s = 'bob john "johnny cash" 234 june'
>>> split_string(s)
['bob', 'john', '"johnny cash"', '234', 'june']
>>>
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python memory handling
Hello,
[EMAIL PROTECTED] wrote:
> I've some troubles getting my memory freed by python, how can I force
> it to release the memory ?
> I've tried del and gc.collect() with no success.
[...]
> The same problem here with a simple file.readlines()
> #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared
> import gc #no memory change
> f=open('primary.xml') #no memory change
> data=f.readlines() #meminfo: 12 Mb private, 1.4 Mb shared
> del data #meminfo: 11.5 Mb private, 1.4 Mb shared
> gc.collect() # no memory change
>
> But works great with file.read() :
> #Python interpreter memory usage : 1.1 Mb private, 1.4 Mb shared
> import gc #no memory change
> f=open('primary.xml') #no memory change
> data=f.read() #meminfo: 7.3Mb private, 1.4 Mb shared
> del data #meminfo: 1.1 Mb private, 1.4 Mb shared
> gc.collect() # no memory change
>
> So as I can see, python maintain a memory pool for lists.
> In my first example, if I reparse the xml file, the memory doesn't
> grow very much (0.1 Mb precisely)
> So I think I'm right with the memory pool.
>
> But is there a way to force python to release this memory ?!
This is from the 2.5 series release notes
(http://www.python.org/download/releases/2.5.1/NEWS.txt):
"[...]
- Patch #1123430: Python's small-object allocator now returns an arena to
the system ``free()`` when all memory within an arena becomes unused
again. Prior to Python 2.5, arenas (256KB chunks of memory) were never
freed. Some applications will see a drop in virtual memory size now,
especially long-running applications that, from time to time, temporarily
use a large number of small objects. Note that when Python returns an
arena to the platform C's ``free()``, there's no guarantee that the
platform C library will in turn return that memory to the operating
system.
The effect of the patch is to stop making that impossible, and in
tests it
appears to be effective at least on Microsoft C and gcc-based systems.
Thanks to Evan Jones for hard work and patience.
[...]"
So with 2.4 under linux (as you tested) you will indeed not always get
the used memory back, with respect to lots of small objects being
collected.
The difference therefore (I think) you see between doing an f.read() and
an f.readlines() is that the former reads in the whole file as one large
string object (i.e. not a small object), while the latter returns a list
of lines where each line is a python object.
I wonder how 2.5 would work out on linux in this situation for you.
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 10, 8:23 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > However, it is not true that += "always leads to a rebinding of a to the
> > result of the operation +". The + operator for lists creates a new list.
> > += for lists does an in-place modification:
>
> It still is true.
>
> a += b
>
> rebinds a. Period. Which is the _essential_ thing in my post, because
> this rebinding semantics are what confused the OP.
Doesn't this depend on wether "a" supports __iadd__ or not? Section
3.4.7 of the docs say
"""
If a specific method is not defined, the augmented operation falls
back to the normal methods. For instance, to evaluate the expression x
+=y, where x is an instance of a class that has an __iadd__() method,
x.__iadd__(y) is called. If x is an instance of a class that does not
define a __iadd__() method, x.__add__(y) and y.__radd__(x) are
considered, as with the evaluation of x+y.
"""
So if a.__iadd__ exists, a += b is executed as a.__iadd__(b), in which
case there's no reason to rebind a.
However, this confuses the heck out of me:
>>> class A:
... l = []
...
>>> class B(A): pass
...
>>> B.__dict__
{'__module__': '__main__', '__doc__': None}
>>> B.l
[]
>>> B.l.append('1')
>>> B.l
['1']
>>> B.__dict__
{'__module__': '__main__', '__doc__': None}
>>> B.l.__iadd__('2')
['1', '2']
>>> B.l
['1', '2']
>>> B.__dict__
{'__module__': '__main__', '__doc__': None}
>>> B.l += '3'
>>> B.__dict__
{'__module__': '__main__', '__doc__': None, 'l': ['1', '2', '3']}
Why is B.l set for the += case only? B.l.__iadd__ obviously exists.
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 17, 10:00 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > On Oct 10, 8:23 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > >> rebinds a. Period. Which is the _essential_ thing in my post, because > >> this rebinding semantics are what confused the OP. > > > Doesn't this depend on wether "a" supports __iadd__ or not? Section > > 3.4.7 of the docs say > > > """ > > If a specific method is not defined, the augmented operation falls > > back to the normal methods. For instance, to evaluate the expression x > > +=y, where x is an instance of a class that has an __iadd__() method, > > x.__iadd__(y) is called. If x is an instance of a class that does not > > define a __iadd__() method, x.__add__(y) and y.__radd__(x) are > > considered, as with the evaluation of x+y. > > """ > > > So if a.__iadd__ exists, a += b is executed as a.__iadd__(b), in which > > case there's no reason to rebind a. > > You misunderstand the documentation, what you quoted doesn't say that > the assignment is suppressed. If a.__iadd__ exists, a += b is executed > as a = a.__iadd__(b) > > The options for a+=b are: > >a = a.__iadd__(b) >a = a.__add__(b) >a = b.__radd__(a) > > but the assignment always happens, it is only what gets executed for the > right hand side which varies. Curious, do you have the relevant section in the docs that describes this behaviour? Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 17, 11:08 am, Duncan Booth <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Curious, do you have the relevant section in the docs that describes > > this behaviour? > > Yes, but mostly by implication. In section 3.4.7 of the docs, the sentence > before the one you quoted says: > > These methods should attempt to do the operation in-place (modifying > self) and return the result (which could be, but does not have to be, > self). > > The 'does not have to be self' tells you that the result of __iadd__ is > used, i.e there is still an assignment going on. > > Just read all of that paragraph carefully. It says that if there is no > __iadd__ method it considers calling __add__/__radd__. Nowhere does it say > that it handles the result of calling the methods differently. Right, the paragraph is actually pretty clear after a second reading. I find it surprising nonetheless, as it's easy to forget to return a result when you're implementing a method that does an in-place operation, like __iadd__: >>> class C: ... def __init__(self, v): ... self.v = v ... def __iadd__(self, other): ... self.v += other ... >>> c=C(1) >>> c.v 1 >>> c += 3 >>> c >>> c is None True Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 17, 2:39 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > > > Simply not to introduce special cases I guess. If you write ``x.a += > > b`` then `x.a` will be rebound whether an `a.__iadd__()` exists or > > not. Otherwise one would get interesting subtle differences with > > properties for example. If `x.a` is a property that checks if the > > value satisfies some constraints ``x.a += b`` would trigger the set > > method only if there is no `__iadd__()` involved if there's no > > rebinding. > > Unfortunately that doesn't work very well. If the validation rejects the > new value the original is still modified: > > >>> class C(object): > > def setx(self, value): > if len(value)>2: > raise ValueError > self._x = value > def getx(self): > return self._x > x = property(getx, setx) > > >>> o = C() > >>> o.x = [] > >>> o.x += ['a'] > >>> o.x += ['b'] > >>> o.x += ['c'] > > Traceback (most recent call last): > File "", line 1, in > o.x += ['c'] > File "", line 4, in setx > raise ValueError > ValueError > > >>> o.x > ['a', 'b', 'c'] Now that's really interesting. I added a print "before" and print "after" statement just before and after the self._x = value and these *do not get called* after the exception is raised when the third element is added. -- http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 17, 3:20 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > On Wed, 17 Oct 2007 05:57:50 -0700, Paul Melis wrote: > > On Oct 17, 2:39 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > >> >>> class C(object): > > >> def setx(self, value): > >> if len(value)>2: > >> raise ValueError > >> self._x = value > >> def getx(self): > >> return self._x > >> x = property(getx, setx) > > >> >>> o = C() > >> >>> o.x = [] > >> >>> o.x += ['a'] > >> >>> o.x += ['b'] > >> >>> o.x += ['c'] > > >> Traceback (most recent call last): > >> File "", line 1, in > >> o.x += ['c'] > >> File "", line 4, in setx > >> raise ValueError > >> ValueError > > >> >>> o.x > >> ['a', 'b', 'c'] > > > Now that's really interesting. I added a print "before" and print > > "after" statement just before and after the self._x = value and these > > *do not get called* after the exception is raised when the third > > element is added. > > Well, of course not. Did you really expect that!? Why? Because o.x *is* updated, i.e. the net result of self._x = value is executed. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Static variable vs Class variable
On Oct 17, 3:41 pm, Paul Melis <[EMAIL PROTECTED]> wrote: > On Oct 17, 3:20 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: > > > > > On Wed, 17 Oct 2007 05:57:50 -0700, Paul Melis wrote: > > > On Oct 17, 2:39 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > > >> >>> class C(object): > > > >> def setx(self, value): > > >> if len(value)>2: > > >> raise ValueError > > >> self._x = value > > >> def getx(self): > > >> return self._x > > >> x = property(getx, setx) > > > >> >>> o = C() > > >> >>> o.x = [] > > >> >>> o.x += ['a'] > > >> >>> o.x += ['b'] > > >> >>> o.x += ['c'] > > > >> Traceback (most recent call last): > > >> File "", line 1, in > > >> o.x += ['c'] > > >> File "", line 4, in setx > > >> raise ValueError > > >> ValueError > > > >> >>> o.x > > >> ['a', 'b', 'c'] > > > > Now that's really interesting. I added a print "before" and print > > > "after" statement just before and after the self._x = value and these > > > *do not get called* after the exception is raised when the third > > > element is added. > > > Well, of course not. Did you really expect that!? Why? > > Because o.x *is* updated, i.e. the net result of self._x = value is > executed. Argh, the getter is of course used to append the third element, after which the rebinding triggers the exception. Got it now... Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Backslash frowned upon?
[EMAIL PROTECTED] wrote: Why is the \ backslash character frowned upon? Can I still use it in Python 3.0 to achieve the same thing it was designed to do? Yes, it's still valid to use in a script. See http://docs.python.org/dev/3.0/whatsnew/3.0.html for the big changes coming with 3.0 Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Shed my a light :)
TheSaint wrote:
On 19:06, lunedì 02 giugno 2008 Chris wrote:
actions= ('print', 'sum', 'divide', 'myfunction')
parameters=(5, 'nothing',5.63, object)
8< 8<
getattr(...)
getattr(object, name[, default]) -> value
8< 8<
for nn in actions:
func = getattr(cp, nn)
if callable(func):
func(parameters)
I got the point of Duncan and I should remain on evail() because the
evaluation is made on a construct of string expression, which give me the
final name of the function I want to call.
Why do you still need eval? Can't you just construct the string
describing the function to call and then use getattr() to get the actual
function object to call?
I've tried on Pyshell and clearly said the object str is not callable.
Well no, but I don't think anyone suggested that it would be.
The name of a function to call and the function itself are different
things. getattr() helps you to get from the first to the latter.
Some of those string are functions inside the module, so I was expecting a
sequence of calls according the passed in functions names, but they *must*
be processed as a python statements ;(
This doesn't exactly make sense, as what you want isn't really clear...
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: SWIG (Python) - "no constructor defined" for concrete class
Stodge wrote:
> Yet another SWIG question (YASQ!).
>
> I'm having a problem with using an abstract base class. When
> generating the Python bindings, SWIG thinks that all the concrete
> classes that derive from this abstract class are abstract too and
> won't create the correct constructor.
>
> Abstract class:
>
> [source lang="cpp"]class CORE_API Shape
> {
> public:
> virtual ~Shape()
> {
> nshapes--;
> };
> double x, y;
> virtual void move(double dx, double dy);
> virtual double area(void) = 0;
> virtual double perimeter(void) = 0;
> static int nshapes;
> protected:
> Shape() {
> nshapes++;
> }
>
> };
> [/source]
>
> Derived classes:
>
> [source lang="cpp"]class CORE_API Circle : public Shape
> {
> private:
> double radius;
> public:
> Circle(double r): Shape(), radius(r)
> {
> };
> virtual double area(void);
> virtual double perimeter(void);
> };
>
> class CORE_API Square : public Shape
> {
> private:
> double width;
> public:
> Square(double r): Shape(), width(r)
> {
> };
> virtual double area(void);
> virtual double perimeter(void);
> };
> [/source]
>
> SWIG file:
>
> [source lang="cpp"]class Shape
> {
> virtual void move(double dx, double dy);
> virtual double area(void) = 0;
> virtual double perimeter(void) = 0;
> };
>
> class Circle: public Shape
> {
> Circle(double r);
> virtual double area(void);
> virtual double perimeter(void);
> };
>
>
> class Square: public Shape
> {
> Square(double r);
> virtual double area(void);
> virtual double perimeter(void);
> };
> [/source]
>
> C++ COde:
>
> [source lang="cpp"] Circle c(1.02);
> std::cout << "(c++)\t\tCircle\t" << c.area() << std::endl;
> Square s(9.20);
> std::cout << "(c++)\t\tSquare\t" << s.area() << std::endl;
>
> [/source]
>
> For some reason SWIG thinks that Circle and Square are abstract. Any
> ideas why? I'm rather confused by this.
See section 6.6.2 of the SWIG documentation (SWIG and C++ -> Default
constructors, copy constructors and implicit destructors).
Your abstract base class defines its default constructor in the
protected section. From the docs:
"Default constructors and implicit destructors are not created if any
base class defines a non-public default constructor or destructor."
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Does Python 2.5 include or not include SQLite engine?
Hi, Diez B. Roggisch wrote: Dennis Lee Bieber schrieb: On Mon, 21 Apr 2008 19:05:46 -0400, [EMAIL PROTECTED] declaimed the following in comp.lang.python: I thought one of the major features of Python 2.5 was its embedded SQLite engine. No, just the inclusion of the adapter became standard... The packagers of Windows installers include the SQLite3 DLL as it isn't a commonly available item... But many Linux versions probably include it as an option during the OS install. AFAIK thats wrong. On my ubuntu gutsy for example, I find this: [EMAIL PROTECTED]:~$ find /usr/lib/python2.5/ | grep -i sqlite /usr/lib/python2.5/lib-dynload/_sqlite3.so /usr/lib/python2.5/site-packages/pysqlite-2.3.2.egg-info /usr/lib/python2.5/site-packages/pysqlite2 /usr/lib/python2.5/site-packages/pysqlite2/__init__.py /usr/lib/python2.5/site-packages/pysqlite2/__init__.pyc /usr/lib/python2.5/site-packages/pysqlite2/_sqlite.so /usr/lib/python2.5/site-packages/pysqlite2/dbapi2.py /usr/lib/python2.5/site-packages/pysqlite2/dbapi2.pyc /usr/lib/python2.5/sqlite3 /usr/lib/python2.5/sqlite3/__init__.py ... As you can see, stock 2.5 ships with its OWN version of sqlite, and I additionally installed the pysqlite-wrapper for whatever reason I now can't remember. The _sqlite3.so is only a wrapper around the real sqlite library. Compiling a fresh Python 2.5.2 install here gives: 15:46|[EMAIL PROTECTED]:~/py25/lib/python2.5/lib-dynload> ldd _sqlite3.so linux-gate.so.1 => (0x00748000) libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00111000) libpthread.so.0 => /lib/libpthread.so.0 (0x00631000) libc.so.6 => /lib/libc.so.6 (0x00d1b000) /lib/ld-linux.so.2 (0x00749000) I.e. the _sqlite3 module links against the system-wide installed Sqlite version. Furthermore, checking the Python source distribution will show that there is no included version of the whole Sqlite library, only the wrapper code. How your Linux distribution packages Python w.r.t. the sqlite3 module is different per distro. Regards, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Success stories
azrael wrote: Which big aplications are written in python. I see its development, But i can't come up with a big name. I know that there are a lot of companys using python, but is there anythong big written only in python. I want him to fuck of with his perl once and for all time Not really "big" in terms of lines of code, but definitely well-known and widespread: the official BitTorrent client is written in Python (and has been since the beginning I believe). Regards, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem building python in virtual machine running centos
Paul Boddie wrote: On 25 Apr, 03:05, Alexandre Gillet <[EMAIL PROTECTED]> wrote: I am trying to build python-2.4.5 on Centos 5.1, which is a virtual machine running with xen. I am not able to build python. The compilation crash with the following: gcc -pthread -c -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -o Objects/unicodeobject.o Objects/unicodeobject.c In file included from ./Include/Python.h:76, from Objects/unicodeobject.c:39: ./Include/object.h:228: internal compiler error: Segmentation fault Please submit a full bug report, with preprocessed source if appropriate. See http://bugzilla.redhat.com/bugzilla> for instructions. The bug is not reproducible, so it is likely a hardware or OS problem. Any suggestion of what am I doing wrong? You say that the bug is not reproducible, so that means that you can "The bug is not reproducible, so it is likely a hardware or OS problem." This line is printed by GCC itself, not the OP Paul sometimes compile Python, or does the crash always happen when compiling some file (not necessarily the one mentioned above)? I think I've only ever seen a reproducible gcc crash once, and that had something to do with a C++ source file which I then split into two and was able to compile as these two separate parts. You might want to check the gcc version (gcc -v) and to look at bug fixes in any later versions. Generally, if you get an internal error in gcc, you aren't doing anything wrong yourself. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: SWIG Python undefined reference
Instead of manually trying to get all the options to gcc correct you
might want to look at using distutils for compiling your extension.
See the SWIG documentation, section 30.2.2
(http://www.swig.org/Doc1.3/Python.html#Python_nn6)
Paul
Soren wrote:
Hi,
I went through the SWIG tutorial for the example named "simple".
I managed to get to the first step, creating example_wrap.c using
swig, and doing:
"gcc -fpic -c example_wrap.c -IC:\python24\include " to create
example_wrap.o
But when I needed to compile the library file using:
"gcc -shared example_wrap.o -o examplemodule.so" I received a lot of
undefined reference compiler errors like:
example_wrap.o(.text+0x35a5):example_wrap.c: undefined reference to
`_imp__PyErr
_SetString'
there are many other similar errors all prefaced with _imp__Py, so I
am assuming there is a linker error with the python libraries. I have
adjusted my PATH variable to include all the python directories (libs/
dlls).
Does anyone here have any suggestions?
FILES FROM TUTORIAL:
//example.c
#include
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(
Re: Issue with regular expressions
Julien wrote:
Hi,
I'm fairly new in Python and I haven't used the regular expressions
enough to be able to achieve what I want.
I'd like to select terms in a string, so I can then do a search in my
database.
query = ' " some words" with and "withoutquotes " '
p = re.compile(magic_regular_expression) $ <--- the magic happens
m = p.match(query)
I'd like m.groups() to return:
('some words', 'with', 'and', 'without quotes')
Is that achievable with a single regular expression, and if so, what
would it be?
Here's one way with a single regexp plus an extra filter function.
>>> import re
>>> p = re.compile('("([^"]+)")|([^ \t]+)')
>>> m = p.findall(q)
>>> m
[('" some words"', ' some words', ''), ('', '', 'with'), ('', '',
'and'), ('"withoutquotes "', 'withoutquotes ', '')]
>>> def f(t):
... if t[0] == '':
... return t[2]
... else:
... return t[1]
...
>>> map(f, m)
[' some words', 'with', 'and', 'withoutquotes ']
If you want to strip away the leading/trailing whitespace from the
quoted strings, then change the last return statement to
be "return t[1].strip()".
Paul
--
http://mail.python.org/mailman/listinfo/python-list
Re: Getting started with pyvtk
On 1 mei, 22:54, Peter Pearson <[EMAIL PROTECTED]> wrote: > I'm trying to get started with pyvtk, the Python interface > to the Visualization Toolkit, It looks like you're using this package: http://cens.ioc.ee/projects/pyvtk/ These are not the official Python bindings to VTK, but seem to be an add-on that allow you to manipulate VTK _files_ from Python. The official bindings are included in the VTK distribution and can be enabled at build-time (assuming you build VTK yourself). For a simple example that will open a window and show some 3D object, see for example the example code the vtkConeSource class: http://public.kitware.com/cgi-bin/viewcvs.cgi/*checkout*/Examples/Tutorial/Step1/Python/Cone.py?root=VTK&content-type=text/plain > Simply running "vtk" (apparently 4.0) VTK 4.0 is really really old. Consider switching to 5.0 at least or use the CVS version if you feel adventurous. Hope this helps, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting started with pyvtk
Peter Pearson wrote: On Thu, 01 May 2008 16:45:51 -0500, Robert Kern <[EMAIL PROTECTED]> wrote: pyvtk is not the Python interface to VTK. It is for the creation of VTK files. The vtk(1) command is a Tcl shell with the VTK libraries loaded (I believe). Read the VTK documentation for information on the Tcl interface if you really want to use it. You're right: I don't really want to use it. The Python interface is also included in the VTK sources, although it might not have been built on your machine. You have to enable it when you build VTK itself. The Python interface is essentially the same as the C++ interface. There are Python examples in the VTK source tree. That's the ticket: I don't want to "import pyvtk", I want to "import vtk" and ape /usr/share/vtk/.../*.py. Thanks. I'm not sure you've been helped so far as you seem to already understand about pyvtk not being the official VTK bindings :) So, what would you like to know? Paul -- http://mail.python.org/mailman/listinfo/python-list
PEP 370 question
In (the recently accepted) PEP 370 it says "Current Python versions don't have a unified way to install packages into the home directory of a user (except for Mac Framework builds). Users are either forced to ask the system administrator to install or update a package for them or to use one of the many workarounds like Virtual Python [1], Working Env [2] or Virtual Env [3]. [...] The feature can't be implemented using the environment variable PYTHONPATH. The env var just inserts a new directory to the beginning of sys.path but it doesn't parse the pth files in the directory. A full blown site-packages path is required for several applications and Python eggs." I'm confused. For years I've been installing packages and extension modules locally using distutils's --prefix option, e.g. using python setup.py install --prefix=$HOME/local Together with adding $HOME/local/lib/python2.4/site-package to my PYTHONPATH this works fine, even if there are packages that require a .pth file to work or that use Eggs (like setuptools and pygments). So what limitation does the quoted paragraph in the PEP refer to? Regards, Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: letter frequency counter / your thoughts..
[EMAIL PROTECTED] wrote:
Here is my code for a letter frequency counter. It seems bloated to
me and any suggestions of what would be a better way (keep in my mind
I'm a beginner) would be greatly appreciated..
Not bad for a beginner I think :)
def valsort(x):
res = []
for key, value in x.items():
res.append((value, key))
return res
def mostfreq(strng):
dic = {}
for letter in strng:
if letter not in dic:
dic.setdefault(letter, 1)
else:
dic[letter] += 1
newd = dic.items()
getvals = valsort(newd)
getvals.sort()
length = len(getvals)
return getvals[length - 3 : length]
thanks much!!
Slightly shorter:
def mostfreq(strng):
dic = {}
for letter in strng:
if letter not in dic:
dic[letter] = 0
dic[letter] += 1
# Swap letter, count here as we want to sort on count first
getvals = [(pair[1],pair[0]) for pair in dic.iteritems()]
getvals.sort()
return getvals[-3:]
I'm not sure if you wanted the function mostfreq to return the 3 most
frequent letters of the first 3 letters? It seems to do the latter. The
code above uses the former, i.e. letters with highest frequency.
Paul
--
http://mail.python.org/mailman/listinfo/python-list
