wx.DC problem

2006-04-14 Thread python
I’m trying to create a way to pass the wx.dc object between multiple
object, and its mostly working… I can get two different panels to draw to
the same DC but when I scale the window out… it looks like the 2nd panel
is getting blocked by something, im not sure if its a OnPaint problem or
Maybe something with me hiding the second panel. Please help me out here…
thanks…

Attached is my two python scripts that im using… use the test.py to test
the PaintPanel script..import wx

class PaintPanel(wx.Panel):
def __init__(self, parent, id, sub = 0, *args, **kwds):
wx.Panel.__init__(self, parent, id, *args, **kwds)
self.parent = parent
self.sub =sub
self.items = []

if self.sub:
self.parent.AddItem(self)
self.Hide()
else:
pass
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

def AddItem(self, item):
## Add Item
self.items.append(item)

def RemoveItem(self, item):
## Remove Item
for i in self.items:
if(i == item):
self.items.remove(i)

def RemoveAll(self):
## Remove All Items
self.items.clear()

def OnPaint(self, event):
self.sizeX, self.sizeY  = self.GetSize()
print position is:  + str(self.parent.GetPosition())
print size is:  + str(self.parent.GetSize())

## Setup Double Buffer DC
buffer = wx.EmptyBitmap(self.sizeX, self.sizeY)
memDC = wx.MemoryDC()
memDC.SelectObject(buffer)
dc = wx.PaintDC(self)
self.PrepareDC(dc)

##memDC.SetBackground(wx.Brush(White))
##memDC.Clear()

self.Draw(memDC)

memDC.EndDrawing()

## Copy DC from MemoryDC
dc.Blit(0, 0, self.sizeX, self.sizeY,  memDC, 0, 0, wx.COPY, True)

## Clean Up The DC
##del memDC
##del dc

def Draw(self, dc):
## Draw All Attached Items
for item in self.items:
item.Draw(dc)

def OnEraseBackground(self, event):
pass

class PaintItem:
def __init__(self, parent, id, name = ):
self.parent = parent

self.name = name

self.parent.AddItem(self)
def Draw(self, dc):
self.posX, self.posY  = self.parent.GetPosition()
dc.SetTextForeground(BLUE)
dc.SetFont(wx.Font(50, wx.SWISS, wx.NORMAL, wx.BOLD))
dc.DrawText( self.name, self.posX, self.posY)

if __name__ == __main__:
app = wx.PySimpleApp(0)
frame = wx.Frame(None, -1, size = (50,50))
frame.SetBackgroundColour((0,0,0))

panel = PaintPanel(frame, -1, size = (50,50))
item = PaintItem(panel, -1, name = test1)

app.SetTopWindow(frame)
frame.Show()
app.MainLoop()import wx
import PaintPanel

class TestFrame(wx.Frame):
def __init__(self, *args, **kwds):
kwds[style] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)

self.panel = PaintPanel.PaintPanel(self, -1)
self.subPanel= PaintPanel.PaintPanel(self.panel, -1, sub = 1)

item1 = PaintPanel.PaintItem(self.panel, -1, name = main)
item2 = PaintPanel.PaintItem(self.subPanel, -1, name = sub)

self.__set_properties()
self.__do_layout()

def __set_properties(self):
self.SetTitle(Test)

def __do_layout(self):
sizer = wx.BoxSizer(wx.HORIZONTAL)
grid_sizer = wx.FlexGridSizer(3, 3, 0, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add(self.subPanel, 1, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)
grid_sizer.Add((20, 20), 0, wx.EXPAND, 0)


grid_sizer.Fit(self.panel)
grid_sizer.SetSizeHints(self.panel)
grid_sizer.AddGrowableRow(0)
grid_sizer.AddGrowableRow(1)
grid_sizer.AddGrowableRow(2)
grid_sizer.AddGrowableCol(0)
grid_sizer.AddGrowableCol(1)
grid_sizer.AddGrowableCol(2)

self.panel.SetAutoLayout(True)
self.panel.SetSizer(grid_sizer)
sizer.Add(self.panel, 1, wx.EXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer)
sizer.Fit(self)
sizer.SetSizeHints(self)
self.Layout()


class MyApp(wx.App):
def OnInit(self):
wx.InitAllImageHandlers()
frame = TestFrame(None, -1, )
frame.SetSize((500,200))
self.SetTopWindow(frame)
frame.Show()
return 1

if __name__ == __main__:
app = MyApp(0)

Re: Remove Whitespace

2006-04-14 Thread John Machin
On 14/04/2006 12:51 PM, Felipe Almeida Lessa wrote:
 Em Sex, 2006-04-14 às 12:46 +1000, Steven D'Aprano escreveu:
 Why would you want to call in the heavy sledgehammer of regular
 expressions for cracking this peanut?
 
 And put heavy on that!
 
 $ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
 4 0' 'str.replace( , )'

Oi! The OP mentioned whitespace ...

 10 loops, best of 3: 3.07 usec per loop
 $ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
 4 0' '.join(str.split())'
 10 loops, best of 3: 4.16 usec per loop
 $ python2.4 -mtimeit -s from re import sub; str = 'D c a V e r \ = d w
 o r d : 0 0 0 0 0 6 4 0' 'sub(\\s, , str)'
 1 loops, best of 3: 23.6 usec per loop
 $ calc 23.6 / 3.07
 ~7.68729641693811074919
 
 I couldn't be expressed better:
 
 Some people, when confronted with a problem, think I know, I'll use
 regular expressions. Now they have two problems.
   — Jamie Zawinski, in comp.lang.emacs
 


C:\junkpython -mtimeit -s str = 23 * ' X' str.replace(' ', '')
10 loops, best of 3: 3.65 usec per loop

C:\junkpython -mtimeit -s str = 23 * ' X' str.replace(' ', 
'').replace('\t', '')
10 loops, best of 3: 4.33 usec per loop

C:\junkpython -mtimeit -s str = 23 * ' X'; cmap = ''.join(chr(k) for k 
in range(256)); delchars = ' \t' str.translate(cmap, delchars)
100 loops, best of 3: 0.883 usec per loop

0.883 / 3.65 - 0.242

Some people, in Gadarene flight from regular expressions, don't read far 
enough in the Library Reference Manual :-)
-- 
http://mail.python.org/mailman/listinfo/python-list

A problem with exec statement

2006-04-14 Thread TPJ
I have the following code:

---
def f():

  def g():
a = 'a' # marked line 1
exec 'a = b' in globals(), locals()
print g: a =, a

  a = 'A'   # marked line 2
  exec 'a = B' in globals(), locals()
  print f: a =, a
  g()

f()
---

I don't understand, why its output is:

f: a = A
g: a = a

instead of:

f: a = B
g: a = b

All works as intended, if the marked lines are commented out. I just
don't understand, why. (I suppose I don't understand, how the exec
statement works, or the way Python handles objects, their names and
namespaces...) In my opinion (according to my knowledge about Python),
with or without the marked lines commented, the code should work the
same. Well - I think I have to learn more about Python...

According to my knowledge, the most important are the namespaces: the
local ones, in this case. When Python calls the f function, its
namespace is created. This namespace contains only the g function.
Then the a variable is created (and the a name is added to the f
function namespace).

The next statement is the exec one. Since the statement knows the
local namespace (obtained from the locals() function), it should
replace the value of the a variable in the local namespace with the
value of the new string B. I don't understand, why this is not done.

The situation in the g function is similar, the only difference is
that the local namespace contains the a name, that refers to a
different Python object.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread OKB (not okblacke)
Nicolas Fleury wrote:

  I have no idea of the 
 implementation implications, but it would be nice to have the
 capability to override the namespace type to use something else
 than dict, so that it can be filled with symbols one statement at a
 time. 

I agree.  I have sometimes wanted this ability for classes, so that 
class definitions could map assignments onto class attributes in some 
way besides blindly stuffing into a dict.

-- 
--OKB (not okblacke)
Brendan Barnwell
Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail.
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


[廣告]徵人~兼職工作全職收入(可在家工作)

2006-04-14 Thread
Part-time job Full-time income
美商高科技生化公司加州百大企業來台拓展亞太市場
誠徵兼職人員,每日2~3小時,月入1萬~3萬

http://www.moonnini.com/w/nica/
上面為在家工作系統網站
若對在家工作有興趣者可去索取電子書

--
夫兵者不祥之器物或惡之故有道者不處君子居則貴左用兵則貴右兵者不祥之器非君子
之器不得已而用之恬淡為上勝而不美而美之者是樂殺人夫樂殺人者則不可得志於天下
矣吉事尚左凶事尚右偏將軍居左上將軍居右言以喪禮處之殺人之眾以哀悲泣之戰勝以
喪禮處之道常無名樸雖小天下莫能臣侯王若能守之萬物將自賓天地相合以降甘露民莫
之令而自均始制有名名亦既有夫亦將知止知 220-137-106-136.dynamic.hinet.net海
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: A problem with exec statement

2006-04-14 Thread Peter Otten
TPJ wrote:

 I have the following code:
 
 ---
 def f():
 
   def g():
 a = 'a' # marked line 1
 exec 'a = b' in globals(), locals()
 print g: a =, a
 
   a = 'A'   # marked line 2
   exec 'a = B' in globals(), locals()
   print f: a =, a
   g()
 
 f()
 ---
 
 I don't understand, why its output is:
 
 f: a = A
 g: a = a
 
 instead of:
 
 f: a = B
 g: a = b

Use the exec statement without the in-clause to get the desired effect:

 def f():
... a = a
... exec a = 'B'
... print a
...
 f()
B

Inside a function locals() creates a new dictionary with name/value pairs of
the variables in the local namespace every time you call it. When that
dictionary is modified the local variables are *not* updated accordingly.

 def f():
... a = a
... d = locals()
... exec a = 'B' in globals(), d
... print a, d[a]
...
 f()
a B

By the way, experiments on the module level are likely to confuse because
there locals() returns the same dictionary as globals().

Peter


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A problem with exec statement

2006-04-14 Thread Steve Holden
TPJ wrote:
 I have the following code:
 
 ---
 def f():
 
   def g():
 a = 'a' # marked line 1
 exec 'a = b' in globals(), locals()
 print g: a =, a
 
   a = 'A'   # marked line 2
   exec 'a = B' in globals(), locals()
   print f: a =, a
   g()
 
 f()
 ---
 
 I don't understand, why its output is:
 
 f: a = A
 g: a = a
 
 instead of:
 
 f: a = B
 g: a = b
 
 All works as intended, if the marked lines are commented out. I just
 don't understand, why. (I suppose I don't understand, how the exec
 statement works, or the way Python handles objects, their names and
 namespaces...) In my opinion (according to my knowledge about Python),
 with or without the marked lines commented, the code should work the
 same. Well - I think I have to learn more about Python...
 
That's true of almost everybody reading this list, myself included.

 According to my knowledge, the most important are the namespaces: the
 local ones, in this case. When Python calls the f function, its
 namespace is created. This namespace contains only the g function.
 Then the a variable is created (and the a name is added to the f
 function namespace).
 
That's a pretty good summary. In fact just after the call to f is 
started its namespace doesn't even contain g, that's added by 
executing the def statement that defines g.

The assignment does indeed create the name a in the function's (local) 
namespace.

 The next statement is the exec one. Since the statement knows the
 local namespace (obtained from the locals() function), it should
 replace the value of the a variable in the local namespace with the
 value of the new string B. I don't understand, why this is not done.
 
So when you exec 'a = B' in globals(), locals() you might think you 
were changing the local namespace. In fact you are changing a *copy* of 
the local namespace: if you read the documentation carefully you will 
see under locals() it says Warning: The contents of this dictionary 
should not be modified; changes may not affect the values of local 
variables used by the interpreter.

 The situation in the g function is similar, the only difference is
 that the local namespace contains the a name, that refers to a
 different Python object.
 
The same answer presumably pertains here. If you modify your code to read:

def f():

   def g():
 a = 'a' # marked line 1
 print globals:, globals(), '\nlocals:', locals()
 exec 'a = b' in globals(), locals()
 print globals:, globals(), '\nlocals:', locals()
 print g: a =, a

   a = 'A'   # marked line 2
   print Globals:, globals(), '\nLocals:', locals()
   exec 'a = B' in globals(), locals()
   print Globals:, globals(), '\nLocals:', locals()
   print f: a =, a
   g()

f()

you will see quite clearly that you aren't making the changes you 
anticipate to the local namespace. I hope I have explained why.

One last note. Newcomers to Python often seem fascinated by the ability 
to use exec to achieve namespace indirection. Even allowing for the 
difficulties you've already experienced, it's nearly always better in 
practical cases to use assignment to the keys of a dictionary. Then no 
exec is required, and you have direct control over your own namespace.

regards
  Steve

-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Steven Bethard
Nicolas Fleury wrote:
 Steven Bethard wrote:
 Ok, I finally have a PEP number.  Here's the most updated version of 
 the make statement PEP.  I'll be posting it shortly to python-dev.

 Thanks again for the previous discussion and suggestions!
 
 I find it very interesting.
 
 My only complaint is that it is limited to things that can be described 
 as a namespace, where the order of declaration is lost.  This problem is 
 also true with metaclasses, but it is more acceptable since they are for 
 classes.

Yep, this seems to be the biggest complaint.  I'm waiting for write 
access to the repository, but here's a clip from the upcoming update:

Open Issues
===

...

Should users of the make statement be able to determine in which dict
object the code is executed?  The make statement could look for a
``__make_dict__`` attribute and call it to allow things like::

 make Element html:
 make Element body:
 make Element h1:
 '''First heading text'''
 make Element h1:
 '''Second heading text'''

where a normal dict object would not suffice since order and repeated
names must be allowed.  Assuming that the ``__make_dict__`` attribute
was called to get the dict in which the block should be executed, the
following code should make the above make statements work::

 class Element(object):

 class __make_dict__(dict):
 def __init__(self, *args, **kwargs):
 self._super = super(Element.__make_dict__, self)
 self._super.__init__(*args, **kwargs)
 self.values = []
 def __getitem__(self, name):
 try:
 return self._super.__getitem__(name)
 except KeyError:
 return globals()[name]
 def __setitem__(self, name, value):
 self._super.__setitem__(name, value)
 if not name.startswith('__'):
 self.values.append(value)

 def __new__(cls, name, args, edict):
 result = etree.ElementTree.Element(name)
 result.text = edict.pop('__doc__', None)
 print edict.values
 for element in edict.values:
 result.append(element)
 return result


STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


whitespace again

2006-04-14 Thread david brochu jr
hello again,

still having problemsi have the following in a txt file:


Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\software\compete\dca]UserId=92005851PanelId=mayflowerPanelName=Consumer Input ToolbarCaptureType=dword:0002
CapTypOvr=dword:0001ExePath=C:\\Program Files\\Consumer Input Toolbar\\ConsumerInputToolbar.exeDcaVer=dword:0640DcaUpdateVer=dword:0640
CfgVer=dword:0640RulesVer=dword:0008UaCheck=dword:005aSurvey=dword:0001ErrWaitMin=dword:0001ErrWaitMax=dword:0002
KeepAlive=dword:0001PerfEnabled=dword:PerfPath=http://www.consumerinput.com.edgesuite.net/speedera/10k2.txt

I want to remove the  found at the beginning of each line. When I use:
for line in new_line.readlines():line = re.sub('',,line) print line
I get: 
i n d o w s R e g i s t r y E d i t o r V e r s i o n 5 . 0 0 

H K E Y _ L O C A L _ M A C H I N E \ s o f t w a r e \ c o m p e t e \ d c a ] 
U s e r I d  =  9 2 0 0 5 8 5 1  
P a n e l I d  =  m a y f l o w e r  
P a n e l N a m e  =  C o n s u m e r I n p u t T o o l b a r  
C a p t u r e T y p e  = d w o r d : 0 0 0 0 0 0 0 2 
C a p T y p O v r  = d w o r d : 0 0 0 0 0 0 0 1 
E x e P a t h  =  C : \ \ P r o g r a m F i l e s \ \ C o n s u m e r I n p u t T o o l b a r \ \ C o n s u m e r I n p u t T o o l b a r . e x e  
D c a V e r  = d w o r d : 0 0 0 0 0 6 4 0 
D c a U p d a t e V e r  = d w o r d : 0 0 0 0 0 6 4 0
etc etc...Too much space...how do i get the same output with all the space..this is killing me please help


-- 
http://mail.python.org/mailman/listinfo/python-list

Pattern_Recognition_School+Conf_2006:Deadline

2006-04-14 Thread heather
PATTERN RECOGNITION EVENTS THIS SUMMER, 2006
___
4TH INTERNATIONAL SUMMER SCHOOL ON PATTERN RECOGNITION (ISSPR, 2006), 23-28 
JULY, UK
WWW.PatternRecognitionSchool.com
The 4th International Summer School on Pattern Recognition will be organised at 
the University of Plymouth, UK (23-28 July, 2006). The  school programme is 
listed below. Please pass on this email to your interested colleagues and 
students. This is a  great summer school which I would recommend for everyone 
to attend. 
DEADLINE: Register BEFORE 01 MAY, 2006 through the website to get a discount on 
the fee. More than 100 participants in 2005!

Speakers at the Summer School (ISSPR'2006)
Dr. Sam Roberts Mathworks, UK (Introduction to Matlab)
Prof. Wojtek Krzanowski University of Exeter, UK (Multivariate Statistics: Data 
Description)
Dr. Mike Tipping, Microsoft Research, UK (Bayesian Pattern Recognition: 
Principles and Practice)
Prof. Chris Bishop, Microsoft Research, UK (Latent Variables, Mixture Models 
and EM)
Dr. Richard Everson, University of Exeter, UK (Dimensionality Reduction)
Dr. Peter Tino  University of Birmingham, UK (Probabilistic framework for 
model-based topographic map formation)
Prof. Chris Williams, University of Edinburgh, UK (Neural Networks and Kernel 
Machines) 
Dr. Colin Campbell, University of Bristol, UK (Support Vector Machines and 
Kernel Methods: An Introduction and  Review)
Prof. John Shawe- Taylor, University of Southampton, UK (Kernel Based Methods)
Dr. Steve Gunn, University of Southampton, UK (Matlab for Support Vector 
Machines)
Prof. Mahesan Niranjan, University of Sheffield, UK (Classifier Performance 
Particle Filters for Tracking and  Sequential Problems) 
Dr. Andrew Webb Qinetiq, UK (Decision TreesData Clustering)
Prof. Xin Yao, University of Birmingham, UK (A Gentle Introduction to 
Evolutionary Computation; ATutorial on  Evolutionary Multi-objective 
Optimisation) 
Dr. Richard Deardon, University of Birmingham, UK (Sequential Decision Making; 
Markov Chains Monte Carlo Methods)
Dr. Jeremy Wyatt, University of Birmingham, UK (An Introduction to 
Reinforcement Learning)
Dr. Ludmila Kuncheva, University of Wales, UK   (Classifier Combination)
Prof. Joseph Kittler, University of Surrey, UK  (Feature Selection and 
Extraction)
Prof. Sameer Singh, Loughborough University, UK (Multiresolution Pattern 
Recognition)
Prof. Susan Craw, Robert Gordon University, UK  (Case Based Reasoning)
SUPPORTED BY: Microsoft, Springer, British Computer Society, and Mathworks. 
___
IEEE CVPR CONFERENCE
www.CVPR.org/2006
17-22 June, 2006
___
18th INTERNATIONAL CONFERENCE ON PATTERN RECOGNITION 
www.comp.hkbu.edu.hk/~icpr06
August 20-24, 2006
__
ICIAR CONFERENCE
www.iciar.uwaterloo.ca/iciar06
18-20 September, 2006
__
Please see the event websites to get FULL information.
Compiled by: Dr. Heather McLelland
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Duncan Booth
Steven Bethard wrote:

 Should users of the make statement be able to determine in which dict
 object the code is executed?  The make statement could look for a
 ``__make_dict__`` attribute and call it to allow things like::
 
  make Element html:
  make Element body:
  make Element h1:
  '''First heading text'''
  make Element h1:
  '''Second heading text'''

I'm concerned about the magic implied here for __doc__:

   make Element p:
   '''This is '''
   make Element strong:
  '''not'''
   '''going to work'''


There is another effect which should be considered here. If you allow 
Element to create an object to be used as the namespace, then as well as 
doing special tracking when values are set in the namespace it can also 
pre-seed it with names which magically appear in scope within the make.

e.g.

make Element html:
make Element body:
make Element p:
text('But this ')
make Element strong:
 text('could')
text(' be made to work')

or even:

   make Element p:
text('This would ')
strong('also')
text(' work')

where text and strong are readable in the Element namespace (there doesn't 
actually have to be any relationship between the names you can access and 
the names you set).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading files in small chunks?

2006-04-14 Thread Rajesh Sathyamoorthy
Hi,Could I have some links? It would be very helpful.Thank You.On 4/14/06, Felipe Almeida Lessa wrote:
Em Sex, 2006-04-14 às 13:45 +0800, Rajesh Sathyamoorthy escreveu: I wanted to know why it is more efficient to read a file in smaller chunks ( using file() or open() )?It's more efficient in some cases, and worse on others. It also depends
on how you implement the read loop. I won't elaborate too much here,there are loads of sites and books that talk about this topic. If this is not done, will this lead to errors in the data read or just
 results in slower performance?It doesn't corrupt anything, unless you have a buggy hardware.--Felipe.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: reading files in small chunks?

2006-04-14 Thread Amit Khemka
On 4/14/06, Rajesh Sathyamoorthy [EMAIL PROTECTED] wrote:
 Hi,

 I wanted to know why it is more efficient to read a file in smaller chunks (
 using file() or open() )? If this is not done, will this lead to errors in
 the data read or just results in slower performance?

  Thank You.

It has basically to do with disk seeks and cache+memory utilization.
and you can look around for the same for details on any of your fav
search engine.

cheers,
amit.

 --
 http://mail.python.org/mailman/listinfo/python-list




--

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-14 Thread Sergei Organov
Dennis Lee Bieber [EMAIL PROTECTED] writes:

 On Fri, 14 Apr 2006 09:17:05 +0400, Sergei Organov [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:

 
 I, as a newcomer, don't have much trouble understanding the binding vs
 the assignment by themselves. What does somewhat confuse is dual role of
 the = operator, -- sometimes it means bind and other times it means
 assign, right? For me it seems that the language would be less

   It always means bind... But if the LHS is a mutable object, AND you
 have specified a component of that object, it is the component that is
 being rebound...

   lst[:] = [] 

 is rebinding the elements inside the list lst, and not rebinding the
 name lst. Essentially, once you add any selector to the name
 (object[...]= or object.xxx=) you are going inside the object, and
 manipulating (rebinding) what is inside. If the name is used pure
 (object=), you are rebinding the /name/ to a different object.

Me gets corrected, thanks. Now I need to unroll my mind somewhat back to
figure out when and why I started to believe it sometimes assigns ;)

-- Sergei.

-- 
http://mail.python.org/mailman/listinfo/python-list


create pixmap from data

2006-04-14 Thread Thomas Girod
Hi there.

I have a list containing integer values from 0 to 255. With this list I
have informations width and height, as width * height = len(my_list)

What I want to do is to convert this array into a pixmap of dimension
width * height in order to draw it inside a pygtk GUI.

Any suggestions about a way to display those informations ?

cheers

Thomas

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editing with emacs/wordstar key bindings.

2006-04-14 Thread Sergei Organov
BartlebyScrivener [EMAIL PROTECTED] writes:
 Yes, but for some reason, I get more and better help here with Python
 than on xemacs.   Or maybe I've just had bad luck. Something like the
 following just leaves me scratching my head. I'm on Windows XP and
 never compiled anything that I know of.  I'd rather pay $30 and have
 the editor work.

Well, I'd pay too, but my experience is that no editor *always* works
for me, and ability to fix it (or fine-tune for my own needs) is indeed
essential for me. To the extreme that I'd rather learn some lisp to be
able to (and besides lisp being fun to learn) ;) That said, I do think
(X)emacs is not very suitable for casual user, but it starts to pay back
for investments put into it pretty soon.

BTW, what you've cited below sounds just like messed/broken Emacs
installation (maybe installing one version on top of another, or mixing
Emacs and XEmacs installations, or borrowing some files from separate
archives -- difficult to say exactly), as you normally don't need to
compile anything. Not to mention the fact that Windows is rather new
platform for emacsen, so quite a few OS-specific issues could well be
unresolved or simply be buggy indeed.

Well, I think we should better stop this as an OT anyway.

-- Sergei.


 BartlebyScrivener [EMAIL PROTECTED] writes:
 I tried searching on this but I don't see exactly my error message.
 When I open a php file for editing, I get: file mode specification
 error: (void-function run-mode-hooks)

 What line do I need to add to my .init file to make this stop?

 You are using .elc files compiled with a different version of Emacs.
 Recompile them.

 -- 
 http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


__getattribute__ and __slots__

2006-04-14 Thread pascal . parent
Hi,
I try to define a (new-style) class who:
- have a __slots__ defined to be strict attributes,
- return None if the attribute is 'ok' but not set, or raise a 'normal'
error if the attribute isn't in __slots__.

This code runs, but is it the good way?

Thanks.

class test(object):
 __slots__ = ['id']
 def __getattr__(self, attr):
 if not attr in self.__slots__: raise AttributeError
 try:
 return self.attr
 except:
 return None

-- 
http://mail.python.org/mailman/listinfo/python-list


requestion regarding regular expression

2006-04-14 Thread Kelie
Hello,

I'm trying to analyze some autolisp code with python.  In the file to
be analyzed there are many functions.  Each function begins with a
defun statement.  And before that, there may or may not have comment
line(s), which begins with ;.  My goal is to export each function
into separate files, with comments, if there is any.  Below is the code
that I'm struggling with:

[code]

path = C:\\AutoCAD\\LSP\\Sub.lsp
string = file(path, 'r').read()

import re
pat = \\;+.+\\n\\(DEFUN
p = re.compile(pat,re.I)

iterator = p.finditer(string)
spans = [match.span() for match in iterator]

for i in range(min(15, len(spans))):
print string[spans[i][0]:spans[i][1]]

[/code]

The code above runs fine.  But it only takes care of the situation in
which there is exactly one comment line above the defun statement.
How do I repeat the sub-pattern \\;+.+\\n here?
For example if I want to repeat this pattern 0 to 10 times, I know
\\;+.+\\n{0:10}\\(DEFUN does not work. But don't know where to put
{0:10}.  As a work around, I tried to use
pat = |.join([\\;+.+\\n*i+ \\(DEFUN for i in range(11)]), and it
turned out to be very slow.  Any help?  

Thank you.

Kelie

-- 
http://mail.python.org/mailman/listinfo/python-list


Upgrading and modules

2006-04-14 Thread Brian Elmegaard
Hi,

Every time I upgrade python I also have to download all packages and
reinstall them.

http://www.voidspace.org.uk/python/articles/upgrading_python.html
tells me that this is only a problem on windows for some reasons that
have to do with binary distributions, compiling and more. 

This leads me to the questions:
1: Isn't there a better way? 
2: Why is compilation needed for installation of a package? 
3: Why isn't python backwards compatible so reinstallation is
unneeded?
4: Would it help if python was compiled with gcc/mingw so installation
would be the same as on other systems?
5: What about a package repository and a manager like miktex has?

regards,
-- 
Brian (remove the sport for mail)
http://www.et.web.mek.dtu.dk/Staff/be/be.html
http://www.rugbyklubben-speed.dk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remove Whitespace

2006-04-14 Thread Fredrik Lundh
John Machin wrote:

  $ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
  4 0' 'str.replace( , )'

 Oi! The OP mentioned whitespace ...

yeah. but as is obvious from his examples, he really means UTF-16, not
whitespace.

/F



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: whitespace again

2006-04-14 Thread Fredrik Lundh
david brochu jr wrote:

 still having problemsi have the following in a txt file:

 Windows Registry Editor Version 5.00

if this is a regedit export, the data is encoded as UTF-16.  treating
that as plain ASCII doesn't really work.

 for line in new_line.readlines():
  line = re.sub('',,line)
  print line

 I get:

 i n d o w s   R e g i s t r y   E d i t o r   V e r s i o n   5 . 0 0

 etc etc...Too much space...

it's NUL bytes (chr(0)), not space.

to open an UTF-16 file with automatic decoding, use codecs.open:

import codecs
infile = codecs.open(file, r, utf-16)

reading from infile will now give you properly decoded unicode strings,
which you can process as usual.

 this is killing me please help

sounds like you need to read up on what text encodings are, and how
you can let Python handle them for you.  start here:

http://www.google.com/search?q=python+unicode

/F



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace issue

2006-04-14 Thread Daniel Nogradi
 def _gn(x):
 return x.upper()

 great_name = _gn

 class myclass:
 def mymethod(self, great_name=False):
 if great_name:
 return _gn('something')
 else:
 return 'something'


   def great_name(x):
 ... return x.upper()
 ...
   class myclass(object):
 ... def mymethod(self, great_name=False):
 ... if great_name:
 ... return globals()['great_name']('something')
 ... else:
 ... return 'something'
 ...
   myclass().mymethod()
 'something'
   myclass().mymethod(True)
 'SOMETHING'



Thanks a lot for both suggestions, they were the things I was looking for.
-- 
http://mail.python.org/mailman/listinfo/python-list


sending email with charset utf-8 but subject is not coded properly

2006-04-14 Thread Grzegorz Ślusarek
Hi all. I sending email using standard python modules smtplib, email, 
coding email in utf but subject of message is not coded properly. In 
subject i use my national characters (polish) and after send i get XX in 
place these characters.
Here is the code

Message = email.message_from_string(pMessage)
Message.set_charset('utf-8')
Message['From'] = '[EMAIL PROTECTED]'
Message['To'] = '[EMAIL PROTECTED]'
SMTPServer=smtplib.SMTP(ConfigurationManager.SMTPServer)
SMTPServer.sendmail('[EMAIL PROTECTED]','[EMAIL PROTECTED]', 
Message.as_string())

Message looks like this:
Subject: Nowe hasło
\n
\n
Nowe email z haslem..

I looked how smtp serwer see my message and I notice that it looks like 
content of the message is convert by BASE64 but not the subject. What 
I'm doing wrong? can anyone tell me?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: create pixmap from data

2006-04-14 Thread Eric Deveaud
Thomas Girod wrote:
  Hi there.
 
  I have a list containing integer values from 0 to 255. With this list I
  have informations width and height, as width * height = len(my_list)
 
  What I want to do is to convert this array into a pixmap of dimension
  width * height in order to draw it inside a pygtk GUI.
 
  Any suggestions about a way to display those informations ?


check the PIL (Python Imaging Library), Image module

Eric


-- 
 S Je cherche aussi des adresses de lieux contenant des fossiles dans
 S la région parisienne 
 http://www.senat.fr/
 -+- DP in http://www.le-gnu.net : La dianurette et les fossiles -+-
-- 
http://mail.python.org/mailman/listinfo/python-list


List of all syntactic sugar?

2006-04-14 Thread Bas
Hi group,

just out of curiosity, is there a list of all the syntactic sugar that
is used in python? If there isn't such a list, could it be put on a
wiki somewhere? The bit of sugar that I do know have helped me a lot in
understanding the inner workings of python.

To give a few examples (might not be totally correct):

x[i] - x.__getitem__(i)
x[a:b] - x.__getitem__(slice(a,b,None))
x+y - x._add__(y)
x.method(a) - call (x.__dict__[method], self, a) ??
for i in x: f(i) - it = iter(x); while True: i = it.next(); f(i) 
except stop: pass

TIA,
Bas

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A problem with exec statement

2006-04-14 Thread TPJ
 Use the exec statement without the in-clause to get the desired effect:

  def f():
 ... a = a
 ... exec a = 'B'
 ... print a
 ...
  f()
 B
 snip

Well... I *do* realize that. But this is *not* my problem. I have a
function with another nested one. If I used exec ... instead of exec
... in some_dict, some_dict I would get the SyntaxError: unqualified
exec is not allowed in function 'f' it contains a nested function with
free variables.

To be honest, the message cited above is the answer to the question
Why have I put those globals(), locals() in the exec statments?.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remove Whitespace

2006-04-14 Thread Roel Schroeven
Fredrik Lundh schreef:
 John Machin wrote:
 
 $ python2.4 -mtimeit -s str = 'D c a V e r \ = d w o r d : 0 0 0 0 0 6
 4 0' 'str.replace( , )'
 Oi! The OP mentioned whitespace ...
 
 yeah. but as is obvious from his examples, he really means UTF-16, not
 whitespace.

Yes, that's what I was thinking. His data looks like a part of a Windows 
registry export, which at least on my system is in what Windows calls 
Unicode.

-- 
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: sending email with charset utf-8 but subject is not coded properly

2006-04-14 Thread Rene Pijlman
Grzegorz ¦lusarek:
I sending email using standard python modules smtplib, email, 
coding email in utf but subject of message is not coded properly. In 
subject i use my national characters (polish) and after send i get XX in 
place these characters.
Here is the code

Message = email.message_from_string(pMessage)
   Message.set_charset('utf-8')
   Message['From'] = '[EMAIL PROTECTED]'
   Message['To'] = '[EMAIL PROTECTED]'
   SMTPServer=smtplib.SMTP(ConfigurationManager.SMTPServer)
   SMTPServer.sendmail('[EMAIL PROTECTED]','[EMAIL PROTECTED]', 
 Message.as_string())

I see no subject in this code.

If you want to include non-ASCII characters in your email headers, say in
the Subject: or To: fields, you should use the Header class and assign the
field in the Message object to an instance of Header instead of using a
string for the header value.
http://docs.python.org/lib/module-email.Header.html

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of all syntactic sugar?

2006-04-14 Thread Rene Pijlman
Bas:
just out of curiosity, is there a list of all the syntactic sugar that
is used in python? 

http://docs.python.org/ref/specialnames.html

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of all syntactic sugar?

2006-04-14 Thread Steven D'Aprano
On Fri, 14 Apr 2006 02:54:11 -0700, Bas wrote:

 Hi group,
 
 just out of curiosity, is there a list of all the syntactic sugar that
 is used in python? If there isn't such a list, could it be put on a
 wiki somewhere? The bit of sugar that I do know have helped me a lot in
 understanding the inner workings of python.

That kind of depends on what you mean by syntactic sugar. For instance, I
wouldn't call any of your examples syntactic sugar. The problem with
(e.g.) calling x[i] syntactic sugar for x.__getitem__(i) is that it gets
the relationship backwards: x[i] _is_ the syntax, it isn't the sugar.
Magic methods like __getitem__ are there as a mechanism to allow custom
classes to use the same syntax as built-in classes.

However, I would call these syntactic sugar:

hello   world - hello world # literal string concatenation

r'raw strings'

x[-n] - x[len(x)-n]

x[:] - x[0:len(x)]

print obj - sys.stdout.write(str(obj) + '\n')

print obj, - sys.stdout.write(str(obj))

s.find(target) - 
try:
return s.index(target)
except IndexError:
return -1
# not really syntax, perhaps method sugar is a better name?

import a, b, c - import a; import b; import c

raise Exception, string - raise Exception(string)


Of course, one person's syntactic sugar is another person's essential
syntactic carbohydrates.



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A problem with exec statement

2006-04-14 Thread TPJ
 snip
 So when you exec 'a = B' in globals(), locals() you might think you
 were changing the local namespace. In fact you are changing a copy of
 the local namespace:
 snip

Well, that explains much, but not all that I want to be explained. Why?
Because now I understand, that by invoking

exec a = 'B' in globals(), locals()

I can modify only *copies* of the global and local namespaces dicts,
not the dicts themselves. OK, that's why my code doesn't work as I want
it to work.

But why on Earth *the same code* will work, if I remove the assignments
from the marked lines? Why then operating on copies of the local
namespaces dicts *will work* ?

 (...) Even allowing for the
 difficulties you've already experienced, it's nearly always better in
 practical cases to use assignment to the keys of a dictionary. Then no
 exec is required, and you have direct control over your own namespace.

Well... Is this a sugestion, that instead of messing up with the exec
statements used to modify local namespaces I should use dictionaries?

Perhaps you're right. In fact, the problem, that I'm trying to solve is
as follows:

def funcA():

  def funcB():
...
var1, var2, var3, ..., varN = ( None, ) * N
t = ( (regexp1, 'var1'), (regexp2, 'var2'), ..., (regexpN, 'varN')
)
for regexp, var_name in t:
  match = regexp.match( some_string )
  if match != None:
  # now the *magic* exec statement comes...
exec var_name + ' = match.groups()[0]' in globals(), locals()
return var1, var2, var3, ..., varN

  ...
  k1, k2, k3, ..., kN = funcB()

Of course, the code presented above doesn't work. It works, if one
change is done in the function funcB:

  def funcB():
...
# no creation of any local variables called var1, var2, ..., varN
here
t = ( (regexp1, 'var1'), (regexp2, 'var2'), ..., (regexpN, 'varN')
)
for regexp, var_name in t:
  match = regexp.match( some_string )
  if match != None:
  # now the *magic* exec statement comes...
exec var_name + ' = match.groups()[0]' in globals(), locals()
  else:
  # here we put the code, that will assign None to the variable
exec var_name + ' = None'
return var1, var2, var3, ..., varN

But I *still* don't understand, why this code works, if I operate on a
copy of the local namespace dict...

Of course, I can do the same thing in a different matter - by using a
dictionary. And perhaps I will. But I still want to know, how the exec
statement works.

* * *

My problem is more complicated, that the presented example. In general,
my problem is: how to create a local variable by executing the Python
code, that isn't known at the moment of writing the program? In another
words: I have to create a local variable, whose name will be known at
the runtime, in a nested function.

Is it possible, or have I to use dictionaries, instead of exec
statement used to modify local namespaces?

-- 
http://mail.python.org/mailman/listinfo/python-list


Future Warning with Negative Int

2006-04-14 Thread brianlum
Hi,

If I try to print a negative integer as a hexadecimal, I get the
following error:
FutureWarning: %u/%o/%x/%X of negative int will return a signed string
in Python 2.4 and up

For example:
 print %X % -1
__main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a
signed string in Python 2.4 and up


Does that mean that in the future it will say -1 or -?  Also,
how do I suppress this warning?

Thanks,
Brian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of all syntactic sugar?

2006-04-14 Thread Bas
That kind of depends on what you mean by syntactic sugar.

Mightbe I was misusing the name of syntactic sugar, but I what I
intended to say was all the possible 'transformations' that can be
made to reduce all the 'advanced' syntax to some sort of minimal core
of the language.

Bas

-- 
http://mail.python.org/mailman/listinfo/python-list


nested functions

2006-04-14 Thread micklee74
hi
just curious , if i have a code like this?

def a():
  def b():
print b
  def c():
print c

how can i call c() ??

-- 
http://mail.python.org/mailman/listinfo/python-list


GdkColor : the phantom class ?

2006-04-14 Thread Thomas Girod
Hi.

No matter how I try, I just can't find this GdkColor class. I'm trying
to convert some data into a pixmap in order to display it. Here is my
code :

import pygtk
pygtk.require('2.0')
import gtk
xbm = #define dump_width 4
#define dump_height 4
static unsigned char dump_bits[] = { 0xaa, 0x6c, 0x55, 0x58, 0x4f,
0x4d, 0xb, 0x9b, 0xf8, 0xcc, 0x1d, 0xd5, 0x61, 0xa4, 0xd8, 0x78,  };

class Ex:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.show()

pixmap = gtk.gdk.pixmap_create_from_data(window.window,
##display
 xbm, ##data
 28,28, ##width/height
 8, ##depth
 fg,bg)

image = gtk.Image()
image.set_from_pixmap(pixmap, None)
image.show()

def main(self):
gtk.main()
return 0

e = Ex()
e.main()

--
The error comes from fg / bg. It says this have to be of type GdkColor,
but I can't find this class anywhere.

Plus, can anyone explain me the utility of those parameters, as I don't
understand the need to set a background and a foreground when you fill
every damn pixel with data ...

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: telnet read_sb_data

2006-04-14 Thread Arne
Thank you for your reply.

Yes I have read the documentation. But I am not sure what is the SB/SE 
suboption. Is this a suboption on the remote machine or for Python.
Maybe you could be so kind and explain it to me with a little code example.

Thany you very much!
Arne

Dennis Lee Bieber [EMAIL PROTECTED] schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
 On Thu, 13 Apr 2006 23:45:06 +0200, Arne [EMAIL PROTECTED]
 declaimed the following in comp.lang.python:

 1. What I look for is the option to get only certain parts of the output. 
 It
 seems to me that the command read_sb_data can do this. The 
 documentation
 says, that I will get the data between the SB/SE pair. But I don't know 
 how
 to invoke the SE command in Unix. Even I don't know the SE command.

 Did you read the full documentation? SB/SE are suboption
 begin/end, and there is also mention of a callback. The ONLY other
 entry in telnetlib that mentions callbacks is the one for negotiating
 telnet options.

 read_sb_data( )
 Return the data collected between a SB/SE pair (suboption begin/end).
 The callback should access these data when it was invoked with a SE
 command. This method never blocks.

 set_option_negotiation_callback( callback)
 Each time a telnet option is read on the input flow, this callback (if
 set) is called with the following parameters : callback(telnet socket,
 command (DO/DONT/WILL/WONT), option). No other action is done afterwards
 by telnetlib.


 Using os.stat(path) doesen't work on XP, I am always getting a 0 return

 No surprise -- os.stat can only access files mounted on the local
 machine. Telnet is remote /terminal/ connection. You'll have to behave
 like a terminal... How would you, as a user at a terminal, know when any
 command had finished? Probably by seeing a console prompt...

 Try

 read_until( expected[, timeout])
 Read until a given string, expected, is encountered or until timeout
 seconds have passed.
 When no match is found, return whatever is available instead, possibly
 the empty string. Raise EOFError if the connection is closed and no
 cooked data is available.

 You'll have to know what the prompt string will be...
 -- 
  == 
[EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG 
   [EMAIL PROTECTED] |   Bestiaria Support Staff   
  == 
Home Page: http://www.dm.net/~wulfraed/
 Overflow Page: http://wlfraed.home.netcom.com/ 


-- 
http://mail.python.org/mailman/listinfo/python-list


%g not the same as %e or %f

2006-04-14 Thread Kent Johnson
According to the docs, %g formatting is Same as e if exponent is
greater than -4 or less than precision, f otherwise. So I would
expect that for any num, '%g'%num == '%e'%num or '%g'%num == '%f'%num.
But this is not the case in fact:

Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on
win32
Type help, copyright, credits or license for more information.

In [1]: num = 1234567898.2345678945

In [2]: print %g\n%e\n%f % (num,num,num)
1.23457e+009
1.234568e+009
1234567898.234568

In [3]: num = 1234.456789

In [4]: print %g\n%e\n%f % (num,num,num)
1234.46
1.234457e+003
1234.456789

So I'm wondering if the docs are wrong or the implementation is wrong or
there's something I don't understand?

Thanks,
Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Kross - Start of a Unified Scripting Approach

2006-04-14 Thread has
Jerry wrote:
 Kind of like AppleScript then?

Same fundamental goal, i.e. language-independent application scripting.
They seem to have a similar sort of approach to decoupling a scripting
language from its host application (Kross::API::ScriptManager vs. the
Open Scripting Architecture API) but a very different approach to the
intercommunication part.

Kross appears to create native language wrappers for the application's
public (C++) classes; nothing fancy, but pretty straightforward. Mac
apps use serialised procedure calls containing first-class queries and
other arguments to describe the action to perform and the application
object(s) to use in that action. A query engine in the application
framework (e.g. Cocoa Scripting) locates the actual object(s) and
applies the appropriate action to them. Much higher level of
abstraction and a lot more sophisticated, though it can be a bit tricky
for application developers to implement (for the same reason).

Plus I get the impression that Kross doesn't do interprocess yet
although it's on the cards, presumably using something like proxy
objects and dbus to provide the bridge. With Macs you only need OSA for
intraprocess communication; the Apple Event Manager, which handles the
messaging part, can pass messages between processes as well.

 Sorry, just starting to learn about some of this stuff (CLI, CLR, CIL,
 etc...) and am interested in understanding better.

As far as how the Mac does it, here's an old but good paper on the
basic principles involved if you want to know more:

http://www.cs.utexas.edu/users/wcook/papers/AppleScript/AppleScript95.pdf

I couldn't find a nice, simple overview of the Kross system. You should
be able to form a rough impression from reading through the following
links, although some better examples of calling Kexi from scripts would
help:

http://wiki.kde.org/tiki-index.php?page=kross
http://www.kexi-project.org/wiki/wikiview/index.php?Scripting
http://www.kexi-project.org/docs/cvs-api/html/namespaceKross.html

HTH

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
 hi
 just curious , if i have a code like this?
 
 def a():
   def b():
 print b
   def c():
 print c
 
 how can i call c() ??

c is a name in the local scope of a(). You can call c from within a, 
where the name is in scope, or you can return c or in some other way 
make the value available in some other scope:

In [5]: def a():
...: def c():
...: print 'called c'
...: c()
...: return c
...:

In [6]: cc=a()
called c

In [7]: cc()
called c

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread Szabolcs Berecz
On 14 Apr 2006 04:37:54 -0700, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 def a():
   def b():
 print b
   def c():
 print c

 how can i call c() ??

Function c() is not meant to be called from outside function a().
That's what a nested function is for: localizing it's usage and
prevent cluttering the global namespace

Szabi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: GdkColor : the phantom class ?

2006-04-14 Thread Thomas Girod
I found an answer :

color = gtk.gdk.Color()

and then use color for fg et bg

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-14 Thread Ben C
On 2006-04-14, Sergei Organov [EMAIL PROTECTED] wrote:
 Dennis Lee Bieber [EMAIL PROTECTED] writes:
  It always means bind... But if the LHS is a mutable object, AND you
 have specified a component of that object, it is the component that is
 being rebound...

  lst[:] = [] 

 [...]

 Me gets corrected, thanks. Now I need to unroll my mind somewhat back to
 figure out when and why I started to believe it sometimes assigns ;)

I used to think it assigned with things like integers, because if you
write:

a = 5
b = a
b += 1
print a

a is still 5. So it looked like a and b stored values and b got a copy
of a's value. But this is the wrong interpretation,

b += 1

is really b = b + 1, and rebinds b.

You can see what's really going on if you use the id() function on a and
b during these operations.

The other reason for the confusion is that I think in Java a variable
either stores a value, in the case of numbers, or a reference in the
case of objects (or a copy-on-write reference, which behaves like a
value, in the case of strings). In Python it's better to think of it as
always a reference, and to think in terms of immutable vs. mutable
objects that are referred to.

If it weren't for the id() function I think the difference between
variable stores value, variable stores immutable reference and
variable stores copy-on-write reference would be implementation detail
and never visible to the programmer. That's why it's easy to be
confused-- most of the time these interpretations are equivalent, so
it doesn't matter which you work with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: requestion regarding regular expression

2006-04-14 Thread Kent Johnson
Kelie wrote:
 Hello,
 
 I'm trying to analyze some autolisp code with python.  In the file to
 be analyzed there are many functions.  Each function begins with a
 defun statement.  And before that, there may or may not have comment
 line(s), which begins with ;.  My goal is to export each function
 into separate files, with comments, if there is any.  Below is the code
 that I'm struggling with:
 
 [code]
 
 path = C:\\AutoCAD\\LSP\\Sub.lsp
 string = file(path, 'r').read()
 
 import re
 pat = \\;+.+\\n\\(DEFUN
 p = re.compile(pat,re.I)
 
 iterator = p.finditer(string)
 spans = [match.span() for match in iterator]
 
 for i in range(min(15, len(spans))):
 print string[spans[i][0]:spans[i][1]]
 
 [/code]
 
 The code above runs fine.  But it only takes care of the situation in
 which there is exactly one comment line above the defun statement.

ISTM you don't need regex here, a simple line processor will work. 
Something like this (untested):

path = C:\\AutoCAD\\LSP\\Sub.lsp
lines = open(path).readlines()

# Find the starts of all the functions
starts = [i for i, line in enumerate(lines) if line.startswith('(DEFUN')]

# Check for leading comments
for i, start in starts:
   while start  0 and lines[start-1].startswith(';'):
 starts[i] = start = start-1

# Now starts should be a list of line numbers for the start of each function

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of all syntactic sugar?

2006-04-14 Thread Diez B. Roggisch
 That kind of depends on what you mean by syntactic sugar. For instance, I
 wouldn't call any of your examples syntactic sugar. 

AFAIK that is exactly what syntactic sugar means. Apart from non-strictness,
all syntax can be expressed by function application. Even 

foo.bar()

is nothing but

bar(self)

So - he used the term right I'd say.

Regards,

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Searching and MySQL module stuff

2006-04-14 Thread broz
Thx for the help in finding the search page for this mailing list!!
BartlebyScrivener pointed me to the right place.

From there
http://groups.google.com/group/comp.lang.python
, I found what I needed

I also discovered I can load mysql-python on my mac fairly easily, if I use
Darwin Ports. 
http://darwinports.opendarwin.org/

Rock and roll!

Thx all!


-- 
http://mail.python.org/mailman/listinfo/python-list


Loop with float increments (frange)?

2006-04-14 Thread forum
Hi!

what's the standard way for a for loop with float increments?

Anton

-- 
http://mail.python.org/mailman/listinfo/python-list


IMPORTANT 2.5 API changes for C Extension Modules and Embedders

2006-04-14 Thread Neal Norwitz
If you don't write or otherwise maintain Python Extension Modules
written in C (or C++) or embed Python in your application,
you can stop reading.

Python 2.5 alpha 1 was released April 5, 2006.  The second alpha
should be released in a few weeks.  There are several changes
which can cause C extension modules or embedded applications
to crash the interpreter if not fixed.  Periodically, I will send out
these reminders with updated information until 2.5 is released.

  * support for 64-bit sequences (eg,  2GB strings)
  * memory allocation modifications

64-bit changes
--
There are important changes that are in 2.5 to support 64-bit systems.
The 64-bit changes can cause Python to crash if your module is not upgraded
to support the changes.  Python was changed internally to use 64-bit
values on 64-bit machines for indices.  If you've got a machine with
more than 16 GB of RAM, it would be great if you can test Python with
large ( 2GB) strings and other sequences.

For more details about the Python 2.5 schedule:
http://www.python.org/dev/peps/pep-0356/
For more details about the 64-bit change:
http://www.python.org/dev/peps/pep-0353/
How to fix your module:
http://www.python.org/dev/peps/pep-0353/#conversion-guidelines

The effbot wrote a program to check your code and find potential
problems with the 64-bit APIs.
http://svn.effbot.python-hosting.com/stuff/sandbox/python/ssizecheck.py

Memory Allocation Modifications
---
In previous versions of Python, it was possible to use different
families of APIs (PyMem_* vs. PyObject_*) to allocate and free
the same block of memory.  APIs in these families include:

  PyMem_*:PyMem_Malloc, PyMem_Realloc, PyMem_Free,
  PyObject_*: PyObject_Malloc, PyObject_Realloc, PyObject_Free

There are a few other APIs with similar names and also the macro variants.

In 2.5, if allocate a block of memory with one family, you must reallocate
or free with the same family.  That means:

  If you allocate with PyMem_Malloc (or MALLOC), you must reallocate
  with PyMem_Realloc (or REALLOC) and free with PyMem_Free (or FREE).
  If you allocate with PyObject_Malloc (or MALLOC), you must reallocate
  with PyObject_Realloc (or REALLOC) and free with PyObject_Free (or FREE).

Using inconsistent APIs can cause double frees or otherwise crash
the interpreter.  It is fine to mix and match functions or macros
within the same family.

Please test and upgrade your extension modules!

Cheers,
n
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Kross - Start of a Unified Scripting Approach

2006-04-14 Thread Jerry
Awesome, thanks for the explaination.  It was very informative.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to install python modules on linux

2006-04-14 Thread Fabian Braennstroem
Hi Harry,

* Harry George [EMAIL PROTECTED] wrote:
 Fabian Braennstroem [EMAIL PROTECTED] writes:

 Hi,
 
 I am pretty new to python and will use it mainly in
 combination with scientific packages. I am running ubuntu
 breezy right now and see that some packages are out of date.
 Do you have any suggestion, how I can get/keep the latest
 python modules (e.g. scipy, numpy,...) on my ubuntu system?
 I.e. does there exist any script/program, which downloads
 and installs automatically the latest stable releases of selected
 modules? It would be nice, if the program can remove the
 installed modules, too!?
 
 Or would it be easier to stick to apt/deb and create own
 packages ...
 
 
 Greetings!
  Fabian
 

 I find it helpful to leave the as-delivered Python (e.g.,
 /usr/bin/python) as-is.  It is being used to run your basic Linux
 system.  Screwing around with it can have nasty side effects.  Instead
 I build a new one at /usr/local, give it a unique name, and
 upgrade/hack that one to my heart's content.  E.g., if the base system
 is using Python 2.2, you can be running Python 2.4 as
 /usr/local/bin/py24, and add all the numerical packages you wish at
 use/local/lib/python2.4/site-packages.  Also, make sure root doesn't
 have /usr/local/bin on its PATH (which is a good rule anyway).

Maybe, I should consider this, too. Thanks!

Greetings!
 Fabian

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why new Python 2.5 feature class C() return old-style class ?

2006-04-14 Thread Christophe
Aahz a écrit :
 In article [EMAIL PROTECTED],
 Felipe Almeida Lessa  [EMAIL PROTECTED] wrote:
 
Em Ter, 2006-04-11 Ã s 07:17 -0700, Aahz escreveu:

Can, yes.  But should it?  The whole point of adding the () option to
classes was to ease the learning process for newbies who don't
understand why classes have a different syntax from functions.  Having

class C(): pass

behave differently from

class C: pass

would be of no benefit for that purpose.

Why should a newbie use an old-style class?
 
 
 Because that's the default.  Because lots of existing code still uses
 classic classes, so you need to learn them anyway.  Because you can't use
 new-style classes in code intended for 2.1 or earlier; because of the
 changes made in 2.3, I don't particularly recommend new-style classes for
 2.2.  Because even the second edition of _Learning Python_ (targeted at
 Python 2.3) doesn't cover new-style classes much, so I'm certainly not
 alone in believing that new-style classes are better avoided for newbies.

Well, old-style classes are perfect to confuse the newbie. After all, 
there's nothing like adding a property in a class and wondering why 
it does not work as expected.

What would be a language without horrible pitfalls ? Newbies would have 
it easy and they have no right for an easy language !
-- 
http://mail.python.org/mailman/listinfo/python-list


Discover Medieval Romania /Vlad the Impaler/Dracula/ /www.medievaltours.ro

2006-04-14 Thread Medieval Tours
br


div align=centera
href=http://www.medievaltours.ro/en/about.php;span
style=/span/aa
href=http://www.medievaltours.ro/en/about.php;span style=img
moz-do-not-send=true alt=
src=http://www.medievalart.ro/img/img-cavaler.gif; border=0
height=155 width=92/span/abigbigbigfont
color=#00bspan style=Discover
Medieval Romaniaimg alt=
src=http://www.medievalart.ro/img/logo-medieval.gif; height=139
width=99/span/b/font/big/big/biga
href=http://www.medievaltours.ro/en/about.php;span
style=/span/abigbigbigfont color=#00bspan
style=/span/bbspan
style=/span/b/font/big/big/bigbr
bigbigbigfont color=#00bspan
style=/span/b/font/big/big/big/div
div align=left
div align=centerfont color=#00span style=font-size: 11pt;
line-height: 125%;/span/fonta
href=http://www.medievaltours.ro/en/about.php;img
moz-do-not-send=true alt=
src=http://www.medievaltours.ro/pics/about/hpim0238.jpg; border=0
height=178 width=237span style=/span/abr
/div

font color=#00span style=font-size: 11pt; line-height:
125%;/span/font/div
p class=MsoBodyText3 style= align=centerfont
color=#00span style=font-size: 11pt; line-height: 125%;We
have the pleasure and
honour of presenting you br
the opportunity to watch and participate in an authentic br
medieval show and really discover /spanspan style=Medieval
Romania/span/fontspan style=font-size: 11pt; line-height:
125%;font color=#00.br
/font/span/p
p class=MsoBodyText3 style= align=centerspan style=font-size:
12pt; line-height: 125%; font-family: quot;Trebuchet MSquot;; color:
rgb(102, 102, 51); font-weight: bold;Why
Romania? o:p/o:p/span/p
div align=center/div
p class=MsoBodyText3 style= align=centerspan style=Could
this country
located between the Balkans and the Carpathians, br
between East and West, provide unforgetable moments? /spanspan
style=font-size: 10pt; line-height: 125%;span
style=nbsp;/spano:p/o:p/span/p

div align=center/div
p class=MsoBodyText3 style= align=centerspan style=Let me
invite you to
visit a land with untouched landscapes, br
with villages and hospitable people - which rarely would you meet in
somebr
nbsp;other countries - with vast flower meadows, with the most
beautiful
monasteriesbr
nbsp;ever seen all over the world, with wonderful bird singing in the
/spanspan style=font-weight: bold;Danube Delta/spanspan
style=,br
nbsp;with the unique landscapes, with incomparable wood churches of
/spanspan style=font-weight: bold;Maramuresbr
/spanspan style=nbsp;and last but not least,nbsp; /spanlast
but not
least, the unrivalled Medieval church-fortresses outliving
over centuries.br

nbsp;
span style=/spanAll this offers you, the traveller in this land,
a
sensation of timelessness which takes youbr
nbsp;away to far Medieval vanished
worlds and yet, so close to you.br
a href=http://www.medievaltours.ro/en/about.php;img
moz-do-not-send=true alt=
src=http://www.medievaltours.ro/pics/about/hpim0217.jpg; border=0
height=187 width=250/a.a
href=http://www.medievaltours.ro/en/about.php;img
moz-do-not-send=true alt=
src=http://www.medievaltours.ro/pics/about/hpim0229.jpg; border=0
height=187 width=250/a/p
div align=centerbigbigbigfont color=#00bspan
style=/span/b/font/big/big/big
/div
p class=MsoNormal style= align=centerspan style=!--[if
!supportEmptyParas]--/spanLet
the sensation lead you to this country; try the steam train
in the bVaser Valey/b in the highland of bMaramures/b, br
try a ride on the narrow railway in the bApuseni Mountains/b.
Forget about accomodation in a 5* hotel br

and try to sleep overnight in a 100 years' house in the
bTransylvanian
Saxon villages/b;br
nbsp;live simply and cleanly for a couple of days in the countryside,
br
try
rustic accomodation in private homes; ask the peasants about pottery,
carpet weaving, painting on glass, br
egg dyeing and painting. Ask them
about the bMerry Cemetery/b and ask them why they meet Death with
a smile on their faces;br
nbsp;have a meal at a sheepfold located in
highlands, together with the shepherds and their livestock; br
feel at
least for one day the Medieval world in the unequaled bFortress of
Sighisoara/b. br

At the end of such intense journey you may have the answer to the
question:br
br
/p
div align=center/div
p class=MsoBodyText3 style= align=centerspan
style=/spanspan style=font-size: 12pt; line-height: 125%;
font-weight: bold;More
info on /spana
href=http://www.medievaltours.ro;bigbigbigfont
color=#00bspan style=img moz-do-not-send=true alt=
src=http://www.mancare-mexicana.com/medieval-tours.gif; border=0
height=33 width=110/span/b/font/big/big/big/aspan
style=font-size: 12pt; line-height: 125%; font-weight: bold;
/spanfont color=#006600span style=font-size: 12pt; line-height:
125%; font-weight: bold;a
href=http://www.medievaltours.ro;www.medievaltours.ro /abr
/span/font/p
div align=center/div
p class=MsoBodyText3 style= align=centerspan style=font-size:
12pt; line-height: 125%; color: rgb(153, 153, 0); font-style: italic;
font-weight: bold;br
br
/span/p
div align=center/div
p 

Re: %g not the same as %e or %f

2006-04-14 Thread Fredrik Lundh
Kent Johnson wrote:

 According to the docs, %g formatting is Same as e if exponent is
 greater than -4 or less than precision, f otherwise. So I would
 expect that for any num, '%g'%num == '%e'%num or '%g'%num == '%f'%num.
 But this is not the case in fact:

 Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on
 win32
 Type help, copyright, credits or license for more information.

 In [1]: num = 1234567898.2345678945

 In [2]: print %g\n%e\n%f % (num,num,num)
 1.23457e+009
 1.234568e+009
 1234567898.234568

 In [3]: num = 1234.456789

 In [4]: print %g\n%e\n%f % (num,num,num)
 1234.46
 1.234457e+003
 1234.456789

 So I'm wondering if the docs are wrong or the implementation is wrong or
 there's something I don't understand?

format != result.  the phrase same format refers to decimal format vs.
exponential format (see the descriptions of %e and %f in the same table),
not the contents of the output string.

(both formats use the same precision value, but %g interprets it as number
of significant digits, while %f and %e interprets it as number of decimals).

the C standard uses the word style instead:

e) The double argument shall be converted in the style [-]d.ddde±dd,
where there is one digit before the radix character (which is non-zero
if the argument is non-zero) and the number of digits after it is equal
to the precision /.../

f) The double argument shall be converted to decimal notation in the
style [-]ddd.ddd, where the number of digits after the radix character
is equal to the precision specification /.../

g) The double argument shall be converted in the style f or e (or in
the style F or E in the case of a G conversion specifier), with the 
precision
specifying the number of significant digits /.../

/F



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Upgrading and modules

2006-04-14 Thread BartlebyScrivener
Are you saying you're on Windows?

If so, try:

http://www.activestate.com/Products/ActivePython/

It's a one-click, msi install with everything you need for win32,
including IDE etc.

Only thing to watch for is that sometimes the msi file won't install
from a logical drive other than c:\. So if you get a file access error
or something, copy the install file to the root of your c:\ drive and
double-click on it.

I'm sure someone else will come along with advice for the Python.org
installation.

rick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: telnet read_sb_data

2006-04-14 Thread Grant Edwards
On 2006-04-14, Arne [EMAIL PROTECTED] wrote:

 Yes I have read the documentation. But I am not sure what is
 the SB/SE suboption. Is this a suboption on the remote machine
 or for Python. Maybe you could be so kind and explain it to me
 with a little code example.

SB/SE are used for telnet protocol option negotation for telnet
protocol options that are more complicated that just on/off.
It has absolutely nothing to do with what you're trying to do.

For more info, read the RFC on the telnet protocol option
negotiation:

  http://www.faqs.org/rfcs/rfc855.html

Here's another decent article:

  http://www.scit.wlv.ac.uk/~jphb/comms/telnet.html

-- 
Grant Edwards   grante Yow!  .. I
  at   feel... JUGULAR...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 just curious , if i have a code like this?

 def a():
   def b():
 print b
   def c():
 print c

 how can i call c() ??

in the same way as you'd access the variable c in this example:

def a():
c = 10

(that is, by calling the function and accessing the local variable c
from the inside.  in both cases, c lives in the local namespace, and
doesn't exist at all unless you call the function).

/F



-- 
http://mail.python.org/mailman/listinfo/python-list


zlib and zip files

2006-04-14 Thread Jan Prochazka
Hi,
I need to decompress zip archive. I wrote a parser of zip file, i obtain
the compressed data, but when i call zlib.decompress(data) on them,
it throws this error:

decbuf = decompressor.decompress(compressed_data)

error: Error -3 while decompressing: unknown compression method

I try to compress by zlib the same data which are in that file, the
result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' on end
when i tried to put this extending data to zlib decompressor, it
decompress some files of zip archive, but it fails, when i try to
decompress 100MB file from archive

could you help, please?
thanks
Honza

-- 
http://mail.python.org/mailman/listinfo/python-list


zlib zip files

2006-04-14 Thread Jan Prochazka
Hi,
I need to decompress zip archive. I wrote a parser of zip file, i obtain 
the compressed data, but when i call zlib.decompress(data) on them,
it throws this error:

decbuf = decompressor.decompress(compressed_data)

error: Error -3 while decompressing: unknown compression method

I try to compress by zlib the same data which are in that file, the 
result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' on end
when i tried to put this extending data to zlib decompressor, it 
decompress some files of zip archive, but it fails, when i try to 
decompress 100MB file from archive

could you help, please?
thanks
Honza
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread Thomas Bartkus
[EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 hi
 just curious , if i have a code like this?

 def a():
   def b():
 print b
   def c():
 print c

 how can i call c() ??

Your function 'a' is it's own little world where functions 'b' and 'c'
exist.
Your code inside 'a' can call 'b' or 'c' - neat as you please.

BUT 'b' and 'c' simply do not exist outside the 'a' world.  This is perfect
because you are in control - building worlds according to your own design.
Had it not been your intention to hide 'b' and 'c', you would not have
isolated them in this manner inside of  'a' .

I, for one, am so glad to have nested functions again ;-)
Thomas Bartkus


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop with float increments (frange)?

2006-04-14 Thread Dan Sommers
On 14 Apr 2006 06:11:38 -0700,
[EMAIL PROTECTED] wrote:

 what's the standard way for a for loop with float increments?

Use a while loop instead:

f = initial_value
while f = final_value:
process(f)
f = f + increment

Note that there is no general guarantee that f will actually be
final_value; see also http://docs.python.org/tut/node16.html.

Regards,
Dan

-- 
Dan Sommers
http://www.tombstonezero.net/dan/
I wish people would die in alphabetical order. -- My wife, the genealogist
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread Fredrik Lundh
Thomas Bartkus wrote:

 I, for one, am so glad to have nested functions again ;-)

again ?

Python has always supported nested functions.  it's the scoping rules
that have changed; before the change from LGB to LEGB, you had to
explictly import objects from outer scopes.

/F



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop with float increments (frange)?

2006-04-14 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

 Hi!
 
 what's the standard way for a for loop with float increments?

AFAIK there is no, but you should be easily able to write an frange
yourself:


def frange(from, to, step):
while from  to:
   yield from
   from += step

for x in frange(10.5, 23.4, 0.3):
   print x


Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Steven Bethard
Duncan Booth wrote:
 Steven Bethard wrote:
 
 Should users of the make statement be able to determine in which dict
 object the code is executed?  The make statement could look for a
 ``__make_dict__`` attribute and call it to allow things like::

  make Element html:
  make Element body:
  make Element h1:
  '''First heading text'''
  make Element h1:
  '''Second heading text'''
 
[snip]
 There is another effect which should be considered here. If you allow 
 Element to create an object to be used as the namespace, then as well as 
 doing special tracking when values are set in the namespace it can also 
 pre-seed it with names which magically appear in scope within the make.
 
 e.g.
 
 make Element html:
 make Element body:
 make Element p:
 text('But this ')
 make Element strong:
  text('could')
 text(' be made to work')

This is nice.  I'll have to play around with it a bit to see how hard it 
would be to make it work.

STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding python and multiple separate scripts

2006-04-14 Thread Stefan D
Hi,

I'm trying to embed python into an chat bot I've made in c++. After 
googling around and reading docs for almost a day I have a few 
questions. First of all it seems like the best way to be able to run 
separate scripts in different, isolated environments is to create a 
sub-interpreter (by using Py_NewInterprete()) with an associated thread 
for each script/file. Or is this wrong?

The big problem I have is when I want to call a python function. When 
loading a script I use the following code:
 PyEval_AcquireLock(); // get global lock so we can create a new interpreter
 threadState = Py_NewInterpreter(); // create a new sub-interpreter and 
get a pointer to the first thread
 PyThreadState_Swap(threadState); // switch to our new thread state
 appModule = PyImport_AddModule(hostapp); // create a module for this 
program
 PyModule_AddIntConstant(appModule, SEVENTEEN, 17); // set a test constant
 FILE* fp = fopen(filename, r); // load the python script file
 PyRun_SimpleFile(fp, filename);
 fclose(fp);
 PyEval_ReleaseThread(threadState); // set current thread state to NULL 
and release global lock

When loading a script that contains:
 import hostapp
 print test: ,hostapp.SEVENTEEN

it prints out test: 17 nicely after the call to PyRun_SimpleFile(...). 
So far so good, but the problem starts when I try to call a python 
function from c++. Here's the code that isn't working:
 PyEval_AcquireThread(threadState);
 PyObject* func = PyDict_GetItemString(PyImport_GetModuleDict(), 
testfunc);
 if(PyCallable_Check(func)) {
   // never get this far
 }
 PyEval_ReleaseThread(threadState);

PyDict_GetItemString always return NULL for me, although I've defined 
the function as:
 def testfunc():
   print hi there

in the python file. Running PyRun_SimpleString(testfunc()\n) just 
after  PyEval_AcquireThread() works like a charm though. Any ideas? I 
kinda get the feeling that I don't get the dict from 
PyImport_GetModuleDict() that I'm expecting.

Thanks in advance..
/Stefan

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zlib and zip files

2006-04-14 Thread Michael Ekstrand
Jan Prochazka wrote:
 Hi,
 I need to decompress zip archive. I wrote a parser of zip file, i obtain
 the compressed data, but when i call zlib.decompress(data) on them,
 it throws this error:
 
 decbuf = decompressor.decompress(compressed_data)
 
 error: Error -3 while decompressing: unknown compression method
 
 I try to compress by zlib the same data which are in that file, the
 result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' on end
 when i tried to put this extending data to zlib decompressor, it
 decompress some files of zip archive, but it fails, when i try to
 decompress 100MB file from archive
 
 could you help, please?

The zlib module is for reading and writing the gzip compression format, 
used by the gzip program; it is not the same as a zip archive a la 
PKZip.  The zipfile module will let you read and write zip archives.

- Michael

-- 
mouse, n: a device for pointing at the xterm in which you want to type.
 -- Fortune
Visit me on the Web: http://www.elehack.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: requestion regarding regular expression

2006-04-14 Thread BartlebyScrivener
Kent,

Running

path = d:/emacs files/emacsinit.txt
lines = open(path).readlines()
# my defun lines are lowercase,
# next two lines are all on one
starts = [i for i, line in enumerate(lines) if
line.startswith('(defun')]
for i, start in starts:
while start  0 and lines[start-1].startswith(';'):
starts[i] = start = start-1
print starts

I get

File D:\Python\findlines.py, line 7, in __main__
for i, start in starts:
TypeError: unpack non-sequence

Also, I don't understand the i for i, but I don't understand a lot of
things yet :)

thanks,

rick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: requestion regarding regular expression

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 07:47 -0700, BartlebyScrivener escreveu:
 starts = [i for i, line in enumerate(lines) if
 line.startswith('(defun')]

This line makes a list of integers. enumerate gives you a generator that
yields tuples consisting of (integer, object), and by i for i, line
you unpack the tuple into (i, line) and pick just i.

 for i, start in starts:

Here you try to unpack the elements of the list starts into (i,
start), but as we saw above the list contains just i, so an exception
is raised. 

I don't know what you want, but...

starts = [i, line for i, line in enumerate(lines) if
line.startswith('(defun')]

or

starts = [x for x in enumerate(lines) if x[1].startswith('(defun')]

...may (or may not) solve your problem.

-- 
Felipe.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: zlib and zip files

2006-04-14 Thread Jan Prochazka
Michael Ekstrand napsal(a):

 Jan Prochazka wrote:

 Hi,
 I need to decompress zip archive. I wrote a parser of zip file, i obtain
 the compressed data, but when i call zlib.decompress(data) on them,
 it throws this error:

 decbuf = decompressor.decompress(compressed_data)

 error: Error -3 while decompressing: unknown compression method

 I try to compress by zlib the same data which are in that file, the
 result was 6 bytes bigger, '\x78\xda' on begin and '\xc9\x1f\x87\x0b' 
 on end
 when i tried to put this extending data to zlib decompressor, it
 decompress some files of zip archive, but it fails, when i try to
 decompress 100MB file from archive

 could you help, please?


 The zlib module is for reading and writing the gzip compression 
 format, used by the gzip program; it is not the same as a zip archive 
 a la PKZip.  The zipfile module will let you read and write zip archives.

 - Michael

Yes, zipfile can read zip format, but i need to read nad write big files 
to zip archive, and zipfile.ZipFile object can only write or read 
strings stored in memory. (i need the ZipFile.read() method to return 
file-like object, not string). also any variant of write method don't 
accpet file-like object
The gzip compressor and decompressor can work on the fly , but the 
format that it produces is a bit other than the format of compressed 
data zipfile (but it differs only in 6 bytes described, so i think, it 
shoud by possible to create and parse zipfile only using zlib module).

Here is my module for parsing zip files:

import struct, zlib

class ZipHeaderEntry:
name = ''
offset = 0
uncomlen = 0
comlen = 0
   
class ZipStream:
entries = []
fd = None # file like object
   
def __init__(self, fd):
self.fd = fd
self.entries = []

class ZipWriteStream(ZipStream):
pass

class ZipReadStream(ZipStream):
cbytesleft = 0
ubytesleft = 0
dec = None # decompress object
decbuf = None
writed_footer = False
   
def __init__(self, fd):
ZipStream.__init__(self, fd)
self.read_directory()

def open_entry(self, entry):
self.fd.seek(entry.offset)   
self.dec = zlib.decompressobj()
self.ubytesleft = entry.uncomlen
self.cbytesleft = entry.comlen
print 'ubytes=', self.ubytesleft, 'cbytes=', self.cbytesleft
self.read_header()
self.dec.decompress('\x78\xda', 0) # patch bytes on the begin of 
compressed buffer
self.decbuf = ''
self.writed_footer = False

def decompress_next(self):
assert len(self.decbuf) == 0
rbytes = 0x1000
if rbytes  self.cbytesleft: rbytes = self.cbytesleft
udata = self.fd.read(rbytes)
self.cbytesleft -= rbytes
self.decbuf = self.dec.decompress(udata)
if self.cbytesleft == 0 and not self.writed_footer:
self.decbuf += self.dec.decompress('\xc9\x1f\x87\x0b') # 
patch bytes on the end of compressed buffer
self.writed_footer = True

def read(self, bytes = None):
if bytes is None: bytes = self.ubytesleft
if bytes  self.ubytesleft: bytes = self.ubytesleft
res = ''
while bytes  0:
s = self.decbuf[:bytes]
self.decbuf = self.decbuf[bytes:]
self.ubytesleft -= len(s)
res += s
bytes -= len(s)
if bytes  0:
self.decompress_next()
return res

def open_file(self, filename):
for entry in self.entries:
if entry.name.upper() == filename.upper():
return self.open_entry(entry)
raise Exception('File not found in archive: %s' % filename)
   

def read_header(self):
hdr = self.fd.read(0x1E)
hdrvalues = struct.unpack('=HLLLHH', hdr)
sigp, sigk, sig3, sig4, ver, flag, method, tm, dt, crc, uncsize, 
comsize, fnlen, extlen = hdrvalues
assert sigp == 'P' and sigk == 'K' and sig3 == '\x03' and sig4 
== '\x04'
name = self.fd.read(fnlen)
extra = self.fd.read(extlen)
print name

def read_directory(self):
self.fd.seek(0, 2)
size = self.fd.tell()
dpos = 0x1000
if dpos  size: dpos = size
self.fd.seek(-dpos, 1)
enddata = self.fd.read()
index = enddata.find('PK\x05\x06')
assert index = 0
enddata = enddata[index: index + 0x16]
sig, ndisk, ndiskc, entriesdisk, entries, dirsize, dirofs, 
comlen = struct.unpack('=LLLH', enddata)
   
self.fd.seek(dirofs)

for i in xrange(entries):
cdirdata = self.fd.read(0x2E)
hdrvalues = struct.unpack('=LLLLHLL', cdirdata)
(sig, vermade, hosts, verex, osver, flag, method, dt, tm, crc,
csize, uncsize, fnlen, extlen, comlen, disknum, fileattr, 
extattr, fileofs) = hdrvalues
name = self.fd.read(fnlen)
extra = self.fd.read(extlen)
 

Re: zlib and zip files

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 17:14 +0200, Jan Prochazka escreveu:
 Here is my module for parsing zip files:

1) Have you checked the source of Python's zipfile module?

 import struct, zlib
 
 class ZipHeaderEntry:
 name = ''
 offset = 0
 uncomlen = 0
 comlen = 0

2) You know that those variables are *class* vars, not instance vars,
right?

3) I didn't read your code, but have you considered
http://pyconstruct.sourceforge.net/ ?

-- 
Felipe.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Iterating command switches from a data file - have a working solution but it seems inefficient

2006-04-14 Thread Larry Bates
News wrote:
 Hi everyone,
 
 My goal is to pull command switches/options from a file and then assign
 the values to select variables which would eventually be included in a
 class object.
 
 The data file looks something like this but the switches could be in any
 order and not all may be used.
 
 -m quemanager -s server -p port -k key -o object -c 20 -t [EMAIL PROTECTED]
 
 Also, please keep in mind that the source code will have more than one
 line in it and each has to be treaded separately.
 
 
 In a first pass, I wrote the following code which works but there is
 probably a better way of doing it.
 
 Any ideas to make it more efficient/stream-lined would be greatly
 appreciated.
 
 #!/usr/bin/python
 
 import string
 inp = open(const.txt,r)
 #
 # Read File
 #
 
 while True:
   
 #
 # Get line from file
 #
   line=inp.readline()
 
 #
 # Check for EOF or break line up to extract relevant pieces
 #
 if len(line) == 0:
   break
   else:
   split_line=line.split()
   length=len(split_line)
   count=0
   
 #
 # Evaluate list item and assign variable based on its contents
 # Print statements are for debugging purposes only
 #
   for i in range(length):
   if split_line[count] == -m:
   qmgr=split_line[count+1]
   print Queue Manager,qmgr;
   elif split_line[count] == -s:
   server=split_line[count+1]
   print Server,server;
   elif split_line[count] == -p:
   port=split_line[count+1]
   print Port,port;
   elif split_line[count] == -o:
   object=split_line[count+1]
   print Object,object;
   elif split_line[count] == -k:
   key=split_line[count+1]
   print Key,key;
   elif split_line[count] == -t:
   mto=split_line[count+1]
   print To,mto; 
   elif split_line[count] == -c:
   check=split_line[count+1]   
   print Check,check;
   elif split_line[count] == -d:
   report=
   print Report,report;
   elif split_line[count] == -q:
   display=False
   print Display,display;
   else:
   continue
   
   count=count+1
 
 # Close input file
 #
 inp.close()
 

Others have addressed your specific question.  I'm going to make
a different suggestion.  Change your thinking so that you can use
ConfigParser to get your values from a .INI/.CONF file instead.
The file would look something like:

[section001]
m=queuemanager
server=myserver
port=1080
key=somekey
object=someobject
c=20
[EMAIL PROTECTED]

[section002]
.
. If you have many of these just put things in a loop
. and process each section
.



You can then read with (not tested):

import ConfigParser
inifilename='program.ini'
INI=ConfigParser.ConfigParser()
INI.read(inifilename)
section='section001'
option='m'
try: m=INI.get(section, option)
except: m=None
option='server'
try: server=INI.get(section, option)
except: server=None
option='port'
try: port=INI.getint(section, option)
except: port=None # Or set to default port
option='key'
try: key=INI.get(section, option)
except: key=None
option='object'
try: object=INI.get(section, option)
except: object=None
option='c'
try: c=INI.getint(section, option)
except: c=None
option='emailtolist'
try: emailtolist=INI.get(section, option).split(';')
except: emailtolist=None


Just a suggestion.

-Larry Bates
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop with float increments (frange)?

2006-04-14 Thread Tim Peters
[EMAIL PROTECTED]
 what's the standard way for a for loop with float increments?

[Dan Sommers]
 Use a while loop instead:

 f = initial_value
 while f = final_value:
 process(f)
 f = f + increment

 Note that there is no general guarantee that f will actually be
 final_value; see also http://docs.python.org/tut/node16.html.

There's no guarantee that the `while` loop will execute the expected
number of times either, and it's generally a Bad Idea to do f +=
increment inside the loop:  the value of f suffers an additional
rounding error on each iteration that way, potentially making it drift
away from the expected value more  more as the loop goes on.

Standard careful numeric practice is this way:

n = compute the number of iterations you want to make in total
for i in xrange(n):
process(initial_value + i * increment)

Then each value computed suffers a total of only two rounding errors
(one for the multiply, one for the add), independent of how large `n`
may be, and doesn't get worse as the loop goes on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Steven Bethard
Steven Bethard wrote:
 Duncan Booth wrote:
 Steven Bethard wrote:

 Should users of the make statement be able to determine in which dict
 object the code is executed?  The make statement could look for a
 ``__make_dict__`` attribute and call it to allow things like::

  make Element html:
  make Element body:
  make Element h1:
  '''First heading text'''
  make Element h1:
  '''Second heading text'''

 [snip]
 There is another effect which should be considered here. If you allow 
 Element to create an object to be used as the namespace, then as well 
 as doing special tracking when values are set in the namespace it can 
 also pre-seed it with names which magically appear in scope within the 
 make.

 e.g.

 make Element html:
 make Element body:
 make Element p:
 text('But this ')
 make Element strong:
  text('could')
 text(' be made to work')
 
 This is nice.  I'll have to play around with it a bit to see how hard it 
 would be to make it work.

Okay, I think it'll work[1].  I'm going to update this section to 
something more like:


Open Issues
===

...

Should users of the make statement be able to determine in which dict
object the code is executed?  This would allow the make statement to
be used in situations where a normal dict object would not suffice,
e.g. if order and repeated names must be allowed. Allowing this sort
of customization could allow XML to be written like::

 make Element html:
 make Element body:
 text('before first h1')
 make Element h1:
 attrib(style='first')
 text('first h1')
 tail('after first h1')
 make Element h1:
 attrib(style='second')
 text('second h1')
 tail('after second h1')

 assert etree.ElementTree.tostring(body) == '''\
 html\
 body\
 before first h1\
 h1 style=firstfirst h1/h1\
 after first h1\
 h1 style=secondsecond h1/h1\
 after second h1\
 /body\
 /html\
 '''

Assuming that the make statement calls the callable's
``__make_dict__`` to get the dict in which to execute the code, the
following should make the above make statements work::

 class Element(object):

 class __make_dict__(dict):

 def __init__(self, *args, **kwargs):
 self._super = super(Element.__make_dict__, self)
 self._super.__init__(*args, **kwargs)
 self.elements = []
 self.text = None
 self.tail = None
 self.attrib = {}

 def __getitem__(self, name):
 try:
 return self._super.__getitem__(name)
 except KeyError:
 if name in ['attrib', 'text', 'tail']:
 return getattr(self, 'set_%s' % name)
 else:
 return globals()[name]

 def __setitem__(self, name, value):
 self._super.__setitem__(name, value)
 self.elements.append(value)

 def set_attrib(self, **kwargs):
 self.attrib = kwargs

 def set_text(self, text):
 self.text = text

 def set_tail(self, text):
 self.tail = text

 def __new__(cls, name, args, edict):
 get_element = etree.ElementTree.Element
 result = get_element(name, attrib=edict.attrib)
 result.text = edict.text
 result.tail = edict.tail
 for element in edict.elements:
 result.append(element)
 return result



[1] Here's the code I used to test it.

  def make(callable, name, args, block_string):
... try:
... make_dict = callable.__make_dict__
... except AttributeError:
... make_dict = dict
... block_dict = make_dict()
... exec block_string in block_dict
... return callable(name, args, block_dict)
...
  class Element(object):
... class __make_dict__(dict):
... def __init__(self, *args, **kwargs):
... self._super = super(Element.__make_dict__, self)
... self._super.__init__(*args, **kwargs)
... self.elements = []
... self.text = None
... self.tail = None
... self.attrib = {}
... def __getitem__(self, name):
... try:
... return self._super.__getitem__(name)
... except KeyError:
... if name in ['attrib', 'text', 'tail']:
... return getattr(self, 'set_%s' % name)
... else:
... return globals()[name]
... def __setitem__(self, name, value):
... self._super.__setitem__(name, value)
... self.elements.append(value)
... 

Re: jpype and zxJDBC

2006-04-14 Thread benchline
I haven't compared them, and you may be exacly right.

Paul

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editing with emacs/wordstar key bindings.

2006-04-14 Thread BartlebyScrivener
Yes, thanks. I was just going to reinstall anyway. That usually fixes
it.

Rick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 09:31 -0600, Steven Bethard escreveu:
 [1] Here's the code I used to test it.
 
   def make(callable, name, args, block_string):
 ... try:
 ... make_dict = callable.__make_dict__
 ... except AttributeError:
 ... make_dict = dict
 ... block_dict = make_dict()
 ... exec block_string in block_dict
 ... return callable(name, args, block_dict)
 ...
   (snip)

I think it would be nice not to put those  and ... to make copy
and paste easier. Okay, I know we can do .join(line[4:] for line in
text), but that's just my humble opinion.

-- 
Felipe.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: zlib and zip files

2006-04-14 Thread Jan Prochazka
Felipe Almeida Lessa napsal(a):

Em Sex, 2006-04-14 às 17:14 +0200, Jan Prochazka escreveu:
  

Here is my module for parsing zip files:



1) Have you checked the source of Python's zipfile module?
  

Nice, i thought, that zipfile is written in C, it should be possible to 
solve my problem using these sources, thanks very much

  

import struct, zlib

class ZipHeaderEntry:
name = ''
offset = 0
uncomlen = 0
comlen = 0



2) You know that those variables are *class* vars, not instance vars,
right?
  

yes i know, i use the fact, that class variables are implicit values for 
instance variables (also it is my style of documenting used instance 
variables and their types)

3) I didn't read your code, but have you considered
http://pyconstruct.sourceforge.net/ ?

  

i use python standard module struct, which solves it
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: requestion regarding regular expression

2006-04-14 Thread Kent Johnson
BartlebyScrivener wrote:
 Kent,
 
 Running
 
 path = d:/emacs files/emacsinit.txt
 lines = open(path).readlines()
 # my defun lines are lowercase,
 # next two lines are all on one
 starts = [i for i, line in enumerate(lines) if
 line.startswith('(defun')]
 for i, start in starts:
 while start  0 and lines[start-1].startswith(';'):
 starts[i] = start = start-1
 print starts
 
 I get
 
 File D:\Python\findlines.py, line 7, in __main__
 for i, start in starts:
 TypeError: unpack non-sequence

Sorry, should be
   for i, start in enumerate(starts):

start is a specific start line, i is the index of that start line in the 
starts array (so the array can be modified in place).

Kent
-- 
http://mail.python.org/mailman/listinfo/python-list


Including standalone=no in XML declaration

2006-04-14 Thread Stephen Briley
I'm trying to learn about Python and XML. I would like to be able
to add standalone=no to my xml declaration when writing an xml file,
but I am unable to figure out how. So far, I have the following
code:

import xml.dom.minidom
doc2 = xml.dom.minidom.Document()
print doc2.toxml('iso-8859-1')

Which produces the following XML declaration:
?xml version=1.0 encoding=iso-8859-1?

However, my goal is to have the XML declaration look like the following:
?xml version=1.0 encoding=iso-8859-1 
standalone=no ?

The following link mentions standalone as a Document class variable,
but I am unsure how to make this work or even if I am on the right
track.
http://epydoc.sourceforge.net/stdlib/private/_xmlplus.dom.minidom.Document-class.html#encoding

Any help would be greatly appreciated.

Thanks.

-- 
http://mail.python.org/mailman/listinfo/python-list

and ... (WAS PEP 359: The make Statement)

2006-04-14 Thread Steven Bethard
Felipe Almeida Lessa wrote:
  Em Sex, 2006-04-14 às 09:31 -0600, Steven Bethard escreveu:
  [1] Here's the code I used to test it.
 
def make(callable, name, args, block_string):
  ... try:
  ... make_dict = callable.__make_dict__
  ... except AttributeError:
  ... make_dict = dict
  ... block_dict = make_dict()
  ... exec block_string in block_dict
  ... return callable(name, args, block_dict)
  ...
(snip)
 
  I think it would be nice not to put those  and ... to make copy
  and paste easier. Okay, I know we can do .join(line[4:] for line in
  text), but that's just my humble opinion.

Depends what you're copying and pasting to.  In PythonWin, you have to 
have the ... , so I include it.

If you have an editor with block-select, you should just be able to 
select the appropriate section (ignoring the first four characters). 
TextPad is one such editor (on Windows), but I'm sure there are many 
others and hopefully if you're on Unix someone here can let you know 
what works there.

STeVe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list.clear() missing?!?

2006-04-14 Thread Steven D'Aprano
Raymond, I suspect we're not seeing eye to eye on this issue, but I do
appreciate you taking the time and effort. Thank you. My comments follow.

On Thu, 13 Apr 2006
09:34:46 -0700, Raymond Hettinger wrote:

 Both the pros and cons
 were quipped with abrupt perjoratives so the bullet points could be
 stated succinctly and with a bit of levity.  

Humour so often doesn't come across in text -- I didn't see the levity you
intended.


 request is inane -- A generation of python programmers has found
 list clearing to be like other parts of the language that you get used
 to very quickly and do not prove to be a problem in practice.  The
 request is in the same category as others which challenge api choices
 made 16 years ago; in particular, the decision to have compact APIs
 where the named methods do not duplicate functionality provided by
 syntax using operators and keywords. The request is less of a bug
 report and more a rejection of Guido's sense of design and his
 subsequent experience using his own language.

Of course it isn't a bug report. It's a feature request.

As for Guido's sense of design, in *this particular instance* I think he
got it wrong. That's hardly a rejection of the man's overall design skills.

In any case, as the creator of Python, Guido has never seen the language
with the eyes of a Python beginner. All the more credit to him for
creating a language which is simultaneously friendly to beginners and
powerful for experts. But he isn't superhuman, his experience is not the
only experience. (True, as BDFL, his experience has the final vote, but
that's a whole different kettle of fish.)

A bit of searching on Google finds this issue coming up frequently. It
seems to me that there is a steady stream of Python programmers asking
where's the list clear method?. Perhaps it isn't a monthly occurrence,
but it is still very common. That surely suggests that, as powerful
as slicing is, people aren't getting the connection between slicing and
emptying a list, and even when they do get it, many dislike it.

Since there is no evidence that these people are universally stupid, it
suggests strongly that the connection is too subtle. Some may protest that
the idiom is in the tutorial, that it is obvious once you know slicing and
del, but the fact is that many people aren't finding it obvious or
self-evident at all -- not even those who have read the tutorial.

Here is another possible solution: have the list.clear method be defined
this way:

def clear(self):
print Haven't you read the tutorial? Use del self[:] or self[:] = []

That at least will stop the procession of people asking how to clear a
list, and Fredrik won't have to spend his time telling them to read the
tutorial.

(Hey, if it's good enough for quit and exit... *wink*)


 A list.clear method will make deleting items from a list more OO,
 consistent with almost everything else you do to lists, and less
 procedural. This is especially true if clear() takes an optional index (or
 two), allowing sections of the list to be cleared, not just the entire
 list.
 
 Don't shoot yourself in the foot here.  If you want to advocate
 list.clear(), then you're hurting your chances by pushing for it to
 take an optional argument.  Essentially, this amounts to an
 unwillingness to use the del-keyword and to duplicate its functionality
 with a named method.

Deleting names from namespaces is conceptually distinct from deleting
components of compound objects like lists, and should be handled
differently: objects know their own contents, and can operate on
themselves, but they don't know what namespace they live in or what
name(s) they are known by. Deleting items from a list should be a case of
object, operate on yourself, just like remove, append and so on, and
hence should be specified by an object method, not a keyword like del.

So you are right: I am uncomfortable having del do double duty to both
delete names and operate on the internals of compound objects. It feels
wrong to me. If insert were a keyword (as in insert list[i:j], obj) it
would feel wrong to me too, and for the same reason.

I haven't been using Python for sixteen years, but at six years and
counting I'm not exactly a newbie. At first I accepted the del obj[:]
idiom implicitly -- the whole language was new to me, and it was no more
strange to me than any other Python syntax or idiom. But as I've got more
familiar with Python, the sense of two distinct concepts being
artificially forced into the same syntax has just gotten stronger.

As a pragmatist, I'd be happy to see a bare list.clear() method; that
would at least have the advantages of being easy to find with dir(list)
and accessible with help(). But as a purist, I really think it needs
optional arguments. Make of that what you will.



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Passing a packed C structure to a c module

2006-04-14 Thread Philippe Martin
Hi,

Is it possible to define a packed C structure in python and pass it to the c
module, or should the wrapper do that ?

Regards,

Philippe

-- 
http://mail.python.org/mailman/listinfo/python-list


instance variable weirdness

2006-04-14 Thread wietse
Hello,

I have written the following script to illustrate a problem in my code:

class BaseClass(object):
def __init__(self):
self.collection = []

class MyClass(BaseClass):
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection

if __name__ == '__main__':
seq = []
inst = None
for i in xrange(5):
inst = MyClass(str(i))
inst.collection.append(i)
seq.append(inst)
inst = None
for i in xrange(5):
inst = MyClass(str(i)+'~', [])
inst.collection.append(i)
seq.append(inst)
inst = None
for i in seq:
print Instance '%s'; collection = %s % (i.name,
str(i.collection))

The output I get is:

Instance '0'; collection = [0, 1, 2, 3, 4]
Instance '1'; collection = [0, 1, 2, 3, 4]
Instance '2'; collection = [0, 1, 2, 3, 4]
Instance '3'; collection = [0, 1, 2, 3, 4]
Instance '4'; collection = [0, 1, 2, 3, 4]
Instance '0~'; collection = [0]
Instance '1~'; collection = [1]
Instance '2~'; collection = [2]
Instance '3~'; collection = [3]
Instance '4~'; collection = [4]


I don't understand why the first loop doesn't give the same result as
the second loop. Can somebody enlighten me?

Wietse

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing a packed C structure to a c module

2006-04-14 Thread Martin v. Löwis
Philippe Martin wrote:
 Is it possible to define a packed C structure in python and pass it to the c
 module, or should the wrapper do that ?

You can create a packed structure using string concatenation, and with
the help of the struct module. However, this gives you a string object
in the end, which you still need to pass into your C library.

It is better to fill the struct in the wrapper.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: requestion regarding regular expression

2006-04-14 Thread BartlebyScrivener
That's it. Thank you! Very instructive.

Final:

path = d:/emacs files/emacsinit.txt
lines = open(path).readlines()
# next two lines all on one
starts = [i for i, line in enumerate(lines) if
line.startswith('(defun')]
for i, start in enumerate(starts):
while start  0 and lines[start-1].startswith(';'):
starts[i] = start = start-1
print starts

-- 
http://mail.python.org/mailman/listinfo/python-list


Fixing Python instalation in win2000 by hand

2006-04-14 Thread Sambo
Some time ago I bought a newer computer with W2000 already on it so I moved my 
old drive
to it as secondary( python was installed on non primary partition ).
Not sure if the .msi installers were broken before, but they are now (on this 
installation)
and the reason I can't move to brand new installation is because I am missing 
sound drivers.
I have copied 3 files from my d:\winnt\system32 (old C:) pywintypes24.dll, 
pythoncom24.dll
(mod 11/10/2004 4:26am) and python24.dll (mod 18/11/2004 6:55pm)
As a result I can now run python.exe but not pythonw.exe 
Is there anything else I need and what, if anything, should be in my PYTHONPATH
f:\Python24\Lib ? ?? Although if I type import os it has no problem.

Thanks in advance,

Sam 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance variable weirdness

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
 def __init__(self, name, collection=[]):

Never, ever, use the default as a list.

 self.collection = collection

This will just make a reference of self.collection to the collection
argument.

 inst.collection.append(i)

As list operations are done in place, you don't override the
self.collection variable, and all instances end up by having the same
list object.

To solve your problem, change 
def __init__(self, name, collection=[]):
BaseClass.__init__(self)
self.name = name
self.collection = collection # Will reuse the list
to
def __init__(self, name, collection=None):
BaseClass.__init__(self)
self.name = name
if collection is None:
collection = [] # Will create a new list on every instance
self.collection = collection


-- 
Felipe.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: instance variable weirdness

2006-04-14 Thread Felipe Almeida Lessa
Em Sex, 2006-04-14 às 13:30 -0300, Felipe Almeida Lessa escreveu:
 To solve your problem, change 
 def __init__(self, name, collection=[]):
 BaseClass.__init__(self)
 self.name = name
 self.collection = collection # Will reuse the list
 to
 def __init__(self, name, collection=None):
 BaseClass.__init__(self)
 self.name = name
 if collection is None:
 collection = [] # Will create a new list on every instance
 self.collection = collection

Or if None is valid in your context, do:

__marker = object()
def __init__(self, name, collection=__marker):
BaseClass.__init__(self)
self.name = name
if collection is __marker:
collection = [] # Will create a new list on every instance
self.collection = collection

-- 
Felipe.

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Passing a packed C structure to a c module

2006-04-14 Thread Philippe Martin
Thanks,

It's a pretty big structure: painfull to pass each item as a param.

Regards,

Philippe


Martin v. Löwis wrote:

 Philippe Martin wrote:
 Is it possible to define a packed C structure in python and pass it to
 the c module, or should the wrapper do that ?
 
 You can create a packed structure using string concatenation, and with
 the help of the struct module. However, this gives you a string object
 in the end, which you still need to pass into your C library.
 
 It is better to fill the struct in the wrapper.
 
 Regards,
 Martin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Rob Williscroft
Steven Bethard wrote in news:[EMAIL PROTECTED] 
in comp.lang.python:

 Open Issues
 ===
 
 Does the ``make`` keyword break too much code?  Originally, the make
 statement used the keyword ``create`` (a suggestion due to Nick
 Coghlan).  However, investigations into the standard library [4]_ and
 Zope+Plone code [5]_ revealed that ``create`` would break a lot more
 code, so ``make`` was adopted as the keyword instead.  However, there
 are still a few instances where ``make`` would break code.  Is there a
 better keyword for the statement?
 

I don't know wether this has been suggested or not, but 
what about def:

def namespace ns:
  x = 1

def type blah(object):
  pass

  def property x:
def get():
  return ns.x


Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Forms with multiple submit buttons vs 'form' objects with single 'submit' methods

2006-04-14 Thread neil . fitzgerald
Paul Rubin wrote:
 [EMAIL PROTECTED] writes:
Here's my question:  Suppose a form has more than one submit button.
  Now the COM 'form' object has a 'submit' method that doesn't take any
  arguments, so how do I tell it which button I want to press?

 What difference does it make?  Don't they all do the same thing?

Not in this case, no.

If you want to see an example of how the button you press might make a
difference, go to www.google.com.

What I'm dealing with, basically, is a form consisting of lots of
INPUT type=image name=whatever, value=whatever...  tags, which is
being used purely as a collection of links.  However, this arrangement
means that they don't appear as links in the document object's links
collection.

Now in the case of Google, the form contains a pair of 'items'
corresponding to the two buttons, and each item has a click method, and
so everything works out fine.  However, in the page I'm trying to
navigate, the form doesn't possess any 'items' whatsoever.

Anyway, it's seeming more and more likely to me that the page was
specifically designed to prevent anyone doing what I'm trying to do
(which is not in any way nefarious, but if I succeeded then it would
only take a small modification to make it very destructive indeed.)
Hence, I'm giving up.

Sorry for the waste of bandwidth.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 359: The make Statement

2006-04-14 Thread Nicolas Fleury
Felipe Almeida Lessa wrote:
 Em Sex, 2006-04-14 às 09:31 -0600, Steven Bethard escreveu:
 [1] Here's the code I used to test it.

   def make(callable, name, args, block_string):
 ... try:
 ... make_dict = callable.__make_dict__
 ... except AttributeError:
 ... make_dict = dict
 ... block_dict = make_dict()
 ... exec block_string in block_dict
 ... return callable(name, args, block_dict)
 ...
   (snip)
 
 I think it would be nice not to put those  and ... to make copy
 and paste easier. Okay, I know we can do .join(line[4:] for line in
 text), but that's just my humble opinion.
 

Note that there's a special paste in wxPython PyShell, with which you 
can copy/paste these lines.

Nicolas
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Passing a packed C structure to a c module

2006-04-14 Thread Martin v. Löwis
Philippe Martin wrote:
 It's a pretty big structure: painfull to pass each item as a param.

So how else would you like to pass them? Define the API you want,
and then just implement it. It still shouldn't require to define
the layout in Python.

Regards,
Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fixing Python instalation in win2000 by hand

2006-04-14 Thread BartlebyScrivener
 Not sure if the .msi installers were broken before,
 but they are now (on this installation)

Are you installing from c:\ ?

With administrator rights?

Check other requirements. It chokes if you are installing from another
logical drive, e.g., d:\

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html

rick

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested functions

2006-04-14 Thread bruno at modulix
Szabolcs Berecz wrote:
 On 14 Apr 2006 04:37:54 -0700, [EMAIL PROTECTED]
 [EMAIL PROTECTED] wrote:
 
def a():
  def b():
print b
  def c():
print c

how can i call c() ??
 
 
 Function c() is not meant to be called from outside function a().
 That's what a nested function is for: localizing it's usage and
 prevent cluttering the global namespace

There's actually more than this about Python's nested functions: they
can be returned from the outer function and then carry the environnement
in which they where created:

def trace(func):
fname = func.__name__

def traced(*args, **kw):
print calling func %s with *%s, **%s % (fname, str(args), kw)
try:
result = func(*args, **kw)
except Exception, e:
print %s raised %s % (fname, e)
raise
else:
print %s returned %s % (fname, str(result))
return result

return traced

def test(arg1, arg2='parrot'):
print in test, arg1 is %s % arg1
return arg2 * 3

test = trace(test)
test(42)


-- 
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: Passing a packed C structure to a c module

2006-04-14 Thread Philippe Martin
Well,

The call actually is an IOCtl: depending on the control code, the structure
has a different format.

Although the number of control codes/structures is finite, it would make the
wrapper function fairly large.

You seem to think that building the structure from python would be a
mistake: why is that ?

PS: the wrapper also has to work under multiple OSs

Regards,

Philippe





Martin v. Löwis wrote:

 Philippe Martin wrote:
 It's a pretty big structure: painfull to pass each item as a param.
 
 So how else would you like to pass them? Define the API you want,
 and then just implement it. It still shouldn't require to define
 the layout in Python.
 
 Regards,
 Martin

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Future Warning with Negative Int

2006-04-14 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 If I try to print a negative integer as a hexadecimal, I get the
 following error:

 print %X % -1
 __main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a
 signed string in Python 2.4 and up
 
 
 Does that mean that in the future it will say -1 or -?  

The future is now:

$ python2.4 -c 'print %X % -1'
-1

 Also, how do I suppress this warning?

With the -W option:

$ python2.3 -W ignore -c 'print %X % -1'


or warnings.filterwarnings('ignore').

http://docs.python.org/lib/warning-functions.html

has more on the subject.

Peter


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python editing with emacs/wordstar key bindings.

2006-04-14 Thread [EMAIL PROTECTED]
This is new to me. I did not know that emacs HAD a word star mode.
I may have to look at emacs again (last time was 1995).

I am still looking for a python editor I like. Yes I used to write asm
code in
wordstar in nondocument mode. And yes all of the old dos editors used
the wordstar keys. Everything by Borland used them.
Because of this I still use the 'joe' editor when I am on the command
line
and cooledit(with wstar like bindings) on X.
I like the features on other editors but I need my wstar keys.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: instance variable weirdness

2006-04-14 Thread Steven D'Aprano
On Fri, 14 Apr 2006 13:30:49 -0300, Felipe Almeida Lessa wrote:

 Em Sex, 2006-04-14 às 09:18 -0700, wietse escreveu:
 def __init__(self, name, collection=[]):
 
 Never, ever, use the default as a list.

Unless you want to use the default as a list.

Sometimes you want the default to mutate each time it is used, for example
that is a good technique for caching a result:

def fact(n, _cache=[1, 1, 2]):
Iterative factorial with a cache.
try:
return _cache[n]
except IndexError:
start = len(_cache)
product = _cache[-1]
for i in range(start, n+1):
product *= i
_cache.append(product)
return product


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list

Writing backwards compatible code

2006-04-14 Thread Steven D'Aprano
I came across an interesting (as in the Chinese curse) problem today. I
had to modify a piece of code using generator expressions written with
Python 2.4 in mind to run under version 2.3, but I wanted the code to
continue to use the generator expression if possible.

My first approach was to use a try...except block to test for generator
expressions:

try:
gen = (something for x in blah)
except SyntaxError:
def g():
for x in blah:
yield something
gen = g()


This failed to work under 2.3, because the SyntaxError occurs at compile
time, and so the try block never happens.

I've been burnt by making assumptions before, so I tried a second,
similar, approach:

if sys.version_info = (2, 4):
gen = (something for x in blah)
else:
# you know the rest

As expected, that failed too.

The solution which worked was to put the generator expression in a second
module, then import that:

try:
import othermodule
except SyntaxError:
# fall back code


What techniques do others use?


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


skip item in list for loop

2006-04-14 Thread Jacob Rael
I am new to python and I love it. I am hacking a file. I want to not
print a line if it contains the word 'pmos4_highv'. I also don't want
to print the next line. The following code works but it smells bad
and just doesn't look right. I was reading about generators. If I was
using one, I could do a .next() after the match and get rid of the
flags. Any suggestions how I can improve this?


inPmos= False

inFile = sys.stdin
fileList = inFile.readlines()

for line in fileList:
line = line.rstrip()
# Remove PMOS definitions - typically two lines. Screwed if only
one and last inst.
if inPmos:
inPmos = False
continue
if 'pmos4_highv' in line:
inPmos = True
continue


jr

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fixing Python instalation in win2000 by hand

2006-04-14 Thread Sambo
BartlebyScrivener wrote:
Not sure if the .msi installers were broken before,
but they are now (on this installation)
 
 
 Are you installing from c:\ ?
almost never
 
 With administrator rights?
 
pretty sure YES

 Check other requirements. It chokes if you are installing from another
 logical drive, e.g., d:\
 
 http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/installnotes.html
 
 rick
 

This problem is not limited to Python, Ja*va.* and MPLab.msi don't work either.
It was screwed up by some windows update , and never fixed by any additional 
updates.
Hmmm. I'll try from C: but.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >