A better self
Michele Simionato
mis6 at pitt.edu
Tue Jul 23 17:48:47 EDT 2002
Personally, I have no problems in conforming myself to the established
tradition and to use the standard self. However many people don't like self.
It has not been mentioned in this thread, but there a simple way to cope
with this problem without changing the language: a Python preprocessor.
Suppose one define the pseudocode
--begin pseudo.py--
from math import sin,sqrt
class Example:
y,z,t=1.0,1.0,1.0
def f(,x):
return sin(.t)*x**.y+sqrt(.z)
example=Example()
print example.f(1.0)
--end pseudo.py--
where the comma in f(,x) remind us that the first argument self is omitted.
One can easily create a preprocessor that convert this code on standard
python code converting
(, ---> (self,
and
.something ---> self.something
For instance the following code does the job (if you work on Red Hat
Linux the first line has to be #!/usr/bin/python2):
--begin pp--
#!/usr/bin/python
from re import compile
import sys
def process(pseudocode):
comma=compile(r'\(\s*,')
dot=compile(r'[^\w_]\.[a-zA-Z_]+')
code=comma.sub('(self,',pseudocode)
end=0; newcode=''
for found in dot.finditer(code):
start=found.start()
newcode+=code[end:start+1]+'self'
end=found.end()
newcode+=code[start+1:end]
return newcode+code[end:]
try:
name=sys.argv[1]
except:
print "Usage: ./p2 programname.py"
sys.exit()
inp=file(name)
out=process(inp.read())
inp.close()
print out
--end pp--
This is not perfect because it converts "(," and ".something" everywhere in
the file, even in comments and in strings, however it can be refined.
The point is that pp (Python Preprocessor) convert the pseudo code in
normal code which can be executed. After a chmod u+x pp the user can type
$ ./pp pseudo.py > normal.py
to convert the pseudocode in standard code or even directly execute the
pseudocode with
$ ./pp pseudo.py | python
Notice that the preprocessor also works with function with no explicit
arguments, since f(,) is converted to f(self,) which is equivalent to f(self).
The preprocessor idea is interesting, not only for people who want to create
their own shortcuts to the language (I think it is better to use good habits
and to use the standard language), but even for more serious jobs.
--
Michele Simionato - Dept. of Physics and Astronomy
210 Allen Hall Pittsburgh PA 15260 U.S.A.
Phone: 001-412-624-9041 Fax: 001-412-624-9163
Home-page: http://www.phyast.pitt.edu/~micheles/
More information about the Python-list
mailing list