Welcome to pypref V. 3.1.0 documentation!

PYthon PREFrences or pypref is a python implementation to creating application’s configuration, preferences or settings file and dynamically interacting, updating and pulling them. Most applications have default preferences and in general those are created and stored in a text file (.ini, xml, json, etc). At some point preferences are pulled and updated by the application and/or users. pypref is especially designed to take care of this task automatically and make programming application’s preferences more desirable. In addition, pypref allows creating dynamic preferences that will be evaluated real time. This becomes handy in plethora of applications for authentication, automatic key generation, etc.

Installation guide:

pypref is a pure python 2.7.x module that needs no particular installation. One can either fork pypref’s github repository and copy the package to python’s site-packages or use pip as the following:

pip install pypref

Package Functions:

pypref.get_version()

Get pypref’s version number.

pypref.get_author()

Get pypref’s author’s name.

pypref.get_email()

Get pypref’s author’s email.

pypref.get_doc()

Get pypref’s official online documentation link.

pypref.get_repository()

Get pypref’s official online repository link.

pypref.get_pypi()

Get pypref pypi’s link.

Usage:

This example shows how to use pypref.

from __future__ import print_function
from pypref import Preferences

#  create preferences instance
pref = Preferences(filename="preferences_test.py")

# create preferences dict example
pdict = {'preference 1': 1, 12345: 'I am a number'}

# set preferences. This would automatically create preferences_test.py
# in your home directory. Go and check it.
pref.set_preferences(pdict)

# lets update the preferences. This would automatically update
# preferences_test.py file, you can verify that.
pref.update_preferences({'preference 1': 2})

# lets get some preferences. This would return the value of the preference if
# it is defined or default value if it is not.
print(pref.get('preference 1'))

# In some cases we must use raw strings. This is most likely needed when
# working with paths in a windows systems or when a preference includes
# especial characters. That's how to do it ...
pref.update_preferences({'my path': 'C:\\Users\\Me\\Desktop'})

# multi-line strings can also be used as values
multiline="""this is a
multi-line
value
"""
pref.update_preferences({'multiline preference': multiline})

# Sometimes preferences to change dynamically or to be evaluated real time.
# This also can be done by using dynamic property. In this example password
# generator preference is set using uuid module. dynamic dictionary
# must include all modules name that must be imported upon evaluating
# a dynamic preference
pre = {'password generator': "str(uuid.uuid1())"}
dyn = {'password generator': ['uuid',]}
pref.update_preferences(preferences=pre, dynamic=dyn)

# lets pull 'password generator' preferences twice and notice how
# passwords are different at every pull
print(pref.get('password generator'))
print(pref.get('password generator'))

# those preferences can be accessed later. Let's simulate that by creating
# another preferences instances which will automatically detect the
# existance of a preferences file and connect to it
newPref = Preferences(filename="preferences_test.py")

# let's print 'my path' preference
print(newPref.get('my path'))
print(newPref.get('multiline preference'))

Preferences main module:

class pypref.Preferences.Preferences(directory=None, filename='preferences.py', *args, **kwargs)

Bases: object

This is pypref main preferences class definition. This class is used to create, load and update application’s preferences dictionary in memory and in file. At initialization, a preferences dictionary will be pulled from the given directory and filename if existing. Otherwise, preferences file will be created and preferences dictionary will be initialized to an empty dictionary. Preferences can be accessed like any python dictionary by slicing a key preference [key] or by using get method.

When used in a python application, it is advisable to use Preferences singleton implementation and not Preferences itself. if no overloading is needed one can simply import the singleton as the following:

from pypref import SinglePreferences as Preferences

Recommended overloading implementation, this is how it could be done:

from pypref import SinglePreferences as PREF

class Preferences(PREF):
    # *args and **kwargs can be replace by fixed arguments
    def custom_init(self, *args, **kwargs):
        # hereinafter any further instanciation can be coded

In case overloading __init__ is needed, this is how it could be done:

from pypref import SinglePreferences as PREF

class Preferences(PREF):
    # custom_init will still be called in super(Preferences, self).__init__(*args, **kwargs)
    def __init__(self, *args, **kwargs):
        if self._isInitialized: return
        super(Preferences, self).__init__(*args, **kwargs)
        # hereinafter any further instanciation can be coded
Parameters
  1. directory (None, path): The directory where to create preferences file. If None is given, preferences will be create in user’s home directory.

  2. filename (string): The preferences file name.

  3. *args (): This is used to send non-keyworded variable length argument list to custom initialize. args will be parsed and used in custom_init method.

  4. **kwargs (): This allows passing keyworded variable length of arguments to custom_init method. kwargs can be anything other than ‘directory’ and ‘filename’.

N.B. args and kwargs are not used by __init__ method but passed to custom_init at the end of initialization. custom_init method is an empty method that can be overloaded

property directory

Preferences file directory.

property filename

Preferences file name.

property fullpath

Preferences file full path.

property preferences

Preferences dictionary copy.

property dynamic

Dynamic dictionary copy.

custom_init(*args, **kwargs)

Custom initialize abstract method. This method will be called at the end of initialzation. This method needs to be overloaded to custom initialize Preferences instances.

Parameters
  1. *args (): This is used to send non-keyworded variable length argument list to custom initialize.

  2. **kwargs (): This allows passing keyworded variable length of arguments to custom_init method. kwargs can be anything other than ‘directory’ and ‘filename’.

get(key, default=None)

Get the preferences value for the given key. If key is not available then returns then given default value.

Parameters
  1. key (object): The Key to be searched in the preferences.

  2. default (object): The Value to be returned in case key does not exist.

Returns
  1. value (object): The value of the given key or given default value is key does not exist.

check_preferences(preferences)

This is an abstract method to be overloaded if needed. All preferences setters such as set_preferences and update_preferences call check_preferences prior to setting anything. This method returns a check flag and a message, if the flag is False, the message is raised as an error like the following:

flag, m = self.check_preferences(preferences)
assert flag, m
Parameters
  1. preferences (dictionary): The preferences dictionary.

Returns
  1. flag (boolean): The check flag.

  2. message (string): The error message to raise.

set_preferences(preferences, dynamic=None)

Set preferences and write preferences file by erasing any existing one.

Parameters
  1. preferences (dictionary): The preferences dictionary.

  2. dynamic (None, dictionary): The dynamic dictionary. If None dynamic dictionary won’t be updated.

set_dynamic(dynamic)

Set dynamic and write preferences file by erasing any existing one.

Parameters
  1. dynamic (dictionary): The dynamic dictionary.

update_preferences(preferences, dynamic=None)

Update preferences and dynamic dictionaries and update preferences file.

Parameters
  1. preferences (dictionary): The preferences dictionary.

  2. dynamic (dictionary): The dynamic dictionary. If None is given, dynamic dictionary won’t get updated

class pypref.Preferences.SinglePreferences(*args, **kwargs)

Bases: pypref.Preferences.Preferences

This is singleton implementation of Preferences class.