1
1
# -*- coding: utf-8 -*-
2
2
3
+ import argparse
4
+ import os
3
5
from ast import literal_eval
4
6
from configparser import ConfigParser
5
7
8
+ import supar
9
+ from supar .utils .fn import download
10
+
6
11
7
12
class Config (object ):
8
13
9
- def __init__ (self , conf = None , ** kwargs ):
14
+ def __init__ (self , ** kwargs ):
10
15
super (Config , self ).__init__ ()
11
16
12
- config = ConfigParser ()
13
- config .read (conf or [])
14
- self .update ({** dict ((name , literal_eval (value ))
15
- for section in config .sections ()
16
- for name , value in config .items (section )),
17
- ** kwargs })
17
+ self .update (kwargs )
18
18
19
19
def __repr__ (self ):
20
20
s = line = "-" * 20 + "-+-" + "-" * 30 + "\n "
@@ -28,6 +28,9 @@ def __repr__(self):
28
28
def __getitem__ (self , key ):
29
29
return getattr (self , key )
30
30
31
+ def __contains__ (self , key ):
32
+ return hasattr (self , key )
33
+
31
34
def __getstate__ (self ):
32
35
return vars (self )
33
36
@@ -46,8 +49,25 @@ def update(self, kwargs):
46
49
kwargs .update (kwargs .pop ('kwargs' , dict ()))
47
50
for name , value in kwargs .items ():
48
51
setattr (self , name , value )
49
-
50
52
return self
51
53
54
+ def get (self , key , default = None ):
55
+ return getattr (self , key ) if hasattr (self , key ) else default
56
+
52
57
def pop (self , key , val = None ):
53
58
return self .__dict__ .pop (key , val )
59
+
60
+ @classmethod
61
+ def load (cls , conf = '' , unknown = None , ** kwargs ):
62
+ config = ConfigParser ()
63
+ config .read (conf if not conf or os .path .exists (conf ) else download (supar .CONFIG .get (conf , conf )))
64
+ config = dict ((name , literal_eval (value ))
65
+ for section in config .sections ()
66
+ for name , value in config .items (section ))
67
+ if unknown is not None :
68
+ parser = argparse .ArgumentParser ()
69
+ for name , value in config .items ():
70
+ parser .add_argument ('--' + name .replace ('_' , '-' ), type = type (value ), default = value )
71
+ config .update (vars (parser .parse_args (unknown )))
72
+ config .update (kwargs )
73
+ return cls (** config )
0 commit comments