Re: Need help with simple OOP Python question

2011-09-05 Thread Stephen Hansen
On 9/4/11 11:47 PM, Kristofer Tengström wrote:
> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables. The code looks like this:
> 
> -
> 
> class A:
> sub = dict()

You are sharing this single "sub" dictionary with all instances of your
A class.

If you want to define instance-specific attributes, define them in the
__init__ method, like so:

class A:
def __init__(self):
self.sub = dict()

def sub_add(self, cls):
obj = cls()
self.sub[obj.id] = obj

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with simple OOP Python question

2011-09-05 Thread Peter Otten
Kristofer Tengström wrote:

> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables. The code looks like this:
> 
> -
> 
> class A:
> sub = dict()

Putting it into the class like this means sub is shared by all instances.

> def sub_add(self, cls):
> obj = cls()
> self.sub[obj.id] = obj
> 
> class B(A):
> id = 'inst'
> 
> base = A()
> base.sub_add(B)
> base.sub['inst'].sub_add(B)
> 
> print # prints a blank line
> print base.sub['inst']
> print base.sub['inst'].sub['inst']
> 
> --
> 
> Now, what I get from this is the following:
> <__main__.B instance at 0x01FC20A8>
> <__main__.B instance at 0x01FC20A8>
> Why is this? What I want is for them to be two separate objects, but
> it seems like they are the same one. I've tried very hard to get this
> to work, but as I've been unsuccessful I would really appreciate some
> comments on this. I'm sure it's something really easy that I just
> haven't thought of.

Your class A needs an initialiser:

class A:
def __init__(self):
self.sub = {} # one dict per instance
# ...

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


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Steven D'Aprano
On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote:

> I am looking for the ability to create dynamic grids in a window but
> can't for the life of me find how to do this.

What GUI toolkit are you using?


-- 
Steven

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


Re: Need help with simple OOP Python question

2011-09-05 Thread Ben Finney
Kristofer Tengström  writes:

> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables.

That terminology is rather confused.

I think what you want is to have instances with their own attributes.

> class A:
> sub = dict()

This binds a single object (a new empty dict) to the class attribute
‘sub’. Every instance of class ‘A’ will share the same attribute, and
hence that same dict.

> def sub_add(self, cls):

This defines a function which will be bound to the class attribute
‘sub_add’. It will, when later called as a method, receive the instance
as the first parameter, bound to the local name ‘self’.

> obj = cls()
> self.sub[obj.id] = obj

Here, ‘self’ will be an instance of the ‘A’ class. Each instance has no
‘sub’ attribute, so Python will find the class attribute ‘A.sub’, shared
by all ‘A’ instances. You're then modifying that class attribute ‘A.sub’.

[…]

> Now, what I get from this is the following:
> <__main__.B instance at 0x01FC20A8>
> <__main__.B instance at 0x01FC20A8>
> Why is this?

I hope the above explains it.

> What I want is for them to be two separate objects, but it seems like
> they are the same one.

Yes. Anything you talk about in the class definition scope cannot know
about any instance of that class, since the instances don't exist yet.

Instead, instance attributes need to be bound to a particular instance,
which means you need to have a reference to the instance; that's what
‘self’ is for. The class initialiser is a method named ‘__init__’, and
is called on each newly-created instance before that instance is
returned from the constructor.

I advise you to work through the Python tutorial, beginning to end,
which will give you a good grounding in these and other fundamental
Python topics http://docs.python.org/tutorial/>. Work through each
example, understand it by experimenting, and then proceed to the next,
until you've done the lot.

-- 
 \ “If history and science have taught us anything, it is that |
  `\ passion and desire are not the same as truth.” —E. O. Wilson, |
_o__)  _Consilience_, 1998 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing WebDAV server

2011-09-05 Thread becky_lewis
>
> > Possibly.
> > I tried this:
> > server.py -n -c config.ini
> > Once again, the server is up and running and when I am logging in with my
> > browser (10.0.0.140:8081) I can see information showing up at the command
> > prompt, showing somebody is logging is, but the same error:
> > "fshandler:get_data: \Webdav not found". During starting up the server
> > mentioned: "pywebdav:Serving data from \Webdav".
>
> > In the config file it says:
> > "# main directory
> > directory = \Webdav"
>
> > Perhaps my Python configuration is at fault.
>
> > Fokke
>
> Is the path supposed to be absolute? In which case you'd need to have:
> directory=C:\path\to\Webdav
>
> instead of just
> directory=\Webdav
>
> I tried:
> directory=D:\Webdav
> directory=D:/Webdav
>
> To no avail.
> It didn.t make any difference.
>
> I surely believe my WebDAV installation is at fault.
>
> Fokke

Interestingly, looking at the code that returns the
"fshandler:get_data: \Webdav not found" message, it looks like it
tests that the path given exists and then tries an os.path.isfile,
then an os.path.isdir. If both fail you get the message that you see.
This might be a bit of a shot in the dark but could you try the path
with and without a trailing '/' or '\'? I don't currently have a
windows box available to test on and figure out why it would be
detected as existing but not test true for either a file or directory.

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


Re: Need help with simple OOP Python question

2011-09-05 Thread srinivas hn
Hi,
You are getting same object because you are overriding the dictionary
update.
Its printing the proper value with the last updated instance of B.

If you want to see the two different instances of class B give print
self.sub inside the sub_add method in class A.

CHEERS
CNA
9986229891


On Mon, Sep 5, 2011 at 12:17 PM, Kristofer Tengström wrote:

> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables. The code looks like this:
>
> -
>
> class A:
>sub = dict()
>def sub_add(self, cls):
>obj = cls()
>self.sub[obj.id] = obj
>
> class B(A):
>id = 'inst'
>
> base = A()
> base.sub_add(B)
> base.sub['inst'].sub_add(B)
>
> print # prints a blank line
> print base.sub['inst']
> print base.sub['inst'].sub['inst']
>
> --
>
> Now, what I get from this is the following:
> <__main__.B instance at 0x01FC20A8>
> <__main__.B instance at 0x01FC20A8>
> Why is this? What I want is for them to be two separate objects, but
> it seems like they are the same one. I've tried very hard to get this
> to work, but as I've been unsuccessful I would really appreciate some
> comments on this. I'm sure it's something really easy that I just
> haven't thought of.
>
> Python version is 2.6.5 (I'm using Panda3D to create a 2½D game).
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Simon Cropper

On 05/09/11 17:19, Steven D'Aprano wrote:

On Mon, 5 Sep 2011 03:18 pm Simon Cropper wrote:


I am looking for the ability to create dynamic grids in a window but
can't for the life of me find how to do this.


What GUI toolkit are you using?




I have looked at wxGlade, Boa Constructor, wxFormBuilder, tkinder, I 
have also looked through the Python website many times looking for 
commands that would allow me to create a GUI from scratch.


--
Cheers Simon

   Simon Cropper - Open Content Creator / Website Administrator

   Free and Open Source Software Workflow Guides
   
   Introduction   http://www.fossworkflowguides.com
   GIS Packages   http://gis.fossworkflowguides.com
   bash / Pythonhttp://scripting.fossworkflowguides.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Thomas Jollans
On 05/09/11 07:18, Simon Cropper wrote:
> I am looking for the ability to create dynamic grids in a window but
> can't for the life of me find how to do this.

It depends on which windowing toolkit you're planning to use. If you use
PyGTK, you'd want a TreeView widget to display the list. Fill a
ListStore instance with your data and give that to the TreeView. You can
implement filtering and sorting on top of that using TreeModelFilter and
TreeModelSort.

LibreOffice and OpenOffice have database management components (I
haven't used them, I assume they're somewhat similar to MS Access) - and
they can be scripted using Python. Depending on what you're doing, and
what you're planning to do in the future (re learning investment), that
might be worth looking into.

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


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Simon Cropper

On 05/09/11 20:40, Thomas Jollans wrote:

It depends on which windowing toolkit you're planning to use. If you use
PyGTK, you'd want a TreeView widget to display the list. Fill a
ListStore instance with your data and give that to the TreeView. You can
implement filtering and sorting on top of that using TreeModelFilter and
TreeModelSort.


I have look at most. I have no preference.

Are you able to point me to some resource material explaining how this 
can be done - e.g. a tutorial or manual?



LibreOffice and OpenOffice have database management components (I
haven't used them, I assume they're somewhat similar to MS Access) - and
they can be scripted using Python. Depending on what you're doing, and
what you're planning to do in the future (re learning investment), that
might be worth looking into.


'Base' is of no value in this regard. It is not really designed for this 
and there is a raging debate at the moment whether it will be maintained 
in the future. It also fails in that it requires predefined connections 
and forms to be established. It would not be possible to dynamically 
link to a table in a database (I have established ODBC links to a SQLite 
database, but the driver is an un-maintained draft). I also believe that 
the 'base' component in libreoffice/openoffice is a java implementation 
not python.


--
Cheers Simon

   Simon Cropper - Open Content Creator / Website Administrator

   Free and Open Source Software Workflow Guides
   
   Introduction   http://www.fossworkflowguides.com
   GIS Packages   http://gis.fossworkflowguides.com
   bash / Pythonhttp://scripting.fossworkflowguides.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread python
Hi Simon,

> I am a applications developer - originally from Windows using primarily 
Visual Foxpro, although I am familiar with a variety of other xbase 
derivatives. 

Check out dabodev.com. Dabo is a Python framework created by former VFP
developers.

Highly recommended.

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


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Simon Cropper

On 05/09/11 23:23, pyt...@bdurham.com wrote:

Check out dabodev.com. Dabo is a Python framework created by former VFP
developers.



Dabo is a great product. Spoke extensively with Ed Leafe and Paul 
McNett. Unfortunately the framework is not 'dynamic'. If you have an 
fixed database and tables it can quite quickly create a basic data entry 
setup and menu. Looks great when it runs. The problem is creating the 
window and grid on the fly.


I want a program that can be used to open any database and 'data mine' 
and extract table content. Dabo allows RAD for an established relational 
databases not unknown ones.


--
Cheers Simon

   Simon Cropper - Open Content Creator / Website Administrator

   Free and Open Source Software Workflow Guides
   
   Introduction   http://www.fossworkflowguides.com
   GIS Packages   http://gis.fossworkflowguides.com
   bash / Pythonhttp://scripting.fossworkflowguides.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help with simple OOP Python question

2011-09-05 Thread Peter Otten
Kristofer Tengström wrote:

> Thanks everyone, moving the declaration to the class's __init__ method
> did the trick. Now there's just one little problem left. I'm trying to
> create a list that holds the parents for each instance in the
> hierarchy. This is what my code looks like now:
> 
> -
> 
> class A:
> def __init__(self, parents=None):
> self.sub = dict()
> if parents:

You should explicitly test for None here; otherwise in a call like

ancestors = []
a = A(anchestors)

the list passed as an argument will not be used, which makes fore confusing 
behaviour.

> self.parents = parents
> else:
> self.parents = []
> def sub_add(self, cls):
> hierarchy = self.parents
> hierarchy.append(self)

Here you are adding self to the parents (that should be called ancestors) 
and pass it on to cls(...). Then -- because it's non-empty -- it will be 
used by the child, too, and you end up with a single parents list.

> obj = cls(hierarchy)
> self.sub[obj.id] = obj

While the minimal fix is to pass a copy

def sub_add(self, cls):
obj = cls(self.parents + [self])
self.sub[obj.id] = obj

I suggest that you modify your node class to keep track only of the direct 
parent instead of all ancestors. That makes the implementation more robust 
when you move a node to another parent.

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


Re: Need help with simple OOP Python question

2011-09-05 Thread Kristofer Tengström
Thanks everyone, moving the declaration to the class's __init__ method
did the trick. Now there's just one little problem left. I'm trying to
create a list that holds the parents for each instance in the
hierarchy. This is what my code looks like now:

-

class A:
def __init__(self, parents=None):
self.sub = dict()
if parents:
self.parents = parents
else:
self.parents = []
def sub_add(self, cls):
hierarchy = self.parents
hierarchy.append(self)
obj = cls(hierarchy)
self.sub[obj.id] = obj

class B(A):
id = 'inst'

base = A()
base.sub_add(B)
base.sub['inst'].sub_add(B)

print
print vars(base)
print
print vars(base.sub['inst'])
print
print vars(base.sub['inst'].sub['inst'])

-

The output from this program is the following:

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794B8>}}

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {'inst': <__main__.B instance at 0x021794E0>}}

{'parents': [<__main__.A instance at 0x02179468>, <__main__.B instance
at 0x021794B8>], 'sub': {}}

As you can see, the problem looks similar to the one before: All the
instances have an identical parent list. However, I don't understand
why as self.parents is declared in the __init__ method. Any ideas?
What I want is for the first instance to have an empty list, the
second to have one element in the list and the third to have two
parent elements.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do class methods always need 'self' as the first parameter?

2011-09-05 Thread Piet van Oostrum
Chris Torek  writes:

[snip]
> Instead, we have a syntax where you, the programmer, write out the
> name of the local variable that binds to the first parameter.  This
> means the first parameter is visible.  Except, it is only visible
> at the function definition -- when you have the instance and call
> the instance or class method:
>
> black_knight = K()
> black_knight.meth1('a', 1)
> black_knight.meth2(2)
>
> the first parameters (black_knight, and black_knight.__class__,
> respectively) are magic, and invisible.
>
> Thus, Python is using the "explicit is better than implicit" rule
> in the definition, but not at the call site.  I have no problem with
> this.  Sometimes I think implicit is better than explicit.  In this
> case, there is no need to distinguish, at the calls to meth1() and
> meth2(), as to whether they are "class" or "instance" methods.  At
> the *calls* they would just be distractions.

It *is* explicit also at the call site. It only is written at the left of the 
dot rather than at the right of the parenthesis. And that is necessary to 
locate which definition of the method applies. It would be silly to repeat this 
information after the parenthesis. Not only silly, it would be stupid as it 
would be a source of errors, and an example of DRY.
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread alex23
On Sep 5, 3:18 pm, Simon Cropper 
wrote:
> My investigations have generally found that windows/forms/data entry
> screen can be created for a specific table or view, but these are
> hard-wired during development. Is there anyway of rapidly defining the
> grid during runtime so any table can be viewed?

The commercial product Resolver One provides a grid/spreadsheet style
interface with Python scripting capabilities. I'm not sure of its
current licensing status but I believe it used to be free if used on
open source projects.

http://www.resolversystems.com/products/resolver-one/

Each spreadsheet itself is Python code; I think it should be quite do-
able to take something with introspective SQL capabilities like
SQLAlchemy and have it title columns and fill them with the correct
fields accordingly.

Hope this helps.


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


Re: Closures and Partial Function Application

2011-09-05 Thread Piet van Oostrum
Travis Parks  writes:

> I also like partial function application. What is the easiest way of
> achieving this in Python? Would it look something like this:
>
> def foo(x, y):
> return x + y
>
> xFoo = lambda y: foo(10, y)

from functools import partial
xfoo = partial(foo, 10)
-- 
Piet van Oostrum 
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing WebDAV server

2011-09-05 Thread Fokke Nauta
"becky_lewis"  wrote in message 
news:a7cd34d7-ed2b-4449-8edc-a6a45b59e...@hb5g2000vbb.googlegroups.com...
> >
>> > Possibly.
>> > I tried this:
>> > server.py -n -c config.ini
>> > Once again, the server is up and running and when I am logging in with 
>> > my
>> > browser (10.0.0.140:8081) I can see information showing up at the 
>> > command
>> > prompt, showing somebody is logging is, but the same error:
>> > "fshandler:get_data: \Webdav not found". During starting up the server
>> > mentioned: "pywebdav:Serving data from \Webdav".
>>
>> > In the config file it says:
>> > "# main directory
>> > directory = \Webdav"
>>
>> > Perhaps my Python configuration is at fault.
>>
>> > Fokke
>>
>> Is the path supposed to be absolute? In which case you'd need to have:
>> directory=C:\path\to\Webdav
>>
>> instead of just
>> directory=\Webdav
>>
>> I tried:
>> directory=D:\Webdav
>> directory=D:/Webdav
>>
>> To no avail.
>> It didn.t make any difference.
>>
>> I surely believe my WebDAV installation is at fault.
>>
>> Fokke
>
> Interestingly, looking at the code that returns the
> "fshandler:get_data: \Webdav not found" message, it looks like it
> tests that the path given exists and then tries an os.path.isfile,
> then an os.path.isdir. If both fail you get the message that you see.
> This might be a bit of a shot in the dark but could you try the path
> with and without a trailing '/' or '\'? I don't currently have a
> windows box available to test on and figure out why it would be
> detected as existing but not test true for either a file or directory.
>

Hi Becky,

I tried it straight away:
directory=D:\Webdav\
directory=D:/Webdav/

Didn't work, in both cases the same error "fshandler:get_data: \Webdav not 
found".

I have the opinion that my WebDAV installation is at fault. The database is 
not created either.
To have set up Python, I used python-2.7.2.msi.
To install WebDAV, I used PyWebDAV-0.9.4.1 and PyXML-0.8.4 packages, both 
Unix/Linux.
To install the, I used
"
>> You dont install from "Python GUI", use normal cmd, navigate to the 
>> folder
>> you downloaded PyXML and PyWebDAV and run "python setup.py install"
>> (python.exe has to be in your PATH). Then you have to find the
>> startup-script "davserver". Find your python installation directory and
>> look into/Tools/Scripts, in my computer this is
>> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the
>> site-packages folder i.e. E:\python27\Lib/site-packages. You might have 
>> to
>> look for "davserver" there..."

Shall I reïnstall the whole lot? Would it make a difference if in that case 
I would use ActivePython-2.7.2.5-win32-x86.msi instead of python-2.7.2.msi?

Fokke





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


Re: Need help with simple OOP Python question

2011-09-05 Thread Jon Clements
On Sep 5, 3:43 pm, Peter Otten <__pete...@web.de> wrote:
> Kristofer Tengström wrote:
> > Thanks everyone, moving the declaration to the class's __init__ method
> > did the trick. Now there's just one little problem left. I'm trying to
> > create a list that holds the parents for each instance in the
> > hierarchy. This is what my code looks like now:
>
> > -
>
> > class A:
> >     def __init__(self, parents=None):
> >         self.sub = dict()
> >         if parents:
>
> You should explicitly test for None here; otherwise in a call like
>
> ancestors = []
> a = A(anchestors)
>
> the list passed as an argument will not be used, which makes fore confusing
> behaviour.
>
> >             self.parents = parents
> >         else:
> >             self.parents = []
> >     def sub_add(self, cls):
> >         hierarchy = self.parents
> >         hierarchy.append(self)
>
> Here you are adding self to the parents (that should be called ancestors)
> and pass it on to cls(...). Then -- because it's non-empty -- it will be
> used by the child, too, and you end up with a single parents list.
>
> >         obj = cls(hierarchy)
> >         self.sub[obj.id] = obj
>
> While the minimal fix is to pass a copy
>
> def sub_add(self, cls):
>     obj = cls(self.parents + [self])
>     self.sub[obj.id] = obj
>
> I suggest that you modify your node class to keep track only of the direct
> parent instead of all ancestors. That makes the implementation more robust
> when you move a node to another parent.

I may not be understanding the OP correctly, but going by what you've
put here, I might be tempted to take this kind of stuff out of the
class's and using a graph library (such as networkx) - that way if
traversal is necessary, it might be a lot easier. But once again, I
must say I'm not 100% sure what the OP wants to achieve...

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


[OT] Anyone here familiar with installing Open Watcom F77?

2011-09-05 Thread W. eWatson

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


Best way to print a module?

2011-09-05 Thread Martin De Kauwe
Hi,

If I wanted to print an entire module, skipping the attributes
starting with "__" is there an *optimal* way? Currently I am doing
something like this. Note I am just using sys here to make the point

import sys

data = []
for attr in sys.__dict__.keys():
if not attr.startswith('__') and not attr.endswith('__'):
attr_val = getattr(sys, attr)
data.append((attr, attr_val))
data.sort()
for i in data:
print "%s = %s" % (i[0], i[1])

Clearly this would be quicker if I didn't store it and sort the
output, i.e.

for attr in sys.__dict__.keys():
if not attr.startswith('__') and not attr.endswith('__'):
attr_val = getattr(sys, attr)
print "%s = %s" % (attr, attr_val)

Anyway if there is a better way it would be useful to hear it...

Many thanks,

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


Re: [OT] Anyone here familiar with installing Open Watcom F77?

2011-09-05 Thread Chris Angelico
On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson  wrote:
> See Subject.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

To what extent "familiar"? I have it installed on several computers,
but only because it comes with Open Wat C/C++.

With something off-topic like this, it might be better to have a real
email address, so the responses can be off-list.

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


Re: Need help with simple OOP Python question

2011-09-05 Thread Peter Otten
Jon Clements wrote:

> I
> must say I'm not 100% sure what the OP wants to achieve...

Learn Python? 

;)

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


Re: [OT] Anyone here familiar with installing Open Watcom F77?

2011-09-05 Thread W. eWatson

On 9/5/2011 8:24 AM, Chris Angelico wrote:

On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson  wrote:

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



To what extent "familiar"? I have it installed on several computers,
but only because it comes with Open Wat C/C++.

With something off-topic like this, it might be better to have a real
email address, so the responses can be off-list.

ChrisA


sierra_mtnview @ sbcglobal.net
Here's the story.

As far as I can tell F77 1.8 is not available.  I've Googled quite a bit 
for it.  My source for 1.9 is 
. It gives me: 
open-watcom-f77-win32-1.9.exe.


When I install, there are only choices: Custom, which presumably will 
ask a lot of questions, and some one shot do-it without any 
intervention.  I took the latter.


..., XP, and no Win7? I use Win7. Trouble??

Something is amiss with my install. I downloaded 1.9. I did not use any 
customization.


 I can bring up the IDE easily. Using it is a different matter. The 
only Getting Started in F77 manual I can find is shown as v1.8.  If 1.9 
is needed, I can't find it. If I use the 1.8 manual, then the contents 
don't match up with what I find in the F77 IDE.  For example, the manual 
talks about a Kitchen project on page 15.  Not found anywhere in the 
install folder.


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


Re: [OT] Anyone here familiar with installing Open Watcom F77?

2011-09-05 Thread Dan Nagle

Hello,

On 2011-09-05 16:15:20 +, W. eWatson said:


On 9/5/2011 8:24 AM, Chris Angelico wrote:

On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson  wrote:

See Subject.





To what extent "familiar"? I have it installed on several computers,

but only because it comes with Open Wat C/C++.

With something off-topic like this,





sierra_mtnview @ sbcglobal.net

Here's the story.

As far as I can tell F77 1.8 is not available.  I've Googled quite a 
bit for it.  My source for 1.9 is 
. It gives me: 
open-watcom-f77-win32-1.9.exe.


On Usenet, comp.lang.fortran might be the best source of help for this.
There's a good chance one of the regulars there can answer you
within one or two posts.  (I'll not cross-post, you can choose for yourself.)

HTH

--
Cheers!

Dan Nagle

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


Re: [OT] Anyone here familiar with installing Open Watcom F77?

2011-09-05 Thread Colin J. Williams

On 05-Sep-11 12:22 PM, Dan Nagle wrote:

Hello,

On 2011-09-05 16:15:20 +, W. eWatson said:


On 9/5/2011 8:24 AM, Chris Angelico wrote:

On Tue, Sep 6, 2011 at 1:15 AM, W. eWatson
wrote:

See Subject.





To what extent "familiar"? I have it installed on several computers,

but only because it comes with Open Wat C/C++.

With something off-topic like this,





sierra_mtnview @ sbcglobal.net

Here's the story.

As far as I can tell F77 1.8 is not available. I've Googled quite a
bit for it. My source for 1.9 is
. It gives me:
open-watcom-f77-win32-1.9.exe.


On Usenet, comp.lang.fortran might be the best source of help for this.
There's a good chance one of the regulars there can answer you
within one or two posts. (I'll not cross-post, you can choose for
yourself.)

HTH



You might get in touch with someone at Waterloo University, which is 
located in Kitchener/Waterloo.


This could have come from the 60's or 70's.

Good luck.

Colin W.

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


Re: Best way to print a module?

2011-09-05 Thread rantingrick
On Sep 5, 10:06 am, Martin De Kauwe  wrote:
> Hi,
>
> If I wanted to print an entire module, skipping the attributes
> starting with "__" is there an *optimal* way? Currently I am doing
> something like this. Note I am just using sys here to make the point
>
> import sys
>
> data = []
> for attr in sys.__dict__.keys():
>     if not attr.startswith('__') and not attr.endswith('__'):
>         attr_val = getattr(sys, attr)
>         data.append((attr, attr_val))
> data.sort()
> for i in data:
>     print "%s = %s" % (i[0], i[1])
>
> Clearly this would be quicker if I didn't store it and sort the
> output, i.e.
>
> for attr in sys.__dict__.keys():
>     if not attr.startswith('__') and not attr.endswith('__'):
>         attr_val = getattr(sys, attr)
>         print "%s = %s" % (attr, attr_val)
>
> Anyway if there is a better way it would be useful to hear it...
>
> Many thanks,
>
> Martin

Martin, have you considered that your custom function is just re-
inventing the built-in dir() function? I would suggest using a list
comprehension against the dir() function with a predicate to remove
anything that startswith '_'. Here's some Ruby code to solve the
problem. I'll let you figure out the Python equivalent.

rb> ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'}
["whatsup"]

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


Re: Need help with simple OOP Python question

2011-09-05 Thread Terry Reedy

On 9/5/2011 9:15 AM, Kristofer Tengström wrote:

Thanks everyone, moving the declaration to the class's __init__ method
did the trick. Now there's just one little problem left. I'm trying to
create a list that holds the parents for each instance in the
hierarchy. This is what my code looks like now:

-

class A:
 def __init__(self, parents=None):
 self.sub = dict()
 if parents:
 self.parents = parents
 else:
 self.parents = []
 def sub_add(self, cls):
 hierarchy = self.parents
 hierarchy.append(self)
 obj = cls(hierarchy)
 self.sub[obj.id] = obj


Indexing objects by their internal id is usually useless. Considier 
whether you should be using sets rather than dicts.


--
Terry Jan Reedy


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


Re: Functions vs OOP

2011-09-05 Thread William Gill

On 9/4/2011 9:13 AM, rusi wrote:

On Sep 3, 9:15 pm, William Gill  wrote:

During some recent research, and re-familiarization with Python, I came
across documentation that suggests that programming using functions, and
programming using objects were somehow opposing techniques.


Staying with (for the moment) the suggestion that OO-P and F-P are
complementary, I believe it is worthwhile to distinguish syntactic OO-
P vs F-P from semantic OO-P vs F-P.

Syntactically: f(x) is functional x.f() is object oriented.
Semantically if f's return value depends only on x ie does not depend
on state it is functional (in the math sense) -- the jargon is that f
is referentially transparent.


Not to split hairs, but syntactically f(x) is a function in many 
programming paradigms.


As I understand it functional programming places specific requirements 
on functions, i.e.referential transparency.  So f(x) may or may not be 
"functional".


x.f() is also a function, but it is a member of the object x, is 
referred to as a 'method' of x, and uses the syntactical "dot" notation 
object"dot"function for identification.



Referential opaqueness is usually such a source of problems that it
turns out good to contain the problem somewhat -- hence the wish for
encapsulation.

One can find in the python library itself all 4 combinations:
syntactically and semantically OO : sort
syntactically and semantically FP: sorted
syntactically OO semantically FP: join


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


Re: Functions vs OOP

2011-09-05 Thread William Gill

On 9/3/2011 12:25 PM, Steven D'Aprano wrote:

William Gill wrote:


Are they suggesting that any function that takes an object as an
argument should always be a method of that object?


Yes.


I can think of times when a special application, such as a converter, 
would take an object as an argument, but the somewhat unique nature of 
the application wouldn't justify changing the class to make the behavior 
into a method.


I could extend the underlying class to include the new behavior 
(method), but that would mean existing instances of the base class would 
need conversion to the new class, requiring yet another method.


Seems to me, that would be POOP (Puristic Object Oriented Programming) ;-)

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


Re: Functions vs OOP

2011-09-05 Thread Jean-Michel Pichavant

William Gill wrote:


Not to split hairs, but syntactically f(x) is a function in many 
programming paradigms.


As I understand it functional programming places specific requirements 
on functions, i.e.referential transparency.  So f(x) may or may not be 
"functional".


x.f() is also a function, but it is a member of the object x, is 
referred to as a 'method' of x, and uses the syntactical "dot" 
notation object"dot"function for identification.




Functional programming is not about writing a programm with functions 
(google it for more info). This may cause some confusion.


Your original post was about functions vs methods, which are identical 
except some syntax detail. FYI, in python x.f() is equivalent to f(x). 
In an OOP world one will  prefer the x.f() form.



JM



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


Re: Best way to print a module?

2011-09-05 Thread Tim Roberts
Martin De Kauwe  wrote:
>
>If I wanted to print an entire module, skipping the attributes
>starting with "__" is there an *optimal* way? 

Your question is somewhat ambiguous.  When I read "print an entire module",
I assumed you were asking for a way to print the source code, perhaps with
syntax coloring.

Surely there is no reason to have an "optimal" method of doing this -- this
is never going to be in an inner loop.  If you have a method that works,
there is little justification to optimize...
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


One line command line filter

2011-09-05 Thread Jon Redgrave
It seems unreasonably hard to write simple one-line unix command line
filters in python:

eg: ls | python -c "  print x.upper()"

to get at sys.stdin or similar needs an import, which makes a
subsequent for-loop illegal.
python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError

Am I missing something obvious?

The best I've come up with is to use sitecustomize.py to add to
__builtin__
def stdin():
  import sys
  for x in sys.stdin():
if not x: return
yield x.strip()
import __builtin__
__builtin__.stdin = stdin

This allows
ls | python -c "for x in stdin(): print x.upper()"

Is there a better solution - if not is this worth a PEP?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-05 Thread Thomas Jollans
On 05/09/11 22:38, Jon Redgrave wrote:
> It seems unreasonably hard to write simple one-line unix command line
> filters in python:
> 
> eg: ls | python -c "  print x.upper()"
> 
> to get at sys.stdin or similar needs an import, which makes a
> subsequent for-loop illegal.
> python -c "import sys; for x in sys.stdin(): print x" <<- SyntaxError
> 
> Am I missing something obvious?

ls | python -c "for line in __import__('sys').stdin: print (line.upper())"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-05 Thread Jon Redgrave
> > Am I missing something obvious?
>
> ls | python -c "for line in __import__('sys').stdin: print (line.upper())"

Ah, so I am missing something - it is possible - but 'obvious'?
Do people think it should be more accessible
-- 
http://mail.python.org/mailman/listinfo/python-list


Running Python Demo on the Web?

2011-09-05 Thread Python Fiddle Admin
Python has been ported to the web browser at pythonfiddle.com. Python
Fiddle can import snippets of code that you are reading on a web page
and run them in the browser. It supports a few popular libraries.

Another common usage is to post code on the site to allow other people
to play around with it. Also, it can be used to demonstrate a working
program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-05 Thread Terry Reedy

On 9/5/2011 4:38 PM, Jon Redgrave wrote:

It seems unreasonably hard to write simple one-line unix command line
filters in python:

eg: ls | python -c "   print x.upper()"

to get at sys.stdin or similar needs an import, which makes a
subsequent for-loop illegal.
python -c "import sys; for x in sys.stdin(): print x"<<- SyntaxError

Am I missing something obvious?


The doc says "-c 
Execute the Python code in command. command can be one or more 
statements separated by newlines,"


However, I have no idea how to put newlines into a command-line string. 
Changing '; ' to '\n' does not work, at least not in Windows. The '\n' 
is passed on to Python as 2 chars, and the '\' is seen as the 
line-continuation char and the 'n' as illegal following it. Will a *nix 
shell 'cook' the string and convert '\n' to a literal newline before 
passing it to Python?


For *nix, I would expect the  Is there a better solution - if not is this worth a PEP?

PEPs have to propose a concrete solution, preferably with some previous 
discussion. I take is that your proposal would be to add another builtin 
means to access stdin.


--
Terry Jan Reedy

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


Re: Functions vs OOP

2011-09-05 Thread Terry Reedy

On 9/5/2011 1:45 PM, William Gill wrote:

On 9/4/2011 9:13 AM, rusi wrote:

On Sep 3, 9:15 pm, William Gill wrote:

During some recent research, and re-familiarization with Python, I came
across documentation that suggests that programming using functions, and
programming using objects were somehow opposing techniques.


Staying with (for the moment) the suggestion that OO-P and F-P are
complementary, I believe it is worthwhile to distinguish syntactic OO-
P vs F-P from semantic OO-P vs F-P.

Syntactically: f(x) is functional x.f() is object oriented.
Semantically if f's return value depends only on x ie does not depend
on state it is functional (in the math sense) -- the jargon is that f
is referentially transparent.


Not to split hairs, but syntactically f(x) is a function in many
programming paradigms.

As I understand it functional programming places specific requirements
on functions, i.e.referential transparency. So f(x) may or may not be
"functional".


In Python, it may be a parameterized procedure. Some languages separate 
functions and procedures (also called subroutines). Python does not. 
(Or you could say that it makes procedures into functions with 
side-effects by returning None by default).



x.f() is also a function, but it is a member of the object x, is
referred to as a 'method' of x, and uses the syntactical "dot" notation
object"dot"function for identification.


Referential opaqueness is usually such a source of problems that it
turns out good to contain the problem somewhat -- hence the wish for
encapsulation.

One can find in the python library itself all 4 combinations:
syntactically and semantically OO : sort
syntactically and semantically FP: sorted
syntactically OO semantically FP: join





--
Terry Jan Reedy

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


Re: One line command line filter

2011-09-05 Thread Terry Reedy

On 9/5/2011 5:32 PM, Jon Redgrave wrote:

Am I missing something obvious?


ls | python -c "for line in __import__('sys').stdin: print (line.upper())"


Ah, so I am missing something - it is possible - but 'obvious'?
Do people think it should be more accessible


__import__ is well-documented and is listed in the index of the builtin 
functions chapter. "Direct use of __import__() is rare, except in cases 
where you want to import a module whose name is only known at runtime." 
could be explanded to include "or where you want to import as part of an 
expression"


Every Python programmer should peruse that chapter to learn what is 
available for possible future use.


--
Terry Jan Reedy

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


Re: Best way to print a module?

2011-09-05 Thread Martin De Kauwe
Hi,

Tim yes I had a feeling my posting might be read as ambiguous! Sorry I
was trying to quickly think of a good example. Essentially I have a
set of .ini parameter files which I read into my program using
configobj, I then replace the default module parameters if the user
file is different (in my program). When it comes to writing the data
back out I need to potentially loop over 5 module files and I need to
ignore the superfluous information. My guess is that the way I am
doing it might be a little on the slow side, hence the posting. Like
you said it might be that the way I am doing it is "fine", I just
wanted to see if there was a better way that is all.

Rantingrick I did actually try the dir() to start with, I can't
remember why I changed back. I will try your suggestion and see
(thanks)

So instead of sys as per my example my module more realistically looks
like this:

params.py

apples = 12.0
cats = 14.0
dogs = 1.3

so my fuller example then

import sys
sys.path.append("/Users/mdekauwe/Desktop/")
import params

#params.py contains
#apples = 12.0
#cats = 14.0
#dogs = 1.3

fname = "test.asc"
try:
ofile = open(fname, 'w')
except IOError:
raise IOError("Can't open %s file for write" % fname)

data = []
for attr in params.__dict__.keys():
if not attr.startswith('__') and not attr.endswith('__'):
attr_val = getattr(params, attr)
data.append((attr, attr_val))

data.sort()
try:
ofile.write("[params]\n")
for i in data:
ofile.write("%s = %s\n" % (i[0], i[1]))
except IOError:
raise IOError("Error writing params files, params section")


etc, etc
thanks

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


Re: Hello, and request for help with 'dynamic grids'

2011-09-05 Thread Simon Cropper

On 06/09/11 00:40, alex23 wrote:

On Sep 5, 3:18 pm, Simon Cropper
wrote:

My investigations have generally found that windows/forms/data entry
screen can be created for a specific table or view, but these are
hard-wired during development. Is there anyway of rapidly defining the
grid during runtime so any table can be viewed?


The commercial product Resolver One provides a grid/spreadsheet style
interface with Python scripting capabilities. I'm not sure of its
current licensing status but I believe it used to be free if used on
open source projects.

http://www.resolversystems.com/products/resolver-one/

Each spreadsheet itself is Python code; I think it should be quite do-
able to take something with introspective SQL capabilities like
SQLAlchemy and have it title columns and fill them with the correct
fields accordingly.

Hope this helps.




Alex,

The Resolver Package looks good. Not exactly open source though. I 
equate it to a proprietary package that can at times be used for free by 
select groups.


The product creates spreadsheets with python code in the background 
(instead of say VBA in Excel or Basic in Calc).


Access to a database still needs to be hard-wired, so it does not act as 
a 'dynamic' viewer. The product works pretty much like Excel and Calc in 
this manner.


Sheets can be shared, although the Resolver Exchange website does not 
clarify the licence under which samples are released (GPL, CC, etc), so 
it is debatable how any of this could reliably be used in creation of 
derivatives.


From what I can glean from this page...

 http://www.resolversystems.com/opensource/

 ... Resolver will allow you to use the package if you are an open 
source project to create spreadsheets that can be redistributed. For 
people to use these sheets they need to download the viewer or purchase 
the package.


--
Cheers Simon

   Simon Cropper - Open Content Creator / Website Administrator

   Free and Open Source Software Workflow Guides
   
   Introduction   http://www.fossworkflowguides.com
   GIS Packages   http://gis.fossworkflowguides.com
   bash / Pythonhttp://scripting.fossworkflowguides.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-05 Thread Steven D'Aprano
Terry Reedy wrote:

> The doc says "-c 
> Execute the Python code in command. command can be one or more
> statements separated by newlines,"
> 
> However, I have no idea how to put newlines into a command-line string.

I imagine that it depends on the shell you are using, but bash on Linux
makes it simple: double quotes "..." are like Python's triple-quoted
strings in that they can include newlines.

[steve@sylar python]$ ls f*.py | python -c "import sys
> print sys.stdin.read()"
factorial.py
fetchqm.py
fib.py
fileutils.py
findsingle.py
fixascii.py
fix.py
frange.py
frequencies.py


Other shells may be different.


-- 
Steven

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


Re: Best way to print a module?

2011-09-05 Thread Martin De Kauwe
Trying to follow the suggestion this would be the alternate
implementation.

import sys
sys.path.append("/Users/mdekauwe/Desktop/")
import params

#params.py contains
#apples = 12.0
#cats = 14.0
#dogs = 1.3

fname = "test.asc"
try:
ofile = open(fname, 'w')
except IOError:
raise IOError("Can't open %s file for write" % fname)

attributes = [attr for attr in dir(params) if not
attr.startswith('__')]
attributes.sort()

try:
ofile.write("[params]\n")
for i in attributes:
ofile.write("%s = %s\n" % (i, getattr(params, i)))
except IOError:
raise IOError("Error writing params files, params section")

Is that a better version? I honestly don't know.

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


Re: One line command line filter

2011-09-05 Thread Steven D'Aprano
Jon Redgrave wrote:

> It seems unreasonably hard to write simple one-line unix command line
> filters in python:
> 
> eg: ls | python -c "  print x.upper()"

Python is neither bash nor Perl. It is not intended to compete in the "quick
and dirty one-liner commands" stakes.

However, you might like to consider ipython, which is intended as a complete
Python shell, not just an interactive interpreter.

http://ipython.org/


[...]
> The best I've come up with is to use sitecustomize.py to add to
> __builtin__

If you're a system administrator who wants to replace bash one-liners at the
command line with Python one-liners, sure, why not?

If you build up a useful collection of sys admin tools or recipes, you might
like to consider sharing them. Perhaps if Python was used more by sys
admins, there might be less resistance to making it easier to compete with
bash one-liners.


-- 
Steven

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


Re: Best way to print a module?

2011-09-05 Thread Steven D'Aprano
Tim Roberts wrote:

> Martin De Kauwe  wrote:
>>
>>If I wanted to print an entire module, skipping the attributes
>>starting with "__" is there an *optimal* way?
> 
> Your question is somewhat ambiguous.  When I read "print an entire
> module", I assumed you were asking for a way to print the source code,
> perhaps with syntax coloring.
> 
> Surely there is no reason to have an "optimal" method of doing this --
> this is never going to be in an inner loop.

Regardless of an inner loop or not, the time required for IO (reading the
file from disk, writing it to a printer) will be much larger than the time
required to skip dunder (double-underscore) objects.

> If you have a method that works, 
> there is little justification to optimize...

Pretty much.

HOWEVER, having agreed with you in general, in this specific case it is
obvious to me from context that the OP doesn't want to print the source
code of the module, but the module's names and their values.

I'd try a couple of approaches:

- use dir() or vars() to get the module's names, then loop and print each
one;

- make a shallow copy of the module __dict__, less dunder names, and pass it
to the prettyprint module for printing.



-- 
Steven

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


Re: Functions vs OOP

2011-09-05 Thread William Gill

On 9/5/2011 3:04 PM, Jean-Michel Pichavant wrote:

William Gill wrote:


Not to split hairs, but syntactically f(x) is a function in many
programming paradigms.

As I understand it functional programming places specific requirements
on functions, i.e.referential transparency. So f(x) may or may not be
"functional".

x.f() is also a function, but it is a member of the object x, is
referred to as a 'method' of x, and uses the syntactical "dot"
notation object"dot"function for identification.



Functional programming is not about writing a programm with functions
. This may cause some confusion.


It can, and it did.  That was the impression I (incorrectly) got from 
the documentation.  Which didn't make sense to me.




(google it for more info).


I can, and I did.  That, and the answers I got in this ng are how I 
corrected my misconception.




Your original post was about functions vs methods, which are identical
except some syntax detail. FYI, in python x.f() is equivalent to f(x).
In an OOP world one will prefer the x.f() form.

No, my original post was about how (based on the aforementioned 
misconception) the documentation seemed to suggest that OOP should never 
have free standing functions, only methods.


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


Re: Why do class methods always need 'self' as the first parameter?

2011-09-05 Thread Chris Torek
>Chris Torek  writes:
>[snip]
>> when you have [an] instance and call [an] instance or class method:

[note: I have changed the names very slightly here, and removed
additional arguments, on purpose]

>> black_knight = K()
>> black_knight.spam()
>> black_knight.eggs()
>>
>> the first parameters ... are magic, and invisible.
>>
>> Thus, Python is using the "explicit is better than implicit" rule
>> in the definition, but not at the call site. ...

In article 
Piet van Oostrum   wrote:
>It *is* explicit also at the call site. It only is written at the left
>of the dot rather than at the right of the parenthesis.

It cannot possibly be explicit.  The first parameter to one of the
method functions is black_knight, but the first parameter to the
other method is black_knight.__class__.

Which one is which?  Is spam() the instance method and eggs() the
class method, or is spam() the class method and eggs the instance
method?  (One does not, and should not, have to *care*, which is
kind of the point here. :-) )

>And that is necessary to locate which definition of the method
>applies.

By "that" I assume you mean the name "black_knight" here.  But the
name is not required to make the call; see the last line of the
following code fragment:

funclist = []
...
black_knight = K()
funclist.append(black_knight.spam)
funclist.append(black_knight.eggs)
...
# At this point, let's say len(funclist) > 2,
# and some number of funclist[i] entries are ordinary
# functions that have no special first parameter.
random.choice(funclist)()

>It would be silly to repeat this information after the parenthesis.
>Not only silly, it would be stupid as it would be a source of errors,
>and an example of DRY.

Indeed.  But I believe the above is a demonstration of how the
"self" or "cls" parameter is in fact implicit, not explicit.

(I am using python 2.x, and doing this in the interpreter:

random.choice(funclist)

-- without the parentheses to call the function -- produces:

>
>


The first is the instance method, whose name I am still keeping
secret; the second is the class method; and the third is the ordinary
function I added to the list.  The actual functions print their
own name and their parameters if any, and one can see that the
class and instance methods get one parameter, and the ordinary
function gets none.)
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One line command line filter

2011-09-05 Thread Terry Reedy

On 9/5/2011 7:18 PM, Steven D'Aprano wrote:

Terry Reedy wrote:


The doc says "-c
Execute the Python code in command. command can be one or more
statements separated by newlines,"

However, I have no idea how to put newlines into a command-line string.


I imagine that it depends on the shell you are using, but bash on Linux
makes it simple: double quotes "..." are like Python's triple-quoted
strings in that they can include newlines.

[steve@sylar python]$ ls f*.py | python -c "import sys

print sys.stdin.read()"

factorial.py
fetchqm.py


I was guessing that whoever wrote the doc could do something like that. 
As far as I know, there is no way to escape a newline with Windows 
cmd.exe. (Someone please tell me if I am wrong!) An "unmatched" quote is 
either ignored or matched by the newline!


C:\Programs\Python32> python -c "print('haha')
haha

--
Terry Jan Reedy

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


Re: Why do class methods always need 'self' as the first parameter?

2011-09-05 Thread rantingrick
On Aug 31, 9:35 am, "T. Goodchild"  wrote:
> I’m new to Python, and I love it.  The philosophy of the language (and
> of the community as a whole) is beautiful to me.

Welcome aboard mate!

> But one of the things that bugs me

Oh here we go! :-)

>  is the requirement that all class
> methods have 'self' as their first parameter.  On a gut level, to me
> this seems to be at odds with Python’s dedication to simplicity.

It will will seem odd at first. I too hated typing all those "selfs"
all the time. But believe me my new friend in no time those selfs will
roll of your fingers with great ease. You'll forget how much you hate
them and find much more to complain about.

Like for instance: I really lament the missing redundancy of Explicit
Lexical Scoping in python. For me global variables should have to be
qualified.

> For example, consider Python’s indent-sensitive syntax.  
> [...]
> and the result was a significantly improved
> signal-to-noise ratio in the readability of Python code.

Yes, forced indention is my favorite aspect of Python!

> So why is 'self' necessary on class methods?

It could be that Guido has a exaggerated self importance and just
liked the sound of all those selfs whist reading source code. However
i believe the real reason is really readability! It takes a while to
understand this aspect because the natural human response is to be
lazy (for instance i could have used "used to" in the previous
sentence if i was slothful). We are all inherently lazy beings who
need structure to keep us from spiraling out of control into the abyss
of selfishness.

GvR: Computer Scientist and Behavioral psychologist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do class methods always need 'self' as the first parameter?

2011-09-05 Thread Steven D'Aprano
On Tue, 6 Sep 2011 11:10 am Chris Torek wrote:

>>> black_knight = K()
>>> black_knight.spam()
>>> black_knight.eggs()
>>>
>>> the first parameters ... are magic, and invisible.
>>>
>>> Thus, Python is using the "explicit is better than implicit" rule
>>> in the definition, but not at the call site. ...
> 
> In article 
> Piet van Oostrum   wrote:
>>It *is* explicit also at the call site. It only is written at the left
>>of the dot rather than at the right of the parenthesis.
> 
> It cannot possibly be explicit.  The first parameter to one of the
> method functions is black_knight, but the first parameter to the
> other method is black_knight.__class__.


I think you are expecting more explicitness than actually required. There
are degrees of explicitness:

- The current President of the United States is a black man.

- On 6th September 2011, the duly constituted President of the United 
  States of America is a black man.

- On 6th September 2011, the duly constituted government official with 
  the title of President of the nation known as the United States of 
  America is an individual member of the species Homo sapiens with XY
  chromosomes and of recent African ancestry.

As opposed to implicit:

- He is a black guy.


There is no requirement for every last gory detail to be overtly specified
in full. I quote from WordNet:

explicit
 adj 1: precisely and clearly expressed or readily observable;
leaving nothing to implication; "explicit
instructions"; "she made her wishes explicit";
"explicit sexual scenes" [syn: expressed] [ant: implicit]
 2: in accordance with fact or the primary meaning of a term
[syn: denotative]

Note the second definition in particular: in accordance with the primary
meaning of a term: the primary meaning of "class method" is that it
receives the class rather than the instance as first argument.

The "explicit is better than implicit" Zen should, in my opinion, be best
understood as a recommendation that code should, in general, avoid getting
input from context. In general, functions should avoid trying to decide 
which behaviour is wanted according to context or the environment:

def func(x):
if running_in_a_terminal():
print "The answer is", (x+1)/2
else:
printer = find_a_printer()
if printer is not None:
printer.send((x+1)/2, header="func(%r)"%x, footer="Page 1")
else:
# Try sending email to the current user, the default user,
# postmaster or root in that order.
msg = make_email("The answer is", (x+1)/2)
for user in [get_current_user(), DEFAULT_USER, 
 "root@localhost.localdomain", ...]:
result = send_mail(msg, to=user)
if result == 0: break
 else:
# Fall back on beeping the speakers in Morse code
... 

(what if I want to beep the speakers from the terminal?), but not as a
prohibition against code like this:

def factorial(x):
# Return the factorial of the integer part of x.
n = int(x)
if n <= 1: return 1
return n*factorial(n-1)


There's no need to require the user to explicitly call int(x) before calling
factorial just to satisfy the Zen.

A function is free to process arguments as required, even to throw out
information (e.g. float -> int, instance -> class). What it shouldn't do is
*add* information implied by context (or at least, it should be very
cautious in doing so, and document it carefully, and preferably allow the
caller to easily override such implied data).


> Which one is which?  Is spam() the instance method and eggs() the
> class method, or is spam() the class method and eggs the instance
> method?  (One does not, and should not, have to *care*, which is
> kind of the point here. :-) )

You can't tell just from the syntax used to call them:

function(arg)
bound_method(arg)
builtin_function_or_method(arg)
callable_instance(arg)
type(arg)

all use the same syntax. There is no requirement that you should be able to
tell *everything* about a line of code just from the syntax used. If you
want to know whether black_knight.spam is an instance method or a class
method, or something else, use introspection to find out.

> By "that" I assume you mean the name "black_knight" here.  But the
> name is not required to make the call; see the last line of the
> following code fragment:
> 
> funclist = []
> ...
> black_knight = K()
> funclist.append(black_knight.spam)
> funclist.append(black_knight.eggs)
> ...
> # At this point, let's say len(funclist) > 2,
> # and some number of funclist[i] entries are ordinary
> # functions that have no special first parameter.
> random.choice(funclist)()

Irrelevant. The instance used for the bound method is explicitly specified
when you create it. But there's no requirement that you need to explicitly
specify the instance 

Floating point multiplication in python

2011-09-05 Thread xyz
hi all:

As we know ,  1.1 * 1.1 is 1.21 . 
But in python ,I got following :

>>> 1.1 * 1.1
1.2102

why python get wrong result? Who can tell me  where's the 0.0002 
from?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Floating point multiplication in python

2011-09-05 Thread Chris Rebert
On Mon, Sep 5, 2011 at 10:57 PM, xyz  wrote:
> hi all:
>
> As we know ,  1.1 * 1.1 is 1.21 .
> But in python ,I got following :
>
 1.1 * 1.1
> 1.2102
>
> why python get wrong result?

It's not Python's fault per se, rather it's the inherent nature of
binary floating-point arithmetic. Try the equivalent in most other
languages and you'll get the same "error".
Please read http://docs.python.org/tutorial/floatingpoint.html

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