#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2

    Help cleaning this snippet. Also, strange syntax error.


    Code:
    class scrollbox():
    	def __init__(self,size,pos,backcolor=glob.color['white'],background=None,font=glob.font['main'],channel=None,alpha=None,textcolor=glob.color['black'])
    		self.size=size
    		self.pos=pos
    		self.font=font
    		self.background=background
    		self.alpha=alpha
    		self.channel=channel
    		self.display=True
    		self.lines=list()
    		#Put Everything Together:
    		self.surf=pygame.surface(size)
    		self.surf.set_alpha(self.alpha)
    		self.surf.convert()
    		if not (self.channel==None):
    			stackless.tasklet(self.receiving)()
    So, that's my initialization script for a little class I'm developing. I'm in Stackless with pygame, so you might want to omit the bits that rely on that if you wish to test.
    For some odd reason, it's raising a syntax error at the end of the argument list for the initialization. "Syntax error" has never been all too specific, and this time I have absolutely no idea as to what it might be referring to.

    Also, any way to make this look a little neater? It's kinda wonky because of all the initialization optional arguments.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481
    You need colon at the end of the long line

    def __init__(blah, blech, yuck):


    You objected last time I showed a different way to possibly produce "neat".

    Python has many ways to write programs that do the same thing. What are the use cases you have in mind? Are you using any of the funky stackless continuations? If not, why trouble yourself with stackless python?
    Code:
    ''' untested python3 code '''
    
    class scrollbox:
    
        '''
            code to demonstrate the mr909 scrollbox class
            with optional arguments removed from constructor.
            The object\'s textcolor and backcolor
            attributes can be accessed and set, but are now
            unavailable in the constructor.
        '''
    
        def __init__(self, size, pos):
            (self.size, self.pos,) = (size, pos,)
            self.backcolor = glob.color['white']
    
        @property
        def textcolor(self):
            """I'm the 'textcolor' property."""
            try:
                return self._textcolor
            except AttributeError:
                return glob.color['black']
    
        @textcolor.setter
        def textcolor(self, value):
            self._textcolor = value
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Gah! The colon! I should have caught onto that XD
    Thank you so much.

    I like using complex constructors with optional arguments simply because they keep the code consistent. If I want to know where such and such was changed, I just look for the original function call. I already know about four or so different scroll-boxes I'm creating (Main display, character display, inventory display, select-a-save)

    I like what you've shown me for some properties, however, and I'm considering just using those instead of some of the defaulting. Do you know if that style will work in 2.7?

    As for Stackless, I'm using the heck out of it. Channels allow me to micromanage the graphics much easier which in turn speeds up the game. Continuations keep most of the processes contained within themselves, which in turn helps me make the system more modular (at least, on my thinking) because each process doesn't need to explicitly refer to every other process that is being called.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,931
    Rep Power
    481
    Properties might work in 2.7 if you use a new style class

    class scrollbox(object):
    #...


    I'm not a 2.6, 2.7 expert. It also could be that if I found a variation between new style classes and python3 classes it would be subtle and unimportant to you.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    I recommend using **kwargs. That way you can pass some arguments to the constructor by keyword if you only want to change a few; or if you want to change all of them you can create a dict before creating your instance and pass it via the **dict unpacking syntax.

    I have actually recently been working on making a flexible scroll window class for pygame myself. I'll post a link after I polish it some more if you are interested.

    -Mek
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Originally Posted by Mekire
    I recommend using **kwargs. That way you can pass some arguments to the constructor by keyword if you only want to change a few; or if you want to change all of them you can create a dict before creating your instance and pass it via the **dict unpacking syntax.

    I have actually recently been working on making a flexible scroll window class for pygame myself. I'll post a link after I polish it some more if you are interested.

    -Mek
    Geh. I should have thought of that. XD

    Well, I'm using Stackless as well which might have some major bearing on implementation, but I'm probably savvy enough to convert it. I'd definitely probably learn something from it, so please, go right ahead.

    Could you show me a snippet to just do **kwargs with all that defaulting? I grok what you're saying but my mind is having trouble wrapping around what it would actually look like.

    EDIT: Oh and if you ever need anything I'm not the best coder but I've had more than a few clever ideas come by my head every now and again.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    The assignment line for my class:
    python Code:
    class ScrollWindow:
        def __init__(self,subrect,content,font,**kwargs):

    A method to process the kwargs:
    python Code:
    def process_kwargs(self,kwargs):
        """All of the following can be used as keyword arguments.  Any or all of
        them can be passed to the init by keyword, or a dict of them can be passed
        via the **dict keyword unpacking syntax."""
        self.kwargs = {"background"            : None,
                        "bg_color"             : (255,255,255),
                        "text_color"           : (0,0,0),
                        "highlight"            : True,
                        "highlight_color"      : (0,0,0,100),
                        "highlight_text_color" : (255,255,0),
                        "bar_bg_image"         : setup.GFX["bar_bg"],
                        "bar_button_images"    : [setup.GFX["button"].subsurface((0,0,24,25)),
                                                  setup.GFX["button"].subsurface((0,25,24,25))],
                        "bar_slider_image"     : setup.GFX["bar"]}
        for kwarg in kwargs:
            if kwarg in self.kwargs:
                self.kwargs[kwarg] = kwargs[kwarg]
            else:
                raise AttributeError("Invalid keyword: {}".format(kwarg))

    I actually leave mine as a dictionary because it suits my needs but if you desire you can make them proper class attributes using hasattr and setattr.

    The current state of my scroll window can be found here:
    http://code.google.com/p/pygame-scro...downloads/list
    Just unzip and run the file driver_test.py as main for an example. The window can also be dragged around the screen. Still very much a work in progress though.

    -Mek
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Heh. Thank you very much, I'll certainly get to work dissecting that.

    I find it funny how quite a bit of our style tendencies seem to be alike. My images are stored in a dictionary, you're using a hierarchical class as a container (although I do a lot of constants using that too.)

    I know absolute imports aren't usually considered kosher, but I'll show you what I got going.

    Code:
    import sys,random,stackless
    import pygame
    sys.path.append(".\\")
    from globs import *
    and then globs is just a set of classes for defining constants like so:

    Code:
    #Globs defines all global constants, including colors, fonts, etc.
    import pygame.font
    pygame.init()
    
    class cat():
    	skill	=	2
    	perk	=	3
    
    class sk():
    	persuasion	=	301
    
    class at():
    	ST	=	101
    	AG	=	102
    	TG	=	103
    	IT	=	104
    	WS	=	105
    	CH	=	106
    
    class color():
    	black	=	(0,0,0)
    	white	=	(255,255,255)
    	gray 	=	(128,128,128)
    	dimgray	=	(64,64,64)
    
    class font():
    	main	=	pygame.font.Font('freesansbold.ttf', 10)
    so that the calls to specific colors are neatly named as subclass attributes, like color.black. Define once, define everywhere.

    It reduced the dependencies on dictionaries for constants, to avoid "string typing", which can really become a problem in game naming.
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    I used to * import a module full of constants too; though I have since reformed. These days if I want to do similar I do something like:
    Code:
    import setup as su
    I have started to be a bit fanatical about keeping my global namespace tidy.

    Constantly yell at people in pygame who do:
    Code:
    from pygame.locals import *
    Similarly to the previous when using pygame I always use:
    Code:
    import pygame as pg
    because don't get me wrong; I'm still lazy.

    -Mek
  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    Well, at least for colors and fonts, the names are used in practically every little thing in the code. I'm making a mostly menu-based game, so color and font calls are EVERYWHERE.

    That's why I used the classes to wrap the constants in. It keeps the definitions compartmentalized without having large numbers of constants to clog up the global namespace. It's almost functionally equivalent to having a separate module defining them, then importing it.

    Like, say, if I had a module named "color" that just held the color definitions, I would still call it with color.black.

    I'm just always so curious as to why absolute imports are so taboo. I mean, I feel that in the manner I'm using them, they're fairly responsible.
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    For me the issue over using * imports is much more about being able to instantly know where the variable came from than anything else. If I'm reading another persons code and they use star imports I have to search for where items defined in other modules came from.

    I have seen pygame code where the coder writes 10 different modules and then collapses them all into one namespace. This makes dissecting the code impossible. Basically if I see a variable and it has no prefix, if it is all-caps, I will look in the global scope of that module; if it is lowercase I will assume it is local to where I'm looking. You should never have to hunt down a name to figure out where it was defined.

    -Mek
  22. #12
  23. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    76
    Rep Power
    2
    hmm... perhaps I'll do what you did and just import it as gl or something...

    Thanks

IMN logo majestic logo threadwatch logo seochat tools logo