Jump to content

check my python?


Dak

Recommended Posts

I'm learning python; would it be ok to paste up a python script that i wrote, and have it critisised?

 

If not, then i'll find a dedicated python forum, but id rather have people that i at least vaguely know critisise it, and i'd rather have an idea about how skilled the commenter is.

 

the code is for a text-based menu system, where you can define your own menus. its a few small functions and one class. the whole thing is ~200 lines long.

 

i'd mainly like critisism on:

 

my comments (how useful they are)

the use of the class/OOPage

overall structure and modus operandi.

 

how well the good/flexible the menu system is is of secondary inportance (it's not too good, but it was mainly a practice thing for classes and oop), but comments on that would obviously be appreciated aswell.

 

so yeah, is that ok?

Link to comment
Share on other sites

Cool, cheers guys.

 

here it be. theres some menu data in there, so that the menu is functional (i.e., it's not just a skeleton menu code, it's got some actual menus programmed in so it can be played with)

 

#######################################################################
#################### Text-based menu system ###########################
#######################################################################
#
#
# By:      Dak
# Ver:     1.0.1.0
# Date:    29/08/06
# Licence: GNU/GPL v2 http://www.gnu.org/licenses/gpl.txt
"""
useage:

blah = Menu('description', [submenu], 'text', 'help')

(note: to ignore any perameter, leave it blank like this: '', or for the submenu: [])


blah: menu items can be named anything, as long as they are more than one charactor long.
       menu items name's must be registered in the list 'listy' as strings

description:    this gets displayed by other menus when linking to this menu item.

[submenu]:      list of functions/menu items to link to

text:       introductory text to be displayed at the top of the menu

help:       displayed if h is pressed on that menu. default is 'there is no helpful information
           associated with this item'

the submenu = ['item1', 'item2', etc]

an item can = 'submenu item' or ['submenu item', 'discription override', 'condition']            

eg:  ['item1', ['item3', 'discription override', 'condition'], ['item4', '', 'condition']]

item: another menu, function, or short snippet of code to be included in the menu.

description override: text to be displayed whilst linking to a menu item. if blank,
                       self.description is used

conditional:        entered as a string, eg 'x == 4'. the menu item will only be displayed
                   if this condition is true. 


"""
############## Update history #########
#
# 20/08/06 -- 1.0.0.0 -- First stable. Menu class, for menus. each menu can have a description,
# a list of other menus/functions to display as options, an intro blurb, and a help file. 'back'
# functionality (up to 9 backs).
# 29/08/06 -- 1.0.1.0 -- fixed goback function, general tweakage. added some test menu data
#
############## Roadmap ################
#
# 
#
############## Bugs ###################
#
# 
#
############## Glossary ###############
#
# things with 'back' in their name are for the goback feature
# listy and listy2 are registrys of the menu items.
# str2var and str2con change text strings into python recognisable variables or conditionals
#
############## Development ############
#
# 
#
#######################################


class Menu:
   def __init__(self, description, submenu, text, hellp):
       self.description = description #for use in other menus (submenu description)
       self.submenu2 = submenu # list of other menus/actions
       self.submenu = [] # this will be the submenu used. generated on the fly.
       self.text = text #introductory blurb to menu
       self.hellp = hellp # help item

   def display(self): # main bit
       self.backshift()
       self.mutate()
       self.write()
       self.enact()

   def backshift(self): # handles the 'back' command
       global backwards, current, goback, back, back2, back3, back4, back5, back6, back7, back8, back9
       if backwards == 1: #if we're going backwards, dont refresh the go-back list.
           backwards = 0 #incase we start going forwards
           goback = current # for starting to go forwards again
       elif goback != current: # refresh the backwards list, except upon menu refresh
           back9 = back8       # ^ eg on invalid input
           back8 = back7
           back7 = back6
           back6 = back5
           back5 = back4
           back4 = back3
           back3 = back2
           back2 = back
           back = goback
           goback = current

   def mutate(self): # removes conditional menu items who's condition is not met
       self.submenu = [] # reset submenu
       loop = 0
       while loop < len(self.submenu2):
           try:
               if len(self.submenu2[loop][2])!=1: # if there's actually a conditional
                   if str2con(self.submenu2[loop][2]) == False: #and it's not met
                       loop +=1 # dont include menu item
                   else: #otherwize
                       self.submenu.append(self.submenu2[loop]) #do 
                       loop +=1
               else: # if theres no conditional (double-entry menu-items, [[a,b]])
                   self.submenu.append(self.submenu2[loop])
                   loop +=1
           except:# if submenu2[loop][2] isn't a conditional (single-entry menu-items: [a]), ie
               self.submenu.append(self.submenu2[loop]) # ^ submenu2[loop][2] will be a single
               loop += 1                                # ^ character

   def write(self): # displays the menu
       print self.text, '\n'*3 # print the intro blurb
       loop = 1
       for n in self.submenu: # print the menu itself
           print loop, ': ',
           if len(n[1]) != 1 and len(n[1]) != 0:  # if theres an override text entry...
               print n[1] # ...display it...
           else: #...otherwize...
               try:
                   print str2var(n).description #...display the default description
               except:
                   print str2var(n[0]).description
           loop += 1
       print 'b :  back a screen'
       print 'm :  main menu'
       print 'h :  help'
       print 'q :  quit'
       print '\n'*2

   def enact(self): # grabs input and reacts
       global backwards, current, goback, back, back2, back3, back4, back5, back6, back7, back8, back9
       x = raw_input('')
       x = x.lower()
       try:
           x = int(x)
       except:
           pass 
       if x == 'q' or x == 'quit':
           loop = 1
           while loop == 1:
               x = raw_input('are you sure you want to quit? (y/n?)')
               if x.lower() == 'y':
                   raise SystemExit
               elif x.lower() == 'n':
                   loop = 0
       elif x == 'b' or x == 'back':
           current = back
           back = back2
           back2=back3
           back3=back4
           back4=back5
           back5=back6
           back6=back7
           back7=back8
           back8=back9
           backwards = 1
       elif x == 'm' or x == 'main':
           current = mainMenu
       elif x == 'h' or x == 'help':
           if self.hellp == '' or self.hellp == ' ':
               print 'there is no helpful information associated with this item :-(' #default help menu entry
           else:
               print self.hellp
           pause = raw_input('\n\npress any key to continue') # should return to loop
       else:
           # check if the selection is valid
           try:
               #check if it's a single menu entry
               menuitem = 0
               loop = 0
               while loop < len(listy):
                   if listy[loop] == self.submenu[x-1]:
                       menuitem = 1
                       current = str2var(self.submenu[x-1])
                   loop +=1
               #check to see if it's a multiple menu entry
               loop = 1
               while loop < len(listy):
                   if listy[loop] == self.submenu[x-1][0]:
                       menuitem = 1
                       current = str2var(self.submenu[x-1][0])
                   loop += 1
               # otherwize, try to execute it.    
               if menuitem == 0:
                   exec(self.submenu[x-1][0])
           except: # if the selection is invalid
               if x == ' ' or x == '':
                   x = 'that'
               print x, 'is not a valid selection. \n\n'

def genlisty2(): #generates listy2 from listy.
   x = ''
   for n in listy:
       x = x+', '+n
   x = x.replace(', ', '[', 1)
   x = 'listy2 = '+x+']'
   return x


def str2var(x): # changes strings into python-recognisable variables via menu registrys (listy
               # ^ and listy2)
   x = listy2[listy.index(x)]
   return x

def str2con(x): # changes strings into python-recognisable conditionals
try:
	x = 'y = bool('+x+')'
	exec(x)
	if y == True:
		return True
	else:
		return False
except NameError: #if a var in the condition isn't set
	return False


#####################Menu data goes here###########
#blah = Menu('description', [submenu], 'text', 'help')
#submenu: [['menuitem', 'description override', 'conditional'],'menuitem2']	    

mainMenu = Menu('main menu', ['menu1', 'menu2', 'menu9', 'menu4', 'menu5', 'menu15', 'menu20'], 'Choose a feature to test', 'see source (up the top) for what stuff like "discription override" means')
menu1 = Menu('test discription override', ['menu6', ['menu6', 'a banana. not a menu, and if it was, it wouldnt be the same menu as above. honestly.']], 'the below menus are the same, but the second has its default discription overriden', 'press m or b to go back to the main menu once youve gotten bored')
menu2 = Menu('test help entries', ['menu7', 'menu8'], 'menus with and without help. whooooo!', '')
menu4 = Menu('test menu linkings', ['menu12'], '', '')
menu5 = Menu('test linking to functions', ['menu14'], 'test linking to functions', '')
menu15 = Menu('test empty perameters', [['menu16', '(this menu has no discription, and a discription override. the next item is the same menu with no override)'], 'menu16', 'menu17', 'menu18', 'menu19'], 'menu items that have blank perameters', 'i.e., self.discription, self.hellp, self.submenu, or self.text = ""')
menu20 = Menu('test the back feature', ['menu21'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')

menu6 = Menu('an empty menu to help test discription overrides', [], 'press b to return to the last screen', '')

menu7 = Menu('a menu with some help', ['menu8'], 'press h. marvel at the helpfull information. go on, you know you want to.', 'press some buttons and then press return ;)')
menu8 = Menu('a menu with no help', ['menu7'], 'press h. witness the wondorously useful default help message.', '')

menu9 = Menu('conditional menu', [['menu10', '', 'condition == 0'], ['menu11', '', 'condition == 1'], ['swapcon()', "change the global variable \'condition\'"], ['print "the value of the variable \'condition\' is", condition', "check the value of the variable \'condition\'"]], 'test the conditional display feature', "change the variable \'condition\', and the menu should display differently")
menu10 = Menu('conditional test 1', ['menu9'], 'you should only be able to reach here if "condition" is 0', 'dont forget, b = back')
menu11 = Menu('conditonal test 2', ['menu9'], 'you should only be able to reach here if condition = 1', 'b is back.')

menu12 = Menu('menu12', ['menu13'], 'this is menu 12, and should link to menu 13', '')
menu13 = Menu('menu13', ['menu12'], 'this is menu13, and should link to menu 12', '')

menu14 = Menu('a menu with a function', [['domath()', 'add a number to two']], 'the entry below points to a function, not anothe menu', '')

menu16 = Menu('', ['menu15'], 'this menu has no discription', 'hello')
menu17 = Menu('a menu with no submenu', [], 'this menu has no submenu', 'hiya')
menu18 = Menu('a menu with no intro text', ['menu15'], '', 'hi')
menu19 = Menu('a menu with no help', ['menu15'], 'this menu has no help', '')

menu21 = Menu('1 screen from the start', ['menu22'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu22 = Menu('2 screens from the start', ['menu23'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu23 = Menu('3 screens from the start', ['menu24'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu24 = Menu('4 screens from the start', ['menu25'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu25 = Menu('5 screens from the start', ['menu26'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu26 = Menu('6 screens from the start', ['menu27'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu27 = Menu('7 screens from the start', ['menu28'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu28 = Menu('8 screens from the start', ['menu29'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu29 = Menu('9 screens from the start', ['menu30'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu30 = Menu('10 screens from the start', [], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')

#
###################################################

####################Menu registry##################
#listy = ['mainMenu, ] #<-------- register all menus here as strings: ['a', 'b'] etc.
listy = ['mainMenu', 'menu1','menu2','menu4','menu5','menu6','menu7','menu8','menu9','menu10','menu11','menu12','menu13','menu14','menu15','menu16','menu17','menu18','menu19', 'menu20','menu21','menu22','menu23','menu24','menu25','menu26','menu27','menu28','menu29','menu30',] #<-------- register all menus here as strings: ['a', 'b'] etc.
exec(genlisty2()) # generates listy2 from listy
###################################################

#### global declorations and functions for the menus###
#
condition = 0

def swapcon():
   global condition
   if condition == 1:
       condition = 0
   elif condition == 0:
       condition = 1

def domath():
   x = raw_input('what number would you like to add to two?')
   print x, '+ 2 =', int(x)+2, '\n\n'
   return
#    
###########################################################


# stuff for the 'go back' function.
current= mainMenu
backwards = 0
goback = mainMenu
back = mainMenu
back2= mainMenu
back3= mainMenu
back4= mainMenu
back5= mainMenu
back6= mainMenu
back7= mainMenu
back8= mainMenu
back9= mainMenu

# mainloop
while 1 == 1:
   #do = crash #generate linecount
   try:
       current.display()
   except SystemExit:
       do=crash #crash . easyer than clicking 'no, i dont want to completely exit' each time in idle

Link to comment
Share on other sites

I didn´t read the code but from a brief look at the appearance:

 

- A four-digit version counter and a licence for a stupid first attempt to learn Python ?!?

- Update history, roadmap, glossary, bugs is complete overkill.

- Usage part is nice, especially because iirc the parts inbetween """ and """ are displayed as class-documentation within Python. Put all relevant parts there and screw the irrelevant stuff I mentioned in the previous two points.

- Don´t comment methods and classes with the #, use the """ because it´s then also displayed within the Python class documentation.

- commenting an else-statement with "# otherwise" is pointless. Either skip it or (preferrably) explicitely write what cases this "otherwise" covers.

- Make the comments more visible as such and try to format them better. Example:

class Menu:
   def __init__(self, description, submenu, text, hellp):
       self.description = description #for use in other menus (submenu description)
       self.submenu2 = submenu # list of other menus/actions
       self.submenu = [] # this will be the submenu used. generated on the fly.
       self.text = text #introductory blurb to menu
       self.hellp = hellp # help item

would better read

class Menu:
   def __init__(self, description, submenu, text, hellp):
       self.description = description  # for use in other menus (submenu description)
       self.submenu2 = submenu         # list of other menus/actions
       self.submenu = []               # this will be the submenu used. generated on the fly.
       self.text = text                # introductory blurb to menu
       self.hellp = hellp              # help item

 

- In contrast to what many beginners seem to believe, adding a lot of lines like #####... or -------... or similar does not improve the readability of the code unless it is used extremely sparsely (in which case one can as well split the stuff up in several files which has a much better readability). I don´t know the reason for it but somehow these "I make clear that something new comes here"-lines have worsened the readability of a code or text in almost all cases I´ve seen.

 

EDIT: Not related to your original question but as a possible follow-up idea: The menu-construction code looks long and boring which is practically unavoidable. How about improving the functionality to loading, editing and saving the menu strucuture ?

Link to comment
Share on other sites

I didn´t read the code but from a brief look at the appearance:

 

- A four-digit version counter and a licence for a stupid first attempt to learn Python ?!?

- Update history' date=' roadmap, glossary, bugs is complete overkill.

- Usage part is nice, especially because iirc the parts inbetween """ and """ are displayed as class-documentation within Python. Put all relevant parts there and screw the irrelevant stuff I mentioned in the previous two points.[/quote']

 

tbh, those parts i just put in because i want to use them to see how useful they are (if that makes sence)

 

eg, in another program i wrote (which is alot longer, and i spent alot longer doing over many sessions), i found the update history helped me pin down bugs i'd introduced, 'bugs' reminded me what needed fixing and the 'roadmap' helped me actually remember where i was trying to go with the program, although i admit, given that this is tiny and i wrote it in one session and another tweaking/fixing session, it wasnt usefull atall in this case (still, im only learning :P)

 

not sure what my rational for the licence was :embarass::D

 

- commenting an else-statement with "# otherwise" is pointless. Either skip it or (preferrably) explicitely write what cases this "otherwise" covers.

 

hehe, guess that does look rather odd.

 

there was a method to my madness, but i guess if it's not apparent, its not good commenting.

 

cheers for the other comments on the comments aswell.

 

by-the-way, ultimately it was your help in irc, followed by yet another read of the tutorial, that helped me finally 'get' the OOPage, so thanks again :)

 

EDIT: Not related to your original question but as a possible follow-up idea: The menu-construction code looks long and boring which is practically unavoidable. How about improving the functionality to loading, editing and saving the menu strucuture ?

 

not quite sure i follow? when you say menu-construction code, do you mean the lists with the menu data in?

Link to comment
Share on other sites

actually, i've just realised how large the code is with the top-bit and the menu data, so if anyone else wants to comment, for convienience the main bit is:

 

"""
useage:

blah = Menu('description', [submenu], 'text', 'help')

(note: to ignore any perameter, leave it blank like this: '', or for the submenu: [])


blah: menu items can be named anything, as long as they are more than one charactor long.
       menu items name's must be registered in the list 'listy' as strings

description:    this gets displayed by other menus when linking to this menu item.

[submenu]:      list of functions/menu items to link to

text:       introductory text to be displayed at the top of the menu

help:       displayed if h is pressed on that menu. default is 'there is no helpful information
           associated with this item'

the submenu = ['item1', 'item2', etc]

an item can = 'submenu item' or ['submenu item', 'discription override', 'condition']            

eg:  ['item1', ['item3', 'discription override', 'condition'], ['item4', '', 'condition']]

item: another menu, function, or short snippet of code to be included in the menu.

description override: text to be displayed whilst linking to a menu item. if blank,
                       self.description is used

conditional:        entered as a string, eg 'x == 4'. the menu item will only be displayed
                   if this condition is true. 


"""

class Menu:
   def __init__(self, description, submenu, text, hellp):
       self.description = description #for use in other menus (submenu description)
       self.submenu2 = submenu # list of other menus/actions
       self.submenu = [] # this will be the submenu used. generated on the fly.
       self.text = text #introductory blurb to menu
       self.hellp = hellp # help item

   def display(self): # main bit
       self.backshift()
       self.mutate()
       self.write()
       self.enact()

   def backshift(self): # handles the 'back' command
       global backwards, current, goback, back, back2, back3, back4, back5, back6, back7, back8, back9
       if backwards == 1: #if we're going backwards, dont refresh the go-back list.
           backwards = 0 #incase we start going forwards
           goback = current # for starting to go forwards again
       elif goback != current: # refresh the backwards list, except upon menu refresh
           back9 = back8       # ^ eg on invalid input
           back8 = back7
           back7 = back6
           back6 = back5
           back5 = back4
           back4 = back3
           back3 = back2
           back2 = back
           back = goback
           goback = current

   def mutate(self): # removes conditional menu items who's condition is not met
       self.submenu = [] # reset submenu
       loop = 0
       while loop < len(self.submenu2):
           try:
               if len(self.submenu2[loop][2])!=1: # if there's actually a conditional
                   if str2con(self.submenu2[loop][2]) == False: #and it's not met
                       loop +=1 # dont include menu item
                   else: #otherwize
                       self.submenu.append(self.submenu2[loop]) #do 
                       loop +=1
               else: # if theres no conditional (double-entry menu-items, [[a,b]])
                   self.submenu.append(self.submenu2[loop])
                   loop +=1
           except:# if submenu2[loop][2] isn't a conditional (single-entry menu-items: [a]), ie
               self.submenu.append(self.submenu2[loop]) # ^ submenu2[loop][2] will be a single
               loop += 1                                # ^ character

   def write(self): # displays the menu
       print self.text, '\n'*3 # print the intro blurb
       loop = 1
       for n in self.submenu: # print the menu itself
           print loop, ': ',
           if len(n[1]) != 1 and len(n[1]) != 0:  # if theres an override text entry...
               print n[1] # ...display it...
           else: #...otherwize...
               try:
                   print str2var(n).description #...display the default description
               except:
                   print str2var(n[0]).description
           loop += 1
       print 'b :  back a screen'
       print 'm :  main menu'
       print 'h :  help'
       print 'q :  quit'
       print '\n'*2

   def enact(self): # grabs input and reacts
       global backwards, current, goback, back, back2, back3, back4, back5, back6, back7, back8, back9
       x = raw_input('')
       x = x.lower()
       try:
           x = int(x)
       except:
           pass 
       if x == 'q' or x == 'quit':
           loop = 1
           while loop == 1:
               x = raw_input('are you sure you want to quit? (y/n?)')
               if x.lower() == 'y':
                   raise SystemExit
               elif x.lower() == 'n':
                   loop = 0
       elif x == 'b' or x == 'back':
           current = back
           back = back2
           back2=back3
           back3=back4
           back4=back5
           back5=back6
           back6=back7
           back7=back8
           back8=back9
           backwards = 1
       elif x == 'm' or x == 'main':
           current = mainMenu
       elif x == 'h' or x == 'help':
           if self.hellp == '' or self.hellp == ' ':
               print 'there is no helpful information associated with this item :-(' #default help menu entry
           else:
               print self.hellp
           pause = raw_input('\n\npress any key to continue') # should return to loop
       else:
           # check if the selection is valid
           try:
               #check if it's a single menu entry
               menuitem = 0
               loop = 0
               while loop < len(listy):
                   if listy[loop] == self.submenu[x-1]:
                       menuitem = 1
                       current = str2var(self.submenu[x-1])
                   loop +=1
               #check to see if it's a multiple menu entry
               loop = 1
               while loop < len(listy):
                   if listy[loop] == self.submenu[x-1][0]:
                       menuitem = 1
                       current = str2var(self.submenu[x-1][0])
                   loop += 1
               # otherwize, try to execute it.    
               if menuitem == 0:
                   exec(self.submenu[x-1][0])
           except: # if the selection is invalid
               if x == ' ' or x == '':
                   x = 'that'
               print x, 'is not a valid selection. \n\n'

def genlisty2(): #generates listy2 from listy.
   x = ''
   for n in listy:
       x = x+', '+n
   x = x.replace(', ', '[', 1)
   x = 'listy2 = '+x+']'
   return x


def str2var(x): # changes strings into python-recognisable variables via menu registrys (listy
               # ^ and listy2)
   x = listy2[listy.index(x)]
   return x

def str2con(x): # changes strings into python-recognisable conditionals
try:
	x = 'y = bool('+x+')'
	exec(x)
	if y == True:
		return True
	else:
		return False
except NameError: #if a var in the condition isn't set
	return False


#####################Menu data goes here###########
#blah = Menu('description', [submenu], 'text', 'help')
#submenu: [['menuitem', 'description override', 'conditional'],'menuitem2']	    
####################Menu registry##################
#listy = ['mainMenu, ] #<-------- register all menus here as strings: ['a', 'b'] etc.
exec(genlisty2()) # generates listy2 from listy
###################################################

#### global declorations and functions for the menus###
#


# stuff for the 'go back' function.
current= mainMenu
backwards = 0
goback = mainMenu
back = mainMenu
back2= mainMenu
back3= mainMenu
back4= mainMenu
back5= mainMenu
back6= mainMenu
back7= mainMenu
back8= mainMenu
back9= mainMenu

# mainloop
while 1 == 1:
   #do = crash #generate linecount
   try:
       current.display()
   except SystemExit:
       do=crash #crash . easyer than clicking 'no, i dont want to completely exit' each time in idle

Link to comment
Share on other sites

In the end, there´s different levels of commenting so don´t assign my comments on your comments too much of importance. Two important criteria for chosing frequency and style of comments are:

- For whom are they supposed to be? Is it just for you so that you don´t get lost in the code? Is it for you in case you want to have a quick reference in case you are looking into the code again months/years later? Is it for others who work on the same project and possibly even the same files and methods as you? Is it for others who might have to look into the code later (for debugging or extensions)? Or is it even a tutorial for absolute beginners?

- What level of knowledge about programming and the topic that you´re programming for can you expect of the target audience? If you´re just commenting fro yourself and are new to the language, even commenting an else-statement with "otherwise" can be ok. In my experience, the more advanced the target level, the more "abstract" the comments can be. E.g. I wouldn´t comment all lines in a subroutine that orders some fields alphabetically, I´d just comment the routine with "sorts the fields alphabetically" and possibly state restrictions on what the entries of the fields may be or what other restrictions there might be.

 

In other words: Just ignore any of my statemetns about your commenting if you think they are irrelevant for you...

 

by-the-way, ultimately it was your help in irc, followed by yet another read of the tutorial, that helped me finally 'get' the OOPage, so thanks again

Glad I could help you. You are in fact the first SFN person I ever saw to start some project and actually finish it (looks at the staff awards and the letter to the authors of some creationist-video, the proposal to create a section for scientific experiments, ...).

 

The idea about loading, editing and saving was meant in the sense that you give the menu a method "save(filename)" which ... big surprise ... saves the menu structure to a file. If you want to use the menu in another programm, you could just load it with another method "load(filename)" instead of adding

mainMenu = Menu('main menu', ['menu1', 'menu2', 'menu9', 'menu4', 'menu5', 'menu15', 'menu20'], 'Choose a feature to test', 'see source (up the top) for what stuff like "discription override" means')
menu1 = Menu('test discription override', ['menu6', ['menu6', 'a banana. not a menu, and if it was, it wouldnt be the same menu as above. honestly.']], 'the below menus are the same, but the second has its default discription overriden', 'press m or b to go back to the main menu once youve gotten bored')
menu2 = Menu('test help entries', ['menu7', 'menu8'], 'menus with and without help. whooooo!', '')
menu4 = Menu('test menu linkings', ['menu12'], '', '')
menu5 = Menu('test linking to functions', ['menu14'], 'test linking to functions', '')
menu15 = Menu('test empty perameters', [['menu16', '(this menu has no discription, and a discription override. the next item is the same menu with no override)'], 'menu16', 'menu17', 'menu18', 'menu19'], 'menu items that have blank perameters', 'i.e., self.discription, self.hellp, self.submenu, or self.text = ""')
menu20 = Menu('test the back feature', ['menu21'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')

menu6 = Menu('an empty menu to help test discription overrides', [], 'press b to return to the last screen', '')

menu7 = Menu('a menu with some help', ['menu8'], 'press h. marvel at the helpfull information. go on, you know you want to.', 'press some buttons and then press return ;)')
menu8 = Menu('a menu with no help', ['menu7'], 'press h. witness the wondorously useful default help message.', '')

menu9 = Menu('conditional menu', [['menu10', '', 'condition == 0'], ['menu11', '', 'condition == 1'], ['swapcon()', "change the global variable \'condition\'"], ['print "the value of the variable \'condition\' is", condition', "check the value of the variable \'condition\'"]], 'test the conditional display feature', "change the variable \'condition\', and the menu should display differently")
menu10 = Menu('conditional test 1', ['menu9'], 'you should only be able to reach here if "condition" is 0', 'dont forget, b = back')
menu11 = Menu('conditonal test 2', ['menu9'], 'you should only be able to reach here if condition = 1', 'b is back.')

menu12 = Menu('menu12', ['menu13'], 'this is menu 12, and should link to menu 13', '')
menu13 = Menu('menu13', ['menu12'], 'this is menu13, and should link to menu 12', '')

menu14 = Menu('a menu with a function', [['domath()', 'add a number to two']], 'the entry below points to a function, not anothe menu', '')

menu16 = Menu('', ['menu15'], 'this menu has no discription', 'hello')
menu17 = Menu('a menu with no submenu', [], 'this menu has no submenu', 'hiya')
menu18 = Menu('a menu with no intro text', ['menu15'], '', 'hi')
menu19 = Menu('a menu with no help', ['menu15'], 'this menu has no help', '')

menu21 = Menu('1 screen from the start', ['menu22'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu22 = Menu('2 screens from the start', ['menu23'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu23 = Menu('3 screens from the start', ['menu24'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu24 = Menu('4 screens from the start', ['menu25'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu25 = Menu('5 screens from the start', ['menu26'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu26 = Menu('6 screens from the start', ['menu27'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu27 = Menu('7 screens from the start', ['menu28'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu28 = Menu('8 screens from the start', ['menu29'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu29 = Menu('9 screens from the start', ['menu30'], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')
menu30 = Menu('10 screens from the start', [], 'keep following the submenus, then see if you can return using the b button', 'you can only go back 10 screens, so you wont be able to make it ALL the way back')

to the code. Plus, I think it is a good exercise on how to save and store tree structures to a file.

Link to comment
Share on other sites

In the end' date=' there´s different levels of commenting so don´t assign my comments on your comments too much of importance. Two important criteria for chosing frequency and style of comments are:

- For whom are they supposed to be? Is it just for you so that you don´t get lost in the code? Is it for you in case you want to have a quick reference in case you are looking into the code again months/years later? Is it for others who work on the same project and possibly even the same files and methods as you? Is it for others who might have to look into the code later (for debugging or extensions)? Or is it even a tutorial for absolute beginners?

- What level of knowledge about programming and the topic that you´re programming for can you expect of the target audience? If you´re just commenting fro yourself and are new to the language, even commenting an else-statement with "otherwise" can be ok. In my experience, the more advanced the target level, the more "abstract" the comments can be. E.g. I wouldn´t comment all lines in a subroutine that orders some fields alphabetically, I´d just comment the routine with "sorts the fields alphabetically" and possibly state restrictions on what the entries of the fields may be or what other restrictions there might be.

 

In other words: Just ignore any of my statemetns about your commenting if you think they are irrelevant for you...[/quote']

 

well, technically they're for me atm, but ultimately, if i learn to program (i'm in a 'trying it out' stage atm) i'd like to eventually get into open-source free program writing, so i'll have to comment for other people.

 

my brain works rather oddly, so a consern (and something i'd like to nip in the bud early) is that my comments will make sence to me and only me :rolleyes:

 

so, whilst it's only one oppinion, any way in which you think my comments are sucky is relevent.

 

in answre to your criteria: mainly me, but also anyone else who looks at the code, and better than me :D

 

The idea about loading, editing and saving was meant in the sense that you give the menu a method "save(filename)" which ... big surprise ... saves the menu structure to a file. If you want to use the menu in another programm, you could just load it with another method "load(filename)" instead of adding

[snip] to the code. Plus, I think it is a good exercise on how to save and store tree structures to a file.

 

ah, gotcha (i think).

 

i was going to do it the other way round: i've got a cryptography program that im wrighting (mainly for the learning), and i was going to include the menu data in that file with the code, but keep the actual menu class in a seperate file (so i could reuse it in other programs, or replace it easily). would that be equivelent?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.