Re: if the else short form

2010-10-10 Thread NevilleDNZ
On Oct 10, 6:02 pm, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 As for DICT, I think table lookups were still a sufficiently novel concept
 for people to disagree on how they should best be implemented.

I then stumbled over this paper:
Title: List processing in Algol 68 - V. J. Rayward-Smith
International Journal of Mathematical Education in Science and
Technology, 1464-5211, Volume 17, Issue 2, 1986, Pages 239 – 245
* http://www.informaworld.com/index/746867626.pdf - PayWall $30.00
 Abstract
 An Algol 68 implementation of a LISP-like list processing package
 is described. Emphasis is placed upon the importance of Algol 68
 as a teaching tool and upon the need for proving the correctness
 of the programs.

Not having LIST and DICT as part of the base language would make sense
if user contributions were encouraged.  After all that would make way
for evolving the base/primitive language by selecting the most
successful contributions.  IMHO this is where python modules have been
a big success story as it helps time proof the language by allowing
the language to embrace new technologies as they establish themselves
in the market place.

c.f. Anti Gravity: http://xkcd.com/353/

Enjoy
NevilleDNZ
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-09 Thread NevilleDNZ
On Oct 9, 6:55 pm, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 In message i8o1ij$ro...@news.eternal-september.org, BartC wrote:

  NevilleDNZ neville...@gmail.com wrote in message
 news:ad9841df-49a1-4c1b-95d0-e76b72df6...@w9g2000prc.googlegroups.com...

  In Algol68 this would be:
  x:=(i|One,Two,Three|None Of The Above)

  The point is, the construction works well when the syntax fully supports
  it.

 But note that Algol68 doesn’t support explicit labels on the alternatives
 in a case expression or statement. That idea came later.

Good point... I do ponder why (given that linked lists can easily be
created in Algol68) useful types like LIST and DICT were left out of
the standard prelude.  I do not recall any conversation about this in
the ALGOL Bulletins /* I can reasonably guess why C elected to
excluded these types */

The nearest to explicit labels in Algol68 would be:
STRING x:=(i=0|Zero |:i=1|One |:i=2|Two |:i=3|Three |None Of
The Above);

Basically a compound IF statement... effectively a read only, compile-
time dictionary.

N


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


Re: if the else short form

2010-10-08 Thread NevilleDNZ
On Oct 7, 9:23 am, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 x = {1 : One, 2 : Two, 3 : Three}.get(i, None Of The Above)

More like:
x = {1:lambda:One, 2:lambda:Two, 3:lambda:Three}.get(i,
lambda:None Of The Above)()

i.e. deferred evaluation of selected case.

In Algol68 this would be:
x:=(i|One,Two,Three|None Of The Above)

N
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if the else short form

2010-10-08 Thread NevilleDNZ
On Oct 7, 10:36 am, BartC b...@freeuk.com wrote:
 i=16
 x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, None Of The Above)
 print x

 Other than efficiency concerns, sometimes you don't want the extra
 side-effects.

 Probably there are workarounds here too, but I suspect the syntax won't be
 quite as pert as the Algol68-style example:

 x = (i | Zero, One, Two | None of the above)  # 0-based

/* ¢ Algol68 case clause is 1-based. ¢ */

However Algol68's CASE ~ IN ~,~,~,~ OUT ~ ESAC clause does mean that
the case items of the clause are not evaluated unless selected.  Here
are some comparisons with python:

$ cat py_case.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# This procedure evaluates all the months lengths _before_ building
the dict.
# In that case of month length, they are constants.

def days_in_month0(year, month):
  return {1:31,
2:{True:29,False:28}[year%4==0 and year%100!=0 or year%400==0],
3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31
  }.get(month,None)

# This procedure is closer - in behaviour - to that of the algol68
case clause.
# Keypoint being that individual month length code is not evaluated
unless called()
def days_in_month(year, month):
  return {1:lambda:31,
2:lambda:{True:lambda:29,False:lambda:28}[year%4==0 and year%100!
=0 or year%400==0](),
3:lambda:31,4:lambda:30,5:lambda:31,6:lambda:30,7:lambda:
31,8:lambda:31,9:lambda:30,10:lambda:31,11:lambda:30,12:lambda:31
  }.get(month,None of the above)()

for year in 1899,1900,1901,1999,2000,2001:
  print %4d=%2d%(year,days_in_month0(year, 2)),



Compare with Algol 68:

Brief choice clause example:

PROC days in month = (INT year, month)UNION(INT,STRING):
  (month|31,
(year%×4=0 ∧ year%×100≠0 ∨ year%×400=0|29|28),
31,30,31,30,31,31,30,31,30,31
  |None of the above # or EMPTY #
  );

BOLD choice clause example:

PROC days in month = (INT year, month)UNION(INT,STRING):
  CASE month IN 31,
IF year MOD 4 EQ 0 AND year MOD 100 NE 0 OR year MOD 400 EQ 0 THEN
29 ELSE 28 FI,
31,30,31,30,31,31,30,31,30,31
  OUT None of the above # or EMPTY #
  ESAC;

[]INT years = (1899,1900,1901,1999,2000,2001);
FOR key TO UPB years DO INT year=years[key];
  printf(($4d,=2d $, year, days in month(year, 2)))
OD


$ python py_case.py
1899=28 1900=28 1901=28 1999=28 2000=29 2001=28

There are also the compound IF and CASE conditional clauses:

 IF condition1 THEN statements ELIF condition2 THEN statements [ ELSE
statements ] FI
 brief form if IF clause:  ( condition1 | statements |: condition2 |
statements | statements )

 CASE switch1 IN statements, statements,... OUSE switch2 IN
statements, statements,... [ OUT statements ] ESAC
 brief form of CASE statement:  ( switch1 |
statements,statements,... |: switch2 | statements,statements,... |
statements )

Enjoy
NevilleDNZ
--
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68/files
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying Class Object

2010-02-23 Thread NevilleDNZ
Hi Groetjes Albert,

I spotted your comment - re: pointers
http://groups.google.com/group/comp.lang.python/msg/5c1e25919b6a74bf

On Feb 22, 11:44 pm, Albert van der Horst alb...@spenarnc.xs4all.nl
wrote:
(I once studied algol 68, and never got confused about these
 subjects anymore, recommended.)

Having used Algol68, then switching to C to discover * for manual
dereferencing I immediately wanted to be back using A68 again, but
alas...  Then when I switched to C++ I immediately understood the
Zen of C++'s ... but still wanted to switch back to A68.  Was
there ever a version with Objects... I saw a version with Areas
but have no idea what an Area is.

@Albert: Given the domain name xs4all in your email address I am
sure YOU have spotted: http://www.xs4all.nl/~jmvdveer/algol.html by
Marcel

Also: I invite you to join one of the below groups (my .sig below) and
deposit some of your Algol68 impressions

There is also a chrestomathy site http://rosettacode.org/wiki/ALGOL_68
where you can pick out an code sample unimplemented in Algol68 and
torture test your Algol68 memories.  (Be warned: Most of the easy
samples are done)

Keep in touch
NevilleDNZ
--
For Algol68-user mailinglist with archives  subscription:
* https://lists.sourceforge.net/lists/listinfo/algol68-user
To download Linux's Algol68 Compiler, Interpreter  Runtime:
* http://sourceforge.net/projects/algol68
Join the linkedin.com's Algol68 group, follow:
* http://www.linkedin.com/groups?gid=2333923
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying octal notation

2009-09-04 Thread NevilleDNZ
On Sep 3, 2:57 pm, James Harris james.harri...@googlemail.com wrote:
 On 3 Sep, 14:26, Albert van der Horst alb...@spenarnc.xs4all.nl
 wrote:

  In article 
  6031ba08-08c8-416b-91db-ce8ff57ae...@w6g2000yqw.googlegroups.com,
  James Harris  james.harri...@googlemail.com wrote:
  SNIP

  So you are saying that Smalltalk has base in decimalrnumber where
  r is presumably for radix? That's maybe best of all. It preserves the
  syntactic requirement of starting a number with a digit and seems to
  have greatest flexibility. Not sure how good it looks but it's
  certainly not bad.

    0xff  0x0e | 0b1101
    16rff  16r0e | 2r1101

  Hmm. Maybe a symbol would be better than a letter.

  Like 0#ff  16#ff ?

 Yes, that looks better.

  That is ALGOL68. It is incredible how many of it has become
  vindicated over time. (Yes, nineteen hundred sixty eight was
  the year that language was conceived.)

 Yes, and its predecessor Algol 60 was a masterful advance in
 programming languages. It set up standards we still use today.
c.f. http://en.wikiquote.org/wiki/C._A._R._Hoare#The_Emperor.27s_Old_Clothes


 James

However I don't recall Algol60 having Bin/Oct/Hex numeric
literals.  c.f. http://www.masswerk.at/algol60/report.htm

And I am pretty sure that Algol60 had neither builtin
byte operators (eg xor, shl/shr), nor a builtin ability to
read nor printf oct/hex.  Maybe these were in AlgolW or a
Burroughs/Unisys dialect of Algol60?

(FYI: AlgolW has been reincarnated by Glyn Webster with
his worthy AlgolW to gcc 'C' translator.  To be found at:
http://www.jampan.co.nz/~glyn/)

The lack input/output in Algol60 did mean you could never
shoot yourself in the foot with true Algol60 c.f.:
[http://www.toodarkpark.org/computers/humor/shoot-self-in-foot.html]
* Algol 58/60+ - shoot yourself in the foot with a Civil
   War-era musket. The musket is aesthetically fascinating,
   and the wound baffles the adolescent medic in the
   emergency room.
* Algol 60 - You spend hours trying to figure out how
   to fire the gun because it has no provisions for input
   or output.

On the other hand compare:
* Algol 68 - You mildly deprocedure the gun, the bullet
   gets firmly dereferenced, and your foot is strongly
   coerced to void.

(I do know Algol 68 has the builtin mode BITS with
matching literals, casts, operators and input/output, cf:
http://rosettacode.org/wiki/Bitwise_operations#ALGOL_68 )

And in summary of 41 years of language advancement:
* Python - You shoot yourself in the foot and then brag
   for hours about how much more elegantly you did it
   than if you had been using C or (God forbid) Perl.

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


Re: Numeric literals in other than base 10 - was Annoying octal notation

2009-08-24 Thread NevilleDNZ
On Aug 23, 9:42 pm, James Harris james.harri...@googlemail.com
wrote:
 The numbers above would be

   0b1011, 0t7621, 0xc26b

Algol68 has the type BITS, that is converted to INT with the ABS
operator.
The numbers above would be:
   2r1011, 8r7621, 16rc26b

r is for radix: http://en.wikipedia.org/wiki/Radix

The standard supports 2r, 4r, 8r  16r only.

The standard supports LONG BITS, LONG LONG BITS etc, but does not
include UNSIGNED.

Compare gcc's:

bash$ cat num_lit.c
#include stdio.h
main(){
  printf(%d %d %d %d\n,0x,0,,0b);
}

bash$ ./num_lit
65535 4095  15


With Algol68's: https://sourceforge.net/projects/algol68/

bash$ cat num_lit.a68
main:(
  printf(($g$,ABS 16r,ABS 8r,,ABS 2r,$l$))
)

bash$ algol68g ./num_lit.a68
 +65535  +4095  ++15

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


Re: RegEx for matching brackets

2008-05-03 Thread NevilleDNZ
To check a complete python expression use:

def check_open_close(expr):
  try:
eval(expr)
  except SyntaxError:
return False
  else:
return True

This also ignores brackets in quotes, and checks =  = operators are
syntatically correct etc...
But is may have side effects... ;-)
eg.
 check_open_close('__import__(os).system(echo rm -rf /) # OK')

c.f http://en.wikipedia.org/wiki/Scope_creep

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


Re: RegEx for matching brackets

2008-05-02 Thread NevilleDNZ
On May 2, 11:13 am, George Sakkis [EMAIL PROTECTED] wrote:
 [1]http://en.wikipedia.org/wiki/Context-free_language
 [2]http://en.wikipedia.org/wiki/Regular_language
 [3]http://wiki.python.org/moin/LanguageParsing

Thanx for the link to these parsers. ANTLR looks interesting.
Yoyo: http://www-users.cs.york.ac.uk/~fisher/software/yoyovwg/readme

I figured out a way to do it in python.

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
tests=
  { a test  BAD
  { a test } OK
  { a test } { a test } OK
  { a test } { this { a test } is a test } OK
  { a test  { this { a test } is a test } missing close BAD
  a test } { this { a test } is a test } BAD
  { a test } this { a test } is a test } BAD
.splitlines()[1:]

def referee(str):
  return bool(re.search(OK,test))

def check_open_close(str):
  try:
eval(.join({{:[,}:],}[c] for c in re.findall( ([{}])|(?:
[^{}]+), str) if c))
  except SyntaxError:
return False
  else:
return True

for test in tests:
  if check_open_close(test) == referee(test):
print DETECTED:,test
  else:
print MISSED:,test
[linux]$ ./matchall_open_close.py
DETECTED:   { a test  BAD
DETECTED:   { a test } OK
DETECTED:   { a test } { a test } OK
DETECTED:   { a test } { this { a test } is a test } OK
DETECTED:   { a test  { this { a test } is a test } missing close BAD
DETECTED:   a test } { this { a test } is a test } BAD
DETECTED:   { a test } this { a test } is a test } BAD

It's not exactly what I planned, but as a python one/two-liner it
works fine.
eval(.join({{:[,}:],}[c] for c in re.findall( ([{}])|(?:
[^{}]+), str) if c))

ThanX again
N


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


RegEx for matching brackets

2008-05-01 Thread NevilleDNZ
Below is a (flawed) one line RegEx that checks curly brackets (from
awk/c/python input) are being matched.  Is there a one liner for doing
this in python?

ThanX
N

re_open_close=(((\{))[^{}]*((?(0)\})))+
re_open_close=re.compile(re_open_close)
tests=
  { this is a test  BAD
  { this is a test } OK
  { this is a test } { this is a test } OK
  { this is a test } { this { this is a test } is a test } OK
  { this is a test  { this { this is a test } is a test } missing
close BAD
.splitlines()[1:]
for test in tests:
  if bool(re_open_close.search(test)) == bool(re.search(OK,test)):
print DETECTED:,test
  else:
print MISSED:,test
[linux]$ python ./re_matching.py
DETECTED:   { this is a test  BAD
DETECTED:   { this is a test } OK
DETECTED:   { this is a test } { this is a test } OK
DETECTED:   { this is a test } { this { this is a test } is a test }
OK
MISSED:   { this is a test  { this { this is a test } is a test }
missing close BAD
--
http://mail.python.org/mailman/listinfo/python-list


Q: a simple(?) raw-utf-8 conversion to internal type unicode \304\246\311\231\316\257\316\271\303\222

2006-12-31 Thread NevilleDNZ
Hi,

Apologies first as I am not a unicode expert indeed I the details
probably totally elude me.  Not withstanding:  how can I convert a
binary string containing UTF-8 binary into a python unicode string?

cutdown example:
$ cat ./uc.py
#!/usr/bin/env python
imported=\304\246\311\231\316\257\316\271\303\222
\317\216\317\203\305\224\304\271\304\220
print English/ASCII quoting:,''+imported+'',SUCCEEDS :-) # xterm
encoding if UTF8
print German/ALCOR quoting:,u\N{runic cross punctuation}+test
+\N{runic cross punctuation},AOK :-)
print German/ALCOR quoting:,u\N{runic cross
punctuation}+imported+u\N{runic cross punctuation},FAILS :-(

$ ./uc.py
English/ASCII quoting: ĦəίιÒ ώσŔĹĐ SUCCEEDS :-)
German/ALCOR quoting: ᛭test᛭ AOK :-)
German/ALCOR quoting:
Traceback (most recent call last):
  File ./uc.py, line 5, in module
print German/ALCOR quoting:,u\N{runic cross
punctuation}+imported+u\N{runic cross punctuation},FAILS :-(
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
ordinal not in range(128)

The last print statement fails because the ascii imported characters
are 8 bit encoded UTF-8 and dont know it! How do I tell imported that
it is actually already UTF-8 unicode?

Cheers
NevilleDNZ

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

Just TOO easy.... Re: Q: a simple(?) raw-utf-8 conversion to internal type unicode \304\246\311\231\316\257\316\271\303\222

2006-12-31 Thread NevilleDNZ
It was just TOO easy... on posting my message to google groups, and
when I re-read the posting on groups I found that google had pointed me
to a python-unicode tutorial...
www.reportlab.com/i18n/python_unicode_tutorial.html - exercise one :-)

Gosh sometime a google is worth so much more then ₁₀¹⁰⁰!

Happy New Year
NevilleD

It works now:
$ ./uc.py
English/ASCII quoting: ĦəίιÒ ώσŔĹĐ SUCCEEDS :-)
German/ALCOR quoting: ᛭test᛭ AOK :-)
German/ALCOR quoting: ᛭ĦəίιÒ ώσŔĹĐ᛭ FAILS :-(
[EMAIL PROTECTED]:/root0/home/nevilled/Project/20 $ vi ./uc.py
[EMAIL PROTECTED]:/root0/home/nevilled/Project/20 $ cat ./uc.py
#!/usr/bin/env python
imported=unicode(\304\246\311\231\316\257\316\271\303\222
\317\216\317\203\305\224\304\271\304\220,utf-8)
print English/ASCII quoting:,''+imported+'',SUCCEEDS :-) # xterm
encoding if UTF8
print German/ALCOR quoting:,u\N{runic cross punctuation}test\N{runic
cross punctuation},AOK :-)
print German/ALCOR quoting:,u\N{runic cross
punctuation}+imported+u\N{runic cross punctuation},Just TOO easy
:-)

$ ./uc.py
English/ASCII quoting: ĦəίιÒ ώσŔĹĐ SUCCEEDS :-)
German/ALCOR quoting: ᛭test᛭ AOK :-)
German/ALCOR quoting: ᛭ĦəίιÒ ώσŔĹĐ᛭ Just TOO easy :-)

NevilleDNZ wrote:
 Hi,

 Apologies first as I am not a unicode expert indeed I the details
 probably totally elude me.  Not withstanding:  how can I convert a
 binary string containing UTF-8 binary into a python unicode string?

 cutdown example:
 $ cat ./uc.py
 #!/usr/bin/env python
 imported=\304\246\311\231\316\257\316\271\303\222
 \317\216\317\203\305\224\304\271\304\220
 print English/ASCII quoting:,''+imported+'',SUCCEEDS :-) # xterm
 encoding if UTF8
 print German/ALCOR quoting:,u\N{runic cross punctuation}+test
 +\N{runic cross punctuation},AOK :-)
 print German/ALCOR quoting:,u\N{runic cross
 punctuation}+imported+u\N{runic cross punctuation},FAILS :-(

 $ ./uc.py
 English/ASCII quoting: ĦəίιÒ ώσŔĹĐ SUCCEEDS :-)
 German/ALCOR quoting: ᛭test᛭ AOK :-)
 German/ALCOR quoting:
 Traceback (most recent call last):
   File ./uc.py, line 5, in module
 print German/ALCOR quoting:,u\N{runic cross
 punctuation}+imported+u\N{runic cross punctuation},FAILS :-(
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
 ordinal not in range(128)

 The last print statement fails because the ascii imported characters
 are 8 bit encoded UTF-8 and dont know it! How do I tell imported that
 it is actually already UTF-8 unicode?
 
 Cheers
 NevilleDNZ

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

proc A def/calls proc B: variable scoping rules.

2006-08-15 Thread NevilleDNZ
Can anyone explain why begin B: 123 prints, but 456 doesn't?

$ /usr/bin/python2.3  x1x2.py
begin A:
Pre B: 123 456
begin B: 123
Traceback (most recent call last):
  File x1x2.py, line 13, in ?
A()
  File x1x2.py, line 11, in A
B()
  File x1x2.py, line 7, in B
print begin B:,x1,x2
UnboundLocalError: local variable 'x2' referenced before assignment


$ cat x1x2.py
#!/usr/bin/env python
def A():
  print begin A:
  x1=123;
  x2=456;
  def B():
print begin B:,x1,x2
x2 = x2 - 1; # comment out this line and script x1x2 magically
works!!
print end B:,x1,x2
  print Pre B:,x1,x2
  B()
  print end A:,x1,x2
A()

$ /usr/bin/python2.3
Python 2.3.4 (#1, Mar 10 2006, 06:12:09)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
Type help, copyright, credits or license for more information.



$ /usr/bin/python2.3 -V
Python 2.3.4

$ /usr/local/bin/python2.4 -V
Python 2.4.2
$ /usr/local/bin/python2.4 x1x2.py
begin A:
Pre B: 123 456
begin B: 123
Traceback (most recent call last):
  File x1x2.py, line 13, in ?
A()
  File x1x2.py, line 11, in A
B()
  File x1x2.py, line 7, in B
print begin B:,x1,x2
UnboundLocalError: local variable 'x2' referenced before assignment

# I compiled up 2.4 from the FC4 source, but 2.3 was from SL4.3
$ python -V
Python 2.4.2
$ python
Python 2.4.2 (#1, Aug 15 2006, 21:51:33)
[GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
Type help, copyright, credits or license for more information.

$

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


Re: proc A def/calls proc B: variable scoping rules.

2006-08-15 Thread NevilleDNZ

Steve Holden wrote:
 Hardly surprising. This statement is an assignment to x2, which
 therefore becomes local to the function. Since no previous value has
 been assigned to this local, the exception occurs.

But: In this case the assignment is never reached eg..
#!/usr/bin/env python
def A():
  print begin A:
  x1=123
  x2=456
  def B():
print begin B:,x1,x2
if False: x2 = x2 + 210 # Magically disappears when this line is
commented out.
print end B:,x1,x2
  print pre B:,x1,x2
  B()
  print end A:,x1,x2
A()

# same error message...
 $ ./x1x2.py
begin A:
Pre B: 123 456
begin B: 123
Traceback (most recent call last):
  File ./x1x2.py, line 13, in module
A()
  File ./x1x2.py, line 11, in A
B()
  File ./x1x2.py, line 7, in B
print begin B:,x1,x2
UnboundLocalError: local variable 'x2' referenced before assignment

I guess it is something to do with the scoping of duck typing.

I WAS expecting that the A.x2 was visable until x2 is somehow (by
assignment) made local.  I guess I am learning that what you do to a
variable in the middle of scope (even in an unreachable statement)
effects the entire scope.  Is there anyway to force x2 to be A.x2
(without declaring it to be a global.x2)?  Maybe I can put it into a
A.local class...

The result sh/could be:
begin A:
pre B: 123 456
begin B: 123 456
end B: 123 666
end A: 123 666

ThanX
NevilleD

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


Re: proc A def/calls proc B: variable scoping rules.

2006-08-15 Thread NevilleDNZ
I inserted x1,x2 into A to force a wider scope and it works.

#!/usr/bin/env python
def A():
  print begin A:
  A.x1=123;
  A.x2=456;
  def B():
print begin B:,A.x1,A.x2
A.x2 = A.x2 + 210; # problem gone.
print end B:,A.x1,A.x2
  print pre B:,A.x1,A.x2
  B()
  print end A:,A.x1,A.x2
A()

$ ./z1z2.py
begin A:
pre B: 123 456
begin B: 123 456
end B: 123 666
end A: 123 666

$ python -V
Python 2.5b3

I checked: This method even handles recursion giving a new instance of
A.x2 each call.
Is this the official way to scope/inherit scopes in sub procs?

ThanX
NevilleD

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


Re: proc A def/calls proc B: variable scoping rules.

2006-08-15 Thread NevilleDNZ

Steve Holden wrote:
 No. It's too horrible to contemplate without getting mild feelings of
 nausea. What exactly is it you are tring to achieve here (since I assume
 your goal wasn't to make me feel sick :-)?

It is part of an algorithum:
#!/usr/bin/env python
def A(k, x1, x2, x3, x4, x5):
  def B():
k = k - 1;
B.out=A.out=A(k, B, x1, x2, x3, x4)
return B.out
  if k = 0: A.out = x4 + x5
  else: B()
  return A.out
print A(10, 1, -1, -1, 1, 0);
#   correct output is -67

The scope of k remains one problem, as it is passed as an argument to
A.

I think x1,x2,x3,x4 are meant to be lambdas as well... :-)
N

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


Re: proc A def/calls proc B: variable scoping rules.

2006-08-15 Thread NevilleDNZ

Steven D'Aprano wrote:
 Basically, when you access a variable name on the left hand side of an
 assignment (e.g. a = 1) ANYWHERE in a function, that name is local to
 that function UNLESS it has been declared global.
ThanX Steven, I am still getting used to python scoping rules. I didn't
realise that using a variable on the left affected the variables on the
right.  I WAS trying to avoid making the variable GLOBAL, and just pick
it out of the superior proc's scope.

 When you access a variable name as the right hand side of an assignment,
 or as an expression (e.g. print a), Python searches for it following the
 scoping rules: first it searches for it in the function's local variables,
 then the local variables of the next higher scope, and so on, and finally
 it searches for it amongst the globals (which is the top-level scope of
 everything).
I am more used to nested scopes, as in pascal/C.

 Play around with the code and see if it makes sense.
I will certainly dabble with your example further.

Many ThanX
NevilleD

BTW: here is my poor attempt at porting the man boy test algorithum
to python.  As you can see in python I am still a boy... :-)

$ cat ./man_boy_test.py
#!/usr/bin/env python
def A(k, x1, x2, x3, x4, x5):
  A.k=k
  def B():
A.k = A.k - 1
B.out=A.out=A(A.k, B, x1, x2, x3, x4)
return B.out
  if A.k = 0: A.out = x4() + x5()
  else: B()
  return A.out
if A(10,lambda:1,lambda:-1,lambda:-1,lambda:1,lambda:0)==-67:
  print man
else: 
  print boy
# end man_boy_test.py

$ ./man_boy_test.py
boy

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