Skip to content

Commit

Permalink
Leverage __set_name_ from Py3.6
Browse files Browse the repository at this point in the history
  • Loading branch information
funkybob committed Nov 19, 2018
1 parent fb88ace commit 4d9fc91
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
19 changes: 14 additions & 5 deletions cbs/__init__.py
Expand Up @@ -39,19 +39,24 @@ def SETTING(self):
def SETTING(self):
'''
def __new__(cls, *args, **kwargs):
if 'type' in kwargs and 'cast' not in kwargs:
kwargs['cast'] = kwargs.pop('type')
if not args:
return partial(cls, **kwargs)
return object.__new__(cls)

def __init__(self, getter, key=None, cast=None, prefix=None):
self.getter = getter
self.cast = cast
self.key = key or getter.__name__
if key is None and getter is not None:
key = getter.__name__
if prefix is None:
prefix = DEFAULT_ENV_PREFIX
self.var_name = ''.join([prefix, self.key])
self.prefix = prefix
self._set_name(key)

def _set_name(self, name):
self.key = name
if name:
self.var_name = ''.join([self.prefix, name])

def __get__(self, obj, klass=None):
if obj is None:
Expand All @@ -61,7 +66,7 @@ def __get__(self, obj, klass=None):
except KeyError:
if self.getter is None:
raise RuntimeError(
'You must set the %s environment variable.' % self.var_name
f'You must set the {self.var_name} environment variable.'
)
value = self.getter(obj)
else:
Expand All @@ -70,6 +75,10 @@ def __get__(self, obj, klass=None):
obj.__dict__[self.key] = value
return value

def __set_name__(self, owner, name):
if self.key is None:
self._set_name(name)


class envbool(env):
'''
Expand Down
7 changes: 7 additions & 0 deletions tests/test_env.py
Expand Up @@ -194,3 +194,10 @@ class Settings:

self.assertEqual(Settings().SETTING, True)

def test_set_name(self):

class Settings:

SETTING = cbs.env(None)

self.assertEqual(Settings.SETTING.key, 'SETTING')

0 comments on commit 4d9fc91

Please sign in to comment.