Skip to content

Instantly share code, notes, and snippets.

@rpapallas
Last active March 18, 2018 19:48
Show Gist options
  • Save rpapallas/619da4bbe97609a5362818c721d8f732 to your computer and use it in GitHub Desktop.
Save rpapallas/619da4bbe97609a5362818c721d8f732 to your computer and use it in GitHub Desktop.
This will force the definition of a class attribute and will throw an error if not defined in Python.
"""
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
class ForceRequiredAttributeDefinitionMeta(type):
def __call__(cls, *args, **kwargs):
class_object = type.__call__(cls, *args, **kwargs)
class_object.check_required_attributes()
return class_object
# Python 2
class ForceRequiredAttributeDefinition(object):
__metaclass__ = ForceRequiredAttributeDefinitionMeta
starting_day_of_week = None
def check_required_attributes(self):
if self.starting_day_of_week is None:
raise NotImplementedError('Subclass must define self.starting_day_of_week attribute. \n This attribute should define the first day of the week.')
# Python 3
class ForceRequiredAttributeDefinition(metaclass=ForceRequiredAttributeDefinitionMeta):
starting_day_of_week = None
def check_required_attributes(self):
if self.starting_day_of_week is None:
raise NotImplementedError('Subclass must define self.starting_day_of_week attribute. \n This attribute should define the first day of the week.')
class ConcereteValidExample(ForceRequiredAttributeDefinition):
def __init__(self):
self.starting_day_of_week = "Monday"
class ConcereteInvalidExample(ForceRequiredAttributeDefinition):
def __init__(self):
# This will throw an error because self.starting_day_of_week is not defined.
pass
ConcereteValidExample() # Working example
ConcereteInvalidExample() # This will throw an NotImplementedError straightaway
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment