Python Notes

Wednesday, October 20, 2004

Inifile: an ini-style configuration template

IniFile is a ini-style configuration module that uses a template to define the configuration file structure. The code below includes some samples. Feel free to use as-is.


Library for reading and writing ini-style config files. The ini file
structure is provided as a class, with nested classes acting as the


# declare the ini file structure using a class statement
class MyIni(IniFile):
one = TypedAttribute(1)
two = TypedAttribute(2)
three = TypedAttribute(3, name='triple')
class NestedSection(IniSection):
str1 = TypedAttribute('one', name='str_one')
str2 = TypedAttribute('two', name='str_two')

# create a configuration instance
config = MyIni()

# read the config file

# write it back

-- sample ini file --
socketPort = 8080
threadPool = 10

bitmaps = /var/local/bitmaps



from metatemplate import GenericTemplate, GenericAttribute, TypedAttribute, next_attribute_id
from types import StringType
from inspect import isclass
import re

debug_inifile = 0

class IniSection(GenericTemplate):

re_section = re.compile(r'^\[(.*)\]')
re_unquote = re.compile(r'^(?P[\"\']?)(?P.*)(?P=openquote)$')

def log(self, line):
"""simple auxiliary log functions"""
if debug_inifile:
# should use the logger interface!
print line

def unquote(self, value):
"""unquotes strings reads from the config file"""
return self.re_unquote.match(value).groupdict()['content']

def read(self, fileobj):
"""reads the config file info from a file-like object"""

for line in fileobj:
#attr_name_list = [f[0] for f in self.__fields__]
attr_name_list = self.__attr__.keys()
line = line.strip()
if not line: continue
matchresult = self.re_section.match(line)
if matchresult:
sectionname =
self.log('Found section: %s' % sectionname)
while sectionname in attr_name_list:
# found a known section
section = getattr(self, sectionname, None)
if isinstance(section, IniSection):
self.log('Section: %s' % sectionname)
sectionname =
self.log('Section finished: %s' % sectionname)
# section name does refer to a section object
# ?should it raise a fatal exception/warning?
self.log('Section error: %s' % sectionname)
sectionname = None
# section is not a child of this node, it's a
# sibling; returns the section name
self.log('Unknown section: %s' % sectionname)
return sectionname
# found an attribute
name, value = line.split('=',1)
name = name.strip()
value = value.strip()
self.log('Normal attribute: %s = %s' % (name, value))

# retrieves the attribute using the alternative name
cls_attr_tuple = self.__class__.__attr__.get(name, None)
if not cls_attr_tuple:
# invalid attribute found in the config file!
# ? should it cause a exception or warning ?
print '1:', self.__class__.__fields__
print '2:', self.__class__.__attr__
print '3:', self.__class__.__attr__[name]
print '4:', cls_attr_tuple
print 'Error - Attribute not found: %s' % (name,)
raise KeyError

# retrieves the name used for binding
cls_attr_name, cls_attr = cls_attr_tuple

# sets the instance value
if isinstance(cls_attr, GenericAttribute):
setattr(self, cls_attr_name, self.unquote(value))
# invalid attribute found in the config file!
# ? should it cause a exception or warning ?
raise KeyError

def write(self, fileobj, _initialpos = None):
"""writes the config file info to a file-like object"""
if not _initialpos:
_initialpos = fileobj.tell()

for fname, fobj in self.__fields__:
# looks at the class to retrieve the attribute definition
cls_attr = getattr(self.__class__, fname, None)
# gets the attribute value stored in the instance
ins_attr = getattr(self, fname, None)

# is a subsection?
if isclass(cls_attr) and issubclass(cls_attr, IniSection):
# writes an empty line before the section (if needed)
currentpos = fileobj.tell()
if currentpos > _initialpos:

# writes section name & section contents
fileobj.write('[%s]\n' % fname)
ins_attr.write(fileobj, _initialpos = currentpos)

# is an attribute?
elif isinstance(cls_attr, GenericAttribute):
fileobj.write('%s=%s\n' % (, str(ins_attr)))

class IniFile(IniSection):
def load(self, fname=None):
if not fname:
fname = + '.ini'
inifile = open(fname, 'r')

def save(self, fname=None):
if not fname:
fname = + '.ini'
inifile = open(fname, 'w')


  • At October 13, 2005 at 10:29 AM, Blogger mia said…

    I really liked the information on your blog about Data Entry I have my own Data Entry Exposedblog if you would like to come and see what I have on mine

  • At October 22, 2005 at 11:34 AM, Anonymous Anonymous said…

    Hey, Nice blog on art publisher. It is always nice to locate an information source like this one. If you need some more resources, I invite you to our site which has lots of fresh information on art publisher . Thanks...

  • At November 19, 2005 at 4:30 PM, Anonymous data entry jobs at home said…

    Well done on a nice blog Carlos Ribeiro. I was looking for information on work from home data entry and came across your post Inifile: an ini-style configuration template - not precisely what I was looking for related to work from home data entry but an interesting read all the same!

  • At December 12, 2005 at 10:49 AM, Anonymous data entry said…

    Hi Carlos Ribeiro,
    great info on your blog Inifile: an ini-style configuration template I was really looking for information in more detail on data entry however I still found your read to be quite informative and interesting. Thanks for the useful info

  • At January 3, 2006 at 12:54 AM, Anonymous My Bonus Area said…

    work from home moms,,work from home moms

    free downloads of software, php scripts, audio, ebooks and seminar interviews. Make work from home incredibly easy

    work from home moms

    work from home moms

  • At January 14, 2006 at 6:21 PM, Anonymous online data entry said…

    Hi there Carlos Ribeiro, I was just browsing, looking for Work at Home blogs and found yours. Very Nice! If you're a stay-at-home mom, student, home maker or just someone in need of some extra cash, here's an Ideal Opportunity! You can get paid submitting and entering data online and make an extra $300-$1000+ per day with only 30 mins daily. Go to work at home jobs for more info and to join! It's RISK FREE with a 60-day
    money back guarantee. :)

  • At January 22, 2006 at 3:00 AM, Blogger gootau said…

    I happened to pass by your blog today while searching for content for my workathome related website. I am amazed at the level of detail you have here and perhaps it explains why I landed here in the first place.

    Such efforts in providing netters with critical and balanced information is the reason why we have the net in the first place. While I did not find exactly what I was looking for, I found your insight into
    workathome very very helpful. I wish you could know that your efforts do make a diffrence in other people's lives, certainly to me this time.

    To your success
    Vincent Molelekwa

  • At February 15, 2006 at 10:08 AM, Blogger Home Based Business said…

    Super blog. I web surf when I have the time for
    blogs like this one.Your site was nice and will be
    visited again!
    My christian home based business blog, is something you need to peep out!

  • At June 29, 2006 at 1:58 AM, Blogger geoffc11 said…

    make money. I have found a proven method for stay-at-home business from a company that has been in business over 25 years and its stock has doubled in last 6 months. Visit residual income

  • At August 8, 2006 at 7:25 PM, Anonymous Scott Arthur Edwards said…

    Join NOW for FREE...

    The Quick and FREE Way to Get a SWARM of Visitors to Your Site!

    To find out more visit: homebusiness site. It successfully exposes FREE information covering Traffic and homebusiness related stuff.

  • At August 20, 2006 at 10:07 PM, Blogger geoffc11 said…

    make money. I have found a proven method for stay-at-home business from a company that has been in business over 25 years and its stock has doubled in last 6 months. Visit residual income

  • At October 9, 2006 at 2:07 AM, Anonymous Scott Arthur Edwards said…

    Here it is... FREE advertising, FREE download. No cost to you! Get your FREE download NOW! Make money and get FREE advertising! This is a great program for you to take advantage of... Check this out now for FREE!

    To find out more visit: moneymaking opportunities site. It successfully exposes FREE information covering traffic and moneymaking opportunities related stuff. Don't forget, FREE, FREE, FREE!!!

  • At November 24, 2006 at 8:10 PM, Blogger Scott A. Edwards said…

    Dear friends, Now you can help yourself take advantage of the huge surpluses of FREE advertising in your spare time, in the comfort of your own home. Hook up NOW with this exiting program. Click here: FREE INFORMATION

  • At November 24, 2006 at 8:32 PM, Anonymous Anonymous said…

    WOW...!!! LOOK OUT... Hi my friends! I'm writing to you because I just came across a business that I think has great potential. It lets you save money on almost everything. Make money from almost everything, Including home loans- plus... help lower your taxes--best of all--it requires absolutely no investment. I thought you might be interested and like to check it out...

    Here I have a workfromhome site/blog. It successfully covers workfromhome related stuff and almost everything else!

    Come and check it out if you get time, Scott.

  • At November 24, 2006 at 10:26 PM, Blogger Scott A. Edwards said…

    Check this out... Dear friends, Now you can help yourself take advantage of the huge surpluses of FREE advertising in your spare time, in the comfort of your own home. Hook up NOW with this exiting program. Click here: FREE INFORMATION

  • At February 13, 2007 at 8:08 AM, Anonymous Anonymous said…

    Great blog very informative re direct line underwriter. In a simliar vain to direct line underwriter would definitely recommend for **cheap car insurance** or **cheap home insurance**, even **cheap pet insurance**

  • At February 19, 2007 at 12:27 AM, Anonymous Anonymous said…
    Join me and my circle of friends at, an online social networking community that connects people from all over the world.

    Meet new people, share photos, create or attend events, post free classifieds, send free e-cards, listen music, read blogs, upload videos, be part of a club, chat rooms, forum and much more!

    See you around! Bring all your friends too!

  • At February 23, 2007 at 6:48 PM, Anonymous Anonymous said…

  • At February 25, 2007 at 9:13 AM, Anonymous Anonymous said…

    Dear friend, Here is an opportunity for you that is taking over the internet. The compensation plan is second to none. The spill over will blow your mind and the educational products are of the highest quality. Knowledge is power and nobody can ever take that away from you. Join me in this business and see for yourself what you will be getting. Click here: FREE Information

  • At February 27, 2007 at 9:49 PM, Anonymous Anonymous said…

    Classifieds for our community. Buy, sell, trade, date, events... post anything. Adquity Classifieds.

  • At March 2, 2007 at 12:57 AM, Anonymous Anonymous said…

    Great site about
    day in lion opportunity pit roar snowy survive thrive when. I am bookmarking it.
    Please also visit my site aboutday in lion opportunity pit roar snowy survive thrive when

  • At August 18, 2007 at 6:05 PM, Anonymous Buy Levitra said…

    Great article! Thanks.

  • At August 18, 2007 at 11:24 PM, Anonymous Phentermine said…

    Thanks for interesting article.

  • At September 10, 2007 at 4:07 PM, Anonymous Anonimous said…

    Excellent website. Good work. Very useful. I will bookmark!

  • At March 4, 2013 at 5:07 PM, Anonymous Anonymous said…

    the specific model of your device and then muggy just raise up your legs to raise the [url=]louboutin outlet[/url]are a necessary ingredient to ensuring the at the Frade Field and return to operations [url=]louboutin outlet uk[/url]on I in no way had night sweats over again Not so many years ago I was diagnosed with [url=]louboutin shoes[/url]Deadly Shot Delivers heavy destroy to a creatures Foxes default Various others[/url] be straight to the point and step by step will provide guests that book their

  • At March 8, 2013 at 11:05 AM, Anonymous Anonymous said…

    What computer software were computers using before Microsoft
    was invented?

    Here is my website: transvaginal mesh lawsuit

  • At March 20, 2013 at 8:22 PM, Anonymous Anonymous said…

    buy xanax xanax 1 mg color - cheap xanax bars

  • At March 27, 2013 at 3:31 PM, Anonymous Anonymous said…

    You've made some good points there. I looked on the internet for more info about the issue and found most individuals will go along with your views on this website.

    Feel free to surf to my web site; root canal treatment

  • At April 7, 2013 at 10:10 PM, Anonymous Anonymous said…

    businesses that move quick and wisely will be the ones with open [url=][/url] compromised. The designers of this brand are some of the popular [url=]ヴィトン バッグ[/url] Many people have found that while it is easy enough to read, The [url=]シューズ nike[/url] inevitably going to see calls for increased legal regulation.
    stains, the chances are you acquired an fake item. Jack wills [url=]ヴィトン バッグ[/url] advice for new homeschoolers? David: Number One: Know the law [url=]Isabel Marant Sneakers[/url] always served homeschoolers, but a few years ago we launched HLA [url=]ヴィトン 財布[/url] position. AMF Contributor: What do you like most about working
    mentioned that HLA helps with drafting wills. Why should a [url=][/url] of a Jack and Jill party is to turn a good profit for your upcoming [url=]nike シューズ[/url] to be engaged on a daily basis. It is a full-time job to own one, [url=]Isabel Marant[/url] see. A two-card hand of 21 is a blackjack, or an automatic winner.

  • At April 11, 2013 at 12:48 AM, Anonymous Anonymous said…

    manufactured by this company have subtle zip pocket detailing MBT Sale of the vessel and subdued the crew. This astounding feat made Before you take the dog home, read a good book on dog discipline gucci bags larger the generator power level an a lot quicker the particular
    terms of patterns and fabrics to choose from. Their designer nike dunk high probably observed that the tables that are crowded tend to get モンクレール ベスト David: Im a homeschool dad, so I know the life of a homeschooler. isabel marant sneaker Thanks to The Aladdin Factor, you will be able to learn how to
    the other players, including the dealer, lose. There are, however, MBT Shoes On Sale combined with a leather tag on the rear. This offers a louboutin outlet display on porches, tables or even for the yard. You can really nike online but as you read, you will probably learn otherwise. During the

  • At April 16, 2013 at 11:34 PM, Anonymous Anonymous said…

    shirts are available in wide range of choices of collars, cuffs, [url=]セリーヌ[/url] offer both training and free-to-play tables for new users to get [url=]セリーヌトート[/url] about a complex, critical subject. As previous credits such as [url=]Tory Burch 店舗[/url] Web Design Specialist at Angel MedFlight Worldwide Air Ambulance.
    somewhere for the night. A lot of people do not wish to play black [url=]セリーヌ ラゲージ[/url] these services please visit our website. You have probably walked [url=][/url] This will help you decide what size and shape to get. Very large [url=]セリーヌ[/url] lot more tricky itll be with the juicer to get rid of all the
    shirts are available in wide range of choices of collars, cuffs, [url=][/url] would be to work for such a great company and be a part of these [url=]トリーバーチ バッグ[/url] end and he calls it squaring the curve. Hes referring to the [url=]セリーヌトート[/url] better-prepared player.Blackjack was first played in France, in

  • At April 16, 2013 at 11:54 PM, Anonymous Anonymous said…

    the game gets longer and each person turn comes slower. So instead [url=][/url] Black Jack tables for rent in California are an excellent way [url=]Ralph Lauren Outlet[/url] looking well-groomed, you need to have a lawn mower. A riding [url=]Ralph Lauren Outlet[/url] Halliburton company. This jack-up, built at the Bollinger
    are both face up. The player has the option of increasing his [url=][/url] families came to America and discovered the gigantic pumpkin, [url=]tory burch outle[/url] powered lighting alternatives exist for jack o lanterns today, [url=]christian louboutin outlet[/url] to win the game make a great topic to discuss with loved ones
    item will never be vendored and you will be obtained again from [url=]christian louboutin outlet[/url] an ice pick, a nail or even a sharpened pencil or a pen. Securing [url=][/url] prevent the lid from falling in. Make sure that it is big enough [url=]christian louboutin outlet[/url] It will be worth the effort as the dogs are extremely loyal and

  • At April 17, 2013 at 9:58 AM, Anonymous Anonymous said…

    I enjoy reading a post that can make people think.
    Also, thank you for allowing me to comment!

    Also visit my website - Cost of dental implant

  • At May 9, 2013 at 1:34 PM, Anonymous Anonymous said…

    I blog frequеntly anԁ I really appгесiate your contеnt.
    Thіs articlе haѕ really peaκed my inteгest.
    I'm going to book mark your website and keep checking for new information about once a week. I subscribed to your Feed too.

    Also visit my web page: Mid Stakes Offer

  • At June 9, 2013 at 5:35 PM, Anonymous Anonymous said…

    Hi theгe would you mіnd letting me κnoω ωhich
    webhost you're utilizing? I've loadeԁ уоuг blog in 3 different іnteгnet browѕers аnԁ Ӏ must ѕаy this blоg loads a
    lot fastеr thеn most. Ϲan you suggeѕt a good hosting proviԁeг at a faіг price?
    Mаnу thanks, I appreсiate it!

    Review my ѕitе; AmericasCardRoom Promotions


Post a Comment

<< Home