Skip to content

Instantly share code, notes, and snippets.

@Larivact
Last active July 21, 2016 06:28
Show Gist options
  • Save Larivact/52f539d1e7edde21b0e8239e5afaf240 to your computer and use it in GitHub Desktop.
Save Larivact/52f539d1e7edde21b0e8239e5afaf240 to your computer and use it in GitHub Desktop.
A cool experimental version of configparser. The CFG file syntax has to be: none, true, false, 'string', 1234
class ConfigDict():
comment_delimiters = ('#', ';')
def __init__(self, path):
self.path = path
self.lines = None
self.data = None
def read(self):
with open(self.path) as f:
lines = f.readlines()
self.lines = lines
self.data = {}
for line in lines:
line = line.strip()
if line != '' and line[0] not in self.comment_delimiters:
if '=' in line:
args = line.split('=')
name = args[0].strip()
value = args[1].strip()
if value == 'true':
value = True
elif value == 'false':
value = False
elif value == 'none':
value = None
elif value[0] == "'" and value[-1] == "'":
value = value[1:-1]
else:
value = int(value)
self.data[name] = value
def write(self):
for idx, line in enumerate(self.lines):
line = line.strip()
if line != '' and line[0] not in self.comment_delimiters:
if '=' in line:
args = line.split('=')
name = args[0].strip()
value = args[1].strip()
if name in self.data:
value = self.data[name]
if value is None:
value = 'none'
elif value is True:
value = 'true'
elif value is False:
value = 'false'
elif isinstance(value, str):
value = "'%s'" % value
elif isinstance(value, int):
value = str(value)
else:
raise ValueError('unkown type')
self.lines[idx] = name+' = '+ value+'\n'
with open(self.path, 'w') as file:
file.writelines( self.lines )
def __getitem__(self, var):
if self.data is None:
self.read()
return self.data[var]
def __getattr__(self,var):
if self.data is None:
self.read()
return self.data[var]
def __setitem__(self,name,value):
self.data[name] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment