Skip to content

Commit

Permalink
v3.0.0
Browse files Browse the repository at this point in the history
`context` argument(feature) has been removed permanently.
  • Loading branch information
pylover committed Nov 27, 2021
1 parent 4d5ef4a commit 100dad3
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 61 deletions.
2 changes: 1 addition & 1 deletion pymlconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
ConfigurationNotInitializedError


__version__ = '2.6.1'
__version__ = '3.0.0'
30 changes: 11 additions & 19 deletions pymlconf/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,9 @@ class Mergable(metaclass=abc.ABCMeta):
:param data: Initial value to constract a mergable instance. It can be
``yaml string`` or python dictionary. default: None.
:type data: list or dict
:param context: dictionary to format the yaml before parsing in
pre-processor.
:type context: dict
"""

def __init__(self, data=None, context=None):
self.context = context if context else {}
def __init__(self, data=None):
if data:
self.merge(data)

Expand Down Expand Up @@ -64,19 +58,18 @@ def copy(self): # pragma: no cover
raise NotImplementedError()

@classmethod
def make_mergable_if_possible(cls, data, context):
def make_mergable_if_possible(cls, data):
"""Make an object mergable if possible.
Returns the virgin object if cannot convert it to a mergable instance.
:returns: :class:`.Mergable` or type(data)
"""
if isinstance(data, dict):
return MergableDict(data=data, context=context)
return MergableDict(data=data)
elif isiterable(data):
return MergableList(
data=[cls.make_mergable_if_possible(i, context) for i in data],
context=context
data=[cls.make_mergable_if_possible(i) for i in data],
)
else:
return data
Expand All @@ -90,7 +83,7 @@ def merge(self, *args):
"""
for data in args:
if isinstance(data, str):
tomerge = yamlhelper.loads(data, self.context)
tomerge = yamlhelper.loads(data)
if not tomerge:
continue
else:
Expand Down Expand Up @@ -128,8 +121,7 @@ def _merge(self, data):
self[k] = v.copy()
else:
self[k] = Mergable.make_mergable_if_possible(
copy.deepcopy(v),
self.context
copy.deepcopy(v)
)

def __getattr__(self, key):
Expand Down Expand Up @@ -163,7 +155,7 @@ def __delattr__(self, key):
super().__delattr__(key)

def copy(self):
return MergableDict(self, context=self.context)
return MergableDict(self)

def dump(self):
return {
Expand Down Expand Up @@ -191,7 +183,7 @@ def _merge(self, data):
self.extend(data)

def copy(self):
return MergableList(self, context=self.context)
return MergableList(self)

def dump(self):
return [
Expand Down Expand Up @@ -227,7 +219,7 @@ def loadfile(self, filename):
if not path.exists(filename):
raise FileNotFoundError(filename)

loadedyaml = yamlhelper.load(filename, self.context)
loadedyaml = yamlhelper.load(filename)
if loadedyaml:
self.merge(loadedyaml)

Expand Down Expand Up @@ -266,7 +258,7 @@ def _getinstance(cls):
)
return cls._instance

def initialize(self, init_value, context=None, force=False):
def initialize(self, init_value, force=False):
"""Initialize the configuration manager.
:param force: force initialization even if it's already initialized
Expand All @@ -277,4 +269,4 @@ def initialize(self, init_value, context=None, force=False):
'Configuration manager object is already initialized.'
)

self.__class__._instance = Root(init_value, context=context)
self.__class__._instance = Root(init_value)
29 changes: 13 additions & 16 deletions pymlconf/yamlhelper.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,29 @@
from os import path
import sys

import yaml
from yaml import YAMLError

try:
from yaml import CLoader as Loader
except ImportError: # pragma: no cover
from yaml import Loader


def preprocess(data, context):
if callable(context):
context = context()
return data % context
def loads(string):
try:
return yaml.load(string, Loader)

except YAMLError as ex:
print('YAML parsing error', file=sys.stderr)
print('Input string start', file=sys.stderr)
print(string, file=sys.stderr)
print('Input string end', file=sys.stderr)
raise ex

def loads(str_data, context=None):
if context:
str_data = preprocess(str_data, context)
return yaml.load(str_data, Loader)


def load(filename, context=None):
directory = path.abspath(path.dirname(filename))
context = context or {}
context.update(here=directory)

def load(filename):
with open(filename) as f:
return loads(f.read(), context)
return loads(f.read())


def dumps(o):
Expand Down
9 changes: 3 additions & 6 deletions tests/test_diferred_root.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@
class TestDiferredRoot:

def test_deferred_config_manager(self):
context = dict(
c=3
)
config = '''
a: 1
b:
Expand All @@ -21,18 +18,18 @@ def test_deferred_config_manager(self):
with pytest.raises(ConfigurationNotInitializedError):
root.attr

root.initialize(config, context)
root.initialize(config)

with pytest.raises(ConfigurationAlreadyInitializedError):
root.initialize(config)

root.merge('''
c: %(c)s
foo: bar
''')

assert root.a == 1
assert root.b == [1]
assert root.c == 3
assert root.foo == 'bar'

root.d = [1, 2]
assert [1, 2] == root.d
23 changes: 4 additions & 19 deletions tests/test_root.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,17 @@

class TestConfigManager:
def test_constructor(self):
context = dict(
c=3
)

builtin = '''
a:
a1: 1
b:
- 1
- 2
- %(c)s
- 3
'''

root = Root(builtin, context)
root = Root(builtin)
assert root.a.a1 == 1
assert root.b[0] == 1
assert root.b[1] == 2
Expand Down Expand Up @@ -62,27 +58,16 @@ def test_loadfile(self):
with pytest.raises(FileNotFoundError):
root.loadfile('not/exists')

def test_callable_context(self):
def context():
return dict(c=3)

root = Root('a: %(c)s', context)
assert root.a == 3

def test_dump(self):
context = dict(
c=3
)

builtin = '''
a:
a1: 1
b:
- 1
- 2
- %(c)s
- 3
'''

root = Root(builtin, context)
root = Root(builtin)
dump = root.dumps()
assert dump == 'a:\n a1: 1\nb:\n- 1\n- 2\n- 3\n'
7 changes: 7 additions & 0 deletions tests/test_yaml_syntax.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import pytest
from yaml.scanner import ScannerError

from pymlconf import Root


Expand Down Expand Up @@ -45,3 +48,7 @@ def test_simple_syntax(self):
assert cm.app.languages[1].country == 'iran'
assert cm.logging.formatter == str
assert isinstance(cm.logging.writer, MyWriter)


with pytest.raises(ScannerError):
Root('q: s:')

0 comments on commit 100dad3

Please sign in to comment.