class Wall(object): height: int = field(doc="Height of the wall in mm.", native=native) color: str = field(default='white', doc="Color of the wall.", native=native) __init__ = make_init(height, color)
class Wall(object): height: int = field(validators={'should be a positive number': x > 0, 'should be a multiple of 100': x % 100 == 0}, doc="Height of the wall in mm.") color: str = field(validators=is_in(colors), default='white', doc="Color of the wall.")
class C(object): y = field() x = field(default_factory=copy_field(y)) @init_fields def __init__(self): pass
class RisingPlaylist: client_id: str = field(check_type=True, doc="The client id") client_secret: str = field(check_type=True, doc="The client secret") date: str = field(check_type=True, doc="The date to search") user_agent: str = field(check_type=True, default="rising-playlist-creator by /u/mfaine", doc="The user agent") def get_playlist_id(self): reddit = praw.Reddit(client_id=self.client_id, client_secret=self.client_secret, user_agent=self.user_agent) # Get the rising subreddit subreddit = reddit.subreddit("rising") # look for the submission with the provided date by rising_mod # A lot of checks here, probably don't need them all for submission in subreddit.new(limit=10): logger.debug(f"Title: {submission.title}") if submission.title == f"Rising: {self.date}": logger.debug(f"Author: {submission.author.name}") logger.debug(f"Is Mod: {submission.author.is_mod}") if submission.author.is_mod and submission.author.name == 'rising_mod': logger.debug(f"Flair: {submission.link_flair_text}") if submission.link_flair_text == "Weekday Playlist": logger.debug(f"URL: {submission.url}") return submission.url.split('=')[1]
class Wall(object): height = field(doc="Height of the wall in mm.", native=native) # type: int color = field(default='white', doc="Color of the wall.", native=native) # type: str __init__ = make_init()
class Foo(object): a = field(type_hint=Optional[int], check_type=True) b = field(type_hint=Optional[int], validators={'is positive': lambda x: x > 0}) c = field(nonable=False, check_type=True) d = field(validators={'accept_all': lambda x: True}) e = field(nonable=False)
class C(B, A): a = field(default=None) c = field(default_factory=copy_field('b')) @init_fields(ancestor_fields_first=a_first) def __init__(self): pass
class Wall(object): height = field(doc="Height of the wall in mm.") # type: int color = field(default='white', doc="Color of the wall.") # type: str @inject_fields def __init__(self, fields): fields.init(self)
class C(object): x = field(default=None, doc="the optional 'x' property") y = field(doc="the mandatory 'y' property") z = field(doc="the mandatory 'z' property") @init_fields def __init__(self): pass
class Wall(object): height: int = field(doc="Height of the wall in mm.", native=native) color: str = field(default='white', doc="Color of the wall.", native=native) def post_init(self, foo: str = 'bar'): print(self.height) print("post init man !") __init__ = make_init(height, color, post_init_fun=post_init)
class Wall(object): height = field(type_hint=int, check_type=True, doc="Height of the wall in mm.") color = field(type_hint=str, check_type=True, default='white', doc="Color of the wall.")
class Wall(object): height = field(doc="Height of the wall in mm.") # type: int color = field(default='white', doc="Color of the wall.") # type: str def post_init(self, foo='bar'): print(self.height) print("post init man !") __init__ = make_init(height, post_init_fun=post_init)
class Account(object): first = field(doc="first name") last = field(doc="last name") age = field(doc="the age in years") id = field(doc="an identifier") balance = field(doc="current balance in euros") @init_fields def __init__(self, msg): print(msg)
class Foo(object): a = field(default_factory=copy_value([])) b = field(default_factory=copy_field('z')) c = field() @c.default_factory def c_default(self): return self.a + ['yes'] z = field()
class Wall: height: int = field(doc="Height of the wall in mm.", native=native) color: str = field(default='white', doc="Color of the wall.", native=native) @inject_fields def __init__(self, fields): with pytest.raises(MandatoryFieldInitError): print(self.height) # initialize all fields received fields.init(self)
class Operate(object): att = field() # Required type_ = field(type_hint=str, check_type=True, validators=is_in(valid_types)) # Required value = field(default_factory=copy_value([])) # Optional mode = field(default=None) # Optional action = field(default=None) # Optional @init_fields def __init__(self): pass
class Position(object): x = field(type_hint=int, check_type=True, validators=lambda x: x > 0) y = field(type_hint=int, check_type=True, validators={ 'y should be between 0 and 100': lambda y: y > 0 and y < 100 }) @init_fields def __init__(self, msg="hello world!"): print(msg)
class House(object): name = field(check_type=True, type_hint=str, doc="the name of your house") nb_floors = field(default=100, check_type=True, type_hint=int, doc="the nb floors", validators={ "should be positive": lambda x: x >= 0, "should be a multiple of 100": lambda x: x % 100 == 0 })
class Wall: height = field(doc="Height of the wall in mm.") # type: int color = field(default='white', doc="Color of the wall.") # type: str @init_fields def __init__(self, msg='hello'): """ After initialization, some print message is done :param msg: the message details to add :return: """ print("post init ! height=%s, color=%s, msg=%s" % (self.height, self.color, msg)) self.non_field_attr = msg
class Car(object): """ My class with many fields """ color = field(type_hint=str, check_type=True, validators=is_in(ALLOWED_COLORS)) name = field(type_hint=str, check_type=True, validators={'should be non-empty': lambda s: len(s) > 0}) wheels = field(type_hint=int, check_type=True, validators={'should be positive': lambda x: x > 0}) @init_fields def __init__(self, msg="hello world!"): print(msg)
class Wall: height = field(doc="Height of the wall in mm.") # type: int color = field(default='white', doc="Color of the wall.") # type: str def post_init(self, msg='hello'): """ After initialization, some print message is done :param msg: the message details to add :return: """ print("post init ! height=%s, color=%s, msg=%s" % (self.height, self.color, msg)) self.non_field_attr = msg # only `height` and `foo` will be in the constructor __init__ = make_init(height, post_init_fun=post_init)
class GoogleService: client_secret_file: str = field(check_type=True, doc="The secrets file") scopes: list = field(check_type=True, doc="The API version") api_name: str = field(check_type=True, default="youtube", doc="The API name") api_version: str = field(check_type=True, default="3", doc="The API version") def authenticate(self) : cred = None logger.debug(f"Secret File: {self.client_secret_file}") logger.debug(f"API Name: {self.api_name}") logger.debug(f"API Version: {self.api_version}") logger.debug(f"Scopes: {','.join(self.scopes)}") # Disable OAuthlib's HTTPS verification when running locally. # *DO NOT* leave this option enabled in production. #os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" pickle_file = f'token_{self.api_name}_{self.api_version}.pickle' logger.debug(f"Pickle File: {pickle_file}") if os.path.exists(pickle_file): with open(pickle_file, 'rb') as token: cred = pickle.load(token) if not cred or not cred.valid: if cred and cred.expired and cred.refresh_token: cred.refresh(Request()) else: # Get credentials and create an API client flow = InstalledAppFlow.from_client_secrets_file(self.client_secret_file, self.scopes) cred = flow.run_local_server() with open(pickle_file, 'wb') as token: pickle.dump(cred, token) try: service = googleapiclient.discovery.build(self.api_name, self.api_version, credentials=cred) logger.debug(f"{self.api_name} service created successfully") return service except ImportError: pass except ModuleNotFoundError: pass except Exception as e: print(e) logger.debug(f'Failed to create service instance for {self.api_name}') os.remove(pickle_file) return None
class Hashtag: v = Validate().generate hashtag: str = field(default=DEFAULT_HASHTAG, validators=v(is_blank=True, max_len=150), check_type=True) start: int = field(default=-1, check_type=True) end: int = field(default=-1, check_type=True) created_at: datetime = field(default=DEFAULT_CREATED_AT, check_type=True) def to_vec(self) -> dict: return { "hashtag": self.hashtag, "start": self.start, "end": self.end, "created_at": self.created_at, }
class B(A): b = field(default='world') def a(self): """ purposedly override the base class field name """ pass __init__ = make_init()
class TweeterMixin: afraid = field(default=False, name='afraid', doc="""Status of the tweeter. When this is `True`, tweets will be lighter""") def tweet(self): how = "lightly" if self.afraid else "loudly" print("tweeting %s" % how)
class Foo2(object): # one single validator f = field(default="hey", type_hint=str, validators=non_empty) # one single validator in a list g = field(type_hint=str, validators=[non_empty]) # one single validator accepting three arguments (obj, field, val) gg = field(type_hint=str, validators=lambda obj, field, val: obj.f in val) # several validators in a dict. keys and values can contain elements of definition in any order h = field(type_hint=str, validators=OrderedDict([ ("h should be non empty", (non_empty, EmptyFailure)), ("h should contain field f", (lambda obj, val: obj.f in val)), ("h should contain 'a'", (lambda val: 'a' in val)) ]))
class Foo(object): f = field(native=native) @f.validator def f_should_be_a_multiple_of_3(self, f_val): return f_val % 3 == 0 @f.validator(help_msg="not a large enough value") def f_should_be_larger_than_g(self, f_val): return f_val > self.g
class EntityUrl: v = Validate().generate url: str = field(default=DEFAULT_ENTITY_URL, validators=v(is_blank=True, max_len=150), check_type=True) start: int = field(default=-1, check_type=True) end: int = field(default=-1, check_type=True) expanded_url: str = field(default="", validators=v(max_len=2083), check_type=True) created_at: datetime = field(default=DEFAULT_CREATED_AT, check_type=True) def to_vec(self) -> dict: return { "url": self.url, "start": self.start, "end": self.end, "expanded_url": self.expanded_url, "created_at": self.created_at, }
class Well(object): name = field() # Required group = field() # Required operate_list = field(default_factory=copy_value([])) # Optional monitor_list = field(default_factory=copy_value([])) # Optional geometry = field(default=None) # Optional perf = field(default=None) # Optional
class UserRelation: v = Validate().generate user_id: str = field(default=DEFAULT_USER_ID, validators=v(is_blank=True, max_len=30), check_type=True) username: str = field(default=DEFAULT_USERNAME, validators=v(is_blank=True), check_type=True) target_id: str = field(default=DEFAULT_USER_ID, validators=v(is_blank=True, max_len=30), check_type=True) target_name: str = field(default=DEFAULT_USERNAME, validators=v(is_blank=True), check_type=True) relation_id: int = field(default=-1, check_type=True) updated_at: datetime = field(default=datetime.now(), check_type=True) def to_vec(self) -> dict: return { "user_id": self.user_id, "username": self.username, "target_id": self.target_id, "target_name": self.target_name, "relation_id": self.relation_id, "updated_at": self.updated_at, }