Module variables
Cameron Zemek
grom_3 at optusnet.com.au
Wed May 28 12:18:15 EDT 2003
Okay I have been translating some pascal into python. I need to have
variables with module scope. atm I'm doing this with "global" in methods
that need to update the global variable. Is there a way todo this that
doesn't need each function to declare what global variables it will need.
Also what is the naming convention for variables and functions that are
internal to the module?
# expr.py
def GetChar():
global Look, input, index
try:
Look = input[index]
index = index + 1
except:
Look = '\n'
def Error(message):
print 'Error: ' + str(message) + '.'
def Abort(message):
raise 'Error: ' + str(message) + '.'
def Expected(message):
Abort(message + ' Expected')
def Match(char):
if Look == char:
GetChar()
else:
Expected("'" + str(char) + "'")
def IsAlpha(char):
return char.isalpha()
def IsDigit(char):
return char.isdigit()
def IsAddop(char):
return char in ['+', '-']
def IsMulop(char):
return char in ['*', '/']
def GetName():
if not IsAlpha(Look):
Expected('Name')
name = Look
GetChar()
return name
def GetNum():
value = 0
if not IsDigit(Look):
Expected('Integer')
while IsDigit(Look):
value = 10 * value + int(Look)
GetChar()
return value
def Emit(string):
print '\t' + str(string)
def Factor():
value = 0
if Look == '(':
Match('(')
value = Expression()
Match(')')
elif IsAlpha(Look):
value = Table[GetName()]
else:
value = GetNum()
return value
def Term():
value = Factor()
while Look in ['*', '/']:
if Look == '*':
Match('*')
value = value * Factor()
elif Look == '/':
Match('/')
value = value / Factor()
return value
def Expression():
if IsAddop(Look):
value = 0
else:
value = Term()
while IsAddop(Look):
if Look == '+':
Match('+')
value = value + Term()
elif Look == '-':
Match('-')
value = value - Term()
return value
def Assignment():
name = GetName()
Match('=')
Table[name] = Expression()
return Table[name]
def Init():
InitTable()
Reset()
def Reset():
global input, index
input = raw_input("$ ")
index = 0
GetChar()
# there is probably better way to do store variable values, but this works
for now
def InitTable():
global Table
Table = {}
for i in range(97, 122):
char = '%c' % i
Table[char] = 0
def Execute():
Init()
while Look != '.':
print Assignment()
Reset()
More information about the Python-list
mailing list