Accessing a method from within its own code

2009-11-02 Thread Paddy O'Loughlin
Hi,
I was wondering if there was a shorthand way to get a reference to a method
object from within that method's code.

Take this code snippet as an example:
import re

class MyClass(object):
def find_line(self, lines):
if not hasattr(MyClass.do_work, matcher):
MyClass.do_work.matcher = re.compile(\d - (.+))
for line in lines:
m = MyClass.do_work.matcher.match(line)
if m:
return m.groups()

Here, I have a method which uses a regular expression object to find
matches. I want the regexp object to be tied to the function, but I don't
want to have to recreate it every time the function is called (I am aware
that regexp objects are cached, avoiding this problem, but I'm just using
this as an example for what I want to know), so I've added it to the method
object as an attribute and create it only if it doesn't exist.

However, typing out Classname.MethodName.variablename everytime is
pretty long and susceptible to refactoring issues, so I was wondering if
there was a way in Python that I am missing which allows you to reference
the method that the code is in (like __module__ gives a reference to the
parent module).

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing a method from within its own code

2009-11-02 Thread Paddy O'Loughlin

 I suspect that the inspection module has your answer, but that it'll be
 bulkier, and much slower than just doing what you're doing already.

Hmm.
Yeah, it does appear to be bulky. I don't think it's really any more use
than what I'm doing already.


Why not use the default arguments gimmick?  Since this cached item is to
 have a module lifetime, it'd be desirable to create it when the method is
 being defined, which is exactly what default arguments do.


I've a few different ways of emulating static function variables from C/Java
and the function/method attribute one is easily the one that appeals most to
my sensibilities.
I find the default arguments gimmick to be a gimmick. It's co-opting a piece
of functionality for something it doesn't seem like it was originally
intended for and as a consequence is less readable (to my eyes).
The only problem with the function/method way is that it gets rather verbose
when you are dealing with a user-defined method and have to give the class
name and method name and it's also a bit of a pain for moving code around
when refactoring.

You ever wish there was more to python scoping than just locals(), globals()
and __builtins__? Like a method's class's scope too?
That's where I am at with this.


-- 
Ray, when someone asks you if you're a god, you say YES!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sorted() erraticly fails to sort string numbers

2009-04-30 Thread Paddy O'Loughlin
2009/4/30 Lie Ryan lie.1...@gmail.com

   container[:] = sorted(container, key=getkey)

  is equivalent to:

   container.sort(key=getkey)


 Equivalent, and in fact better since the sorting is done in-place instead
 of creating a new list, then overwriting the old one.


Not when, as pointed out by uuid, container is not list-like (at least as
far as the sort() method goes).
:)

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Reading an exact number of characters from input

2009-04-16 Thread Paddy O'Loughlin
Hi,
How would I use python to simply read a specific number of characters
from standard input?

raw_input() only returns when the user inputs a new line (or some
other special character).
I tried
 import sys
 sys.stdin.read(15)

and that *returns* up to 15 characters, but it keeps accepting input
(and doesn't return) until I press Enter.

My initial thoughts are that a function like C's fgetc would be the
easiest way to do it, but I haven't been able to find an equivalent in
my google search, so I was wondering if anyone here might have some
ideas.

What say you?

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Introducing Python to others

2009-03-26 Thread Paddy O'Loughlin
Hi,
As our resident python advocate, I've been asked by my team leader to
give a bit of a presentation as an introduction to python to the rest
of our department.
It'll be less than an hour, with time for taking questions at the end.

There's not going to be a whole lot of structure to it. First, I'm
going to open up a python terminal and show them how the interpreter
works and a few basic syntax things and then a file .py files (got to
show them that python's indenting structure is not something to be
afraid of :P). I think I'll mostly show things in the order that they
appear in the python tutorial (http://docs.python.org/tutorial/).

My question to you, dear python-list, is what suggestions do you have
for aspects of python that I should show them to make them maybe think
that python is better than what they are using at the moment.
All of the audience will be experienced (4+ years) programmers, almost
all of them are PHP developers (2 others, plus myself, work in C, know
C#, perl, java, etc.).
Because of this, I was thinking of making sure I included exceptions
and handling, the richness of the python library and a pointing out
how many modules there were out there to do almost anything one could
think of.
Anything else you think could make PHP developers starting think that
python is a better choice?
If I were to do a (very) short demonstration one web framework for the
PHP devs, what should I use? CherryPy (seems to be the easiest),
Django (seems to be the biggest/most used), or something else?

Any other suggestions for a possible wow reaction from an audience like that?

Thanks,
Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Introducing Python to others

2009-03-26 Thread Paddy O'Loughlin
Thanks for all your replies.
A lot of very strong answers :)

2009/3/26 Mensanator mensana...@aol.com:
 What would you have to do to make this work?

 x+x+x      # expecting [3,6]
 [2, 4, 1, 2]

What's happening is that the call to map() is returning a list object.
So after it calculates the first x+x, you are left with the equivalent of:
[6, 6] + x
Because the list object is on the left, it's __add__() function is
called, which appends x to [6,6].

Instead, convert the list returned by map to a Vector before returning
it. Like so:
 class Vector(list):
... def __add__(self, other):
... return Vector(map(add, self, other))
...
 x = Vector([3,3])
 x+x+x
[9, 9]



-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Run a python script as an exe and run a new process from it

2009-02-27 Thread Paddy O'Loughlin
2009/2/27 venutaurus...@gmail.com venutaurus...@gmail.com:
 Thanks for the reply,,
            I am trying to use the above application using psexec()in
 command line.But it failed returning the error message

  exited with error code 255.

              But when I ran the application normally it worked
 fine.Do I need to add anything to my python script(either the main one
 or the script which is calling it) to make it work.

I don't have any experience with psexec, so I'm not sure if I can help
you with that.
I assume this means that you are trying to run the script on a remote
computer? (Elsewise, why use psexec?)

I took a look at it though and it seems that it always exits with
*some* error code. I think it's more usual for that error code to be
zero, though (it does when I run it on my machine).

You might try psexec start script1.py, which might work if you've
successfully set Explorer to run .py files with python.exe when you
double-click on them.

psexec python script1.py will work if the python.exe is in the correct path.

You can also specify the full path to your python.exe. if you know it
e.g.: psexec C:\python25\python.exe script1.py



-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Run a python script as an exe and run a new process from it

2009-02-26 Thread Paddy O'Loughlin
Try this as an outline:
 script1.py
from subprocess import Popen

if __name__ == '__main__':
scriptname = script2.py

Popen(python %s % scriptname, shell=True)


print I'm done


 script2.py
from time import sleep

if __name__ == '__main__':
while (True):
print waiting..
sleep(2)

###
If you install python using the Windows Installer (.exe), it should
set up .py files to be opened by python when double-clicking on them.
Alternatively, you can right-click on your .py file and go to Open
With... then choose program, then click Browse..., you can Browse
to the python executable, so Explorer will use it to open .py files
when you double-click on them.

As someone else mentioned there is also a py2exe program. Google it.

2009/2/26 venutaurus...@gmail.com venutaurus...@gmail.com:
 Hello all,
           I've a strange requirement where I need to run a python
 script just as we run an exe (by double clicking through windows
 explorer or by typing the script name at command prompt). In that
 process I should be able to execute another python script in such a
 way that, the second script should continue running but the main one
 should terminate without effecting the second one.

                    My requirement may be little confusing so please
 get back if you didn't understand what I meant above.


 Thank you,
 Venu.
 --
 http://mail.python.org/mailman/listinfo/python-list




-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Byte type?

2009-02-24 Thread Paddy O'Loughlin
2009/2/24 John Nagle na...@animats.com:
 Martin v. Löwis wrote:

 Please don't call something dumb that you don't fully understand. It's
 offenses the people who have spent lots of time developing Python --
 personal, unpaid and voluntary time!

   Some of the people involved are on Google's payroll.

Uh, what does that have to do with anything?
It would only be relevant if you are saying that Google is paying them
to do the work (so not just on their payroll).

More importantly, it's also only relevant if ALL the people
contributing are being paid by Google to do the work, which I'm pretty
sure is not the case.

There are people are spending lots of personal, unpaid and voluntary
time developing Python.

Paddy
-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Paddy O'Loughlin
2009/2/20 Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid:
 Note that while you *can* do direct access to the implementation attribute
 (here, '_A' for property 'A'), you don't *need* to so (and usually shouldn't
 - unless you have a very compelling reason).

Interesting. Why shouldn't you?
I haven't used the property() function before and probably have no
call to, but when you say usually shouldn't, what is there against
it?

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Paddy O'Loughlin
2009/2/20 Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid:
 Interesting. Why shouldn't you?
 I haven't used the property() function

 s/function/object/

Nice try, but what I wrote was what I intended to say:
http://docs.python.org/library/functions.html#property

For all I know I could have used property objects several times in modules :)

 The case is that the whole point of using a computed attribute is to perform
 some computation on the value. IOW, except for a couple corner cases, only
 the accessors should directly access the implementation(s) attributes(s).

 And of course, like for any other GoldenRule(tm), it's not meant to be
 blindly followed. It's just that most of the times, going thru the accessors
 is really what you want - even from within the class code.

Hmm, it doesn't seem to me like it's much of a big deal, for it to
described as anything like a GoldenRule or to advise against its
overuse.
You use it when its appropriate and don't use it when you it's not,
like any other feature.

Paddy


-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-20 Thread Paddy O'Loughlin
2009/2/20 Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid:
 Check by yourself:

 import inspect
 inspect.isfunction(property)
 False
Using this, every single builtin function returns False. That's a
pretty limited definition to be being pedantic over, especially when
they are in the Built-in Functions section of the manual.

 property()
 property object at 0xb7cbc144
I never said that calling it didn't return a property object :)

 property
type 'property'

So it's a type.
I think I didn't make such a bad error on my part. My intent in what I
was saying was to indicate that I hadn't created a property type. It's
fair enough to consider type constructors as functions given how they
are listed as such by the python documentation.
I don't think that your correction was much help, unless you just want
to say that everything is an object. Maybe you'd be right, but it's
not much use to use the term that way, imo

shrug

 dir(property)
 ['__class__', '__delattr__', '__delete__', '__doc__', '__get__',
 '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
 '__reduce_ex__', '__repr__', '__set__', '__setattr__', '__str__', 'fdel',
 'fget', 'fset']

Doesn't prove a whole lot. So types have attributes...
So do functions:
 def myfunc():
... pass
...
 dir(myfunc)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__', '__module__',
'__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__str__', 'func_closure', 'func_code',
'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']


 Hmm, it doesn't seem to me like it's much of a big deal, for it to
 described as anything like a GoldenRule

 One could say the same for each and any of the usual GoldenRules(tm).
Not really. To do so would be over-generalising and not useful to discussion
I guess it's your pedantry that I'm questioning.
Something like don't use goto's works as a GoldenRule because it's
been observed that without it, people start using goto statements in
places where it's not really appropriate.
When you said that [you] usually shouldn't [use properties] - unless
you have a very compelling reason, your tone implied that properties
are easy to misuse and tend to be.
Not being familiar with properties and seeing them as being pretty
harmless, I was intrigued by this, which is why I asked for an
explanation.
Your explanation seems to show that your tone was likely to be more
personal bias than any real issue with properties.

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-17 Thread Paddy O'Loughlin
Use the global statement.
http://docs.python.org/reference/simple_stmts.html#the-global-statement

A working example based on your pseudocode would be:

def getA():
global A
return A

def getB():
global B
return B

def setA(value):
global A
A = value

def setB(value):
global B
B = value

def main():
setA(5)
setB(6)
print getA()
print getB()

if __name__ == '__main__':
main()

#

Although honestly, I think you'd be best not coding like that (with
gets and sets and all) in python.

Paddy

2009/2/17 Linuxguy123 linuxguy...@gmail.com:
 How do I do this in Python ?

 #
 declare A,B

 function getA
return A

 function getB
return B

 function setA(value)
 A = value

 function setB(value)
 B = value

 main()
getA
getB
dosomething
setA(aValue)
setB(aValue)
 

 The part I don't know to do is declare the variables, either as globals
 or as vars in a class.  How is this done in Python without setting them
 to a value ?

 Thanks



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




-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I declare global vars or class vars in Python ?

2009-02-17 Thread Paddy O'Loughlin
2009/2/17 MRAB goo...@mrabarnett.plus.com:
 It isn't possible to have an uninitialised variable. If it doesn't have
 a value then it doesn't exist.

True, but you can use the global statement to refer to the variable
within a function and read from the variable there, without it being
already initialised in the module.

Of course, if you try to call that function before the global has been
initialised, python will complain [and rightly so :)]

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way to determine if a string is a number

2009-02-17 Thread Paddy O'Loughlin
2009/2/16 Python Nutter pythonnut...@gmail.com:
 silly me, forgot to mention

 build a set from digits + '.' and use that for testing.

 Cheers,
 PN


 2009/2/16 Python Nutter pythonnut...@gmail.com:
 Type casting seems to be the wrong way to go about this.

 teststring = '15719'
 teststring.isdigit()
 returns True

 That takes care of integers.

 from string import digits
 digits
 '0123456789'

 now you have all the digits and you can do set testing in your logic
 to see if the teststring has anything in digits

 A dumb way to test is alphanumeric

 teststring2 = '105.22'
 teststring2.isalnum()
 returns True

 now you can go on from there and test to further to eliminate
 'abcd385laf8' which on alnum() also returns true.

Hmmm, this doesn't seem right to me.

Unless I'm missing something, won't your code think that 123.123.123
is numeric? What about scientific or engineering notation with
exponents?

What's wrong with using python's own casting rules (given that you are
trying to emulate the way python behaves? Or, alternatively, using a
regular expression (as Nick Craig-Wood did).

Given these solutions, type-conversion and catching the ValueError
appears, to me, to be correct, the most concise, and the most readable
solution.

Of course, if you want to use your own set of rules for number
encoding, then building your own regular expression would seem to be
the right way to go.

Paddy

-- 
Ray, when someone asks you if you're a god, you say YES!
--
http://mail.python.org/mailman/listinfo/python-list