Jump to content
  • Advertisement
Sign in to follow this  
Tutorial Doctor

Python Keyword Arguments for Config files?

This topic is 1079 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I saw a configuration file for a camera in a 3D program and tried to model it using python:

#useful for config files?

#If the following variable is false, no camera will exist?
camsOn=True

def camera(**settings):
	global camsOn
	if camsOn:
		return settings
	else:
		print 'Can\'t return settings'
		return {}


cam1 = camera(mode='PERS',radius=0,focus=(0,0,0),angle=(0,0,0),frustrum=0)
cam2 = camera(mode='ORTHO')
# the power of a function is that logic can be added

 
cam1['angle']=(23,68,79)
print cam1['angle']


# FUNCTIONS
def get_settings(cam):
	global camsOn
	if camsOn:
		for settings in cam:
			print str(settings) + ' = ' + str(cam[settings])
	else:
		print 'Can\'t get settings'
		return {}


get_settings(cam1)
print
get_settings(cam2)

I see here I could have used a dictionary for the settings, but the advantage of having it as a function is that additional logic can be added. 

This was done pretty quickly, and is probably not the best way.

 

But what would be the best way?

 

Anyone know of any other uses for keyword arguments? I have seen a few, but this could be a cool use?

 

Making a class seemed to be too much.

 

Attempts were made here:

http://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python

http://stackoverflow.com/questions/8225954/python-configuration-file-any-file-format-recommendation-ini-format-still-appr

Edited by Tutorial Doctor

Share this post


Link to post
Share on other sites
Advertisement

First off, it's generally bad form to embed print statements inside a function that returns a value. What if I want to call it in a non-console context? Given Python's native tuples, you can return both the constructed object and an error string—or, even better, raise an exception on error.

 

 

But what would be the best way?

 

Anyone know of any other uses for keyword arguments? I have seen a few, but this could be a cool use?

 

 

The general use for keyword arguments is cases where some of them are optional. That way you don't have to provide a bunch of None values for parameters you don't care about.

Share this post


Link to post
Share on other sites

Thanks for the reply Oluseyi. I will fix the print statements. I am really wondering why a solution like this wasn't mentioned on stack overflow. Is it a bad idea? It seems like it would work nicely. It seems either they use dictionaries or they get complex.

Edited by Tutorial Doctor

Share this post


Link to post
Share on other sites

I am really wondering why a solution like this wasn't mentioned on stack overflow.


Isn't that what is the accepted answer here?

 

Is it a bad idea? It seems like it would work nicely. It seems either they use dictionaries or they get complex.


Yours is a dictionary wrapped in a function, isn't it? If you're writing configuration purely for a Python program, why not make Python itself the configuration language? It's only worthwhile to invest in a different configuration format if you have to share it with other environments.

Share this post


Link to post
Share on other sites

What type of use case are you looking for? There are many ways to handle configuration in python and each offers very different pros and cons but typically are good for specific uses.

 

Keyword arguments can be useful but I try to avoid **kwargs style syntax because it can make it difficult to understand what types of arguments the function can take.

 

I like to usually use properties + builders to accomplish configuration like the following:

#useful for config files?

#If the following variable is false, no camera will exist?
camsOn=True


class Camera(object):
    def __init__(self, **settings):
        self._settings = settings

    @property
    def all_settings(self):
        """Be able to get all settings and present them as a dictionary but is read only."""
        return dict(self._settings)

    @property
    def mode(self):
        return self._settings.get('mode')

    @property
    def radius(self):
        return self._settings.get('radius')

    @property
    def focus(self):
        return self._settings.get('focus')

    @property
    def angle(self):
        return self._settings.get('angle')

    @angle.setter
    def angle(self, value):
        """An example of a setter but by default properties will be read only."""
        self._settings['angle'] = value

    @property
    def frustrum(self):
        # This is a function so you can add any additional logic here.
        return self._settings.get('frustrum')


def camera(**settings):
    if camsOn:
        return Camera(**settings)

    # Also could raise here if no camera is an error or the user should know about it.
    return None


cam1 = camera(mode='PERS',radius=0,focus=(0,0,0),angle=(0,0,0),frustrum=0)
cam2 = camera(mode='ORTHO')
# the power of a function is that logic can be added

 
cam1.angle = (23,68,79)
print cam1.angle


# FUNCTIONS
def get_settings(cam):
    global camsOn
    if camsOn:
        for settings in cam.all_settings:
            print str(settings) + ' = ' + str(cam[settings])
    else:
        print 'Can\'t get settings'
        return {}


get_settings(cam1)
print
get_settings(cam2)

I know classes seem overkill but they allow you to be extremely explicit and have defaults automatically specified as well as easy usage because there is no need to care if a particular setting exists or not. Also, properties allow "read only" values if you do not have a setter. And finally you can change the source of the configuration any time without changing any of the usage code because you have abstracted it out. For instance you could read this information from a file in the builder and pass it into the object and you would use it the same as if you just used a flat dictionary.

 

It all depends on your use case but in the method above you could have logic specific to the settings either in the property functions or the setter or the builder that creates the settings object.

Edited by slicksk8te

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!