Skip to content

Instantly share code, notes, and snippets.

@svagionitis
Created November 25, 2015 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svagionitis/4703ea8c50b5eea13683 to your computer and use it in GitHub Desktop.
Save svagionitis/4703ea8c50b5eea13683 to your computer and use it in GitHub Desktop.
Read a python class and extract the attributes from the constructor
#!/bin/sh -ex
# Read an python class file and extraact the attributes
# from the constructor. Then assign them and creates setters
PYTHON_CLASS_FILE=${1}
get_constructor_definition=$(sed -n '/__init__(self,/,/):/p' ${PYTHON_CLASS_FILE} | tr -s ' ')
get_mandatory_attributes=$(echo ${get_constructor_definition} | sed 's/def\|__init__\|self//g' | sed 's/, /\n/g' | tr -d ' (,):' | grep -v '=None')
get_optional_attributes=$(echo ${get_constructor_definition} | sed 's/def\|__init__\|self//g' | sed 's/, /\n/g' | tr -d ' (,):' | grep '=None' | cut -d '=' -f 1)
for attr in ${get_mandatory_attributes}
do
echo self.${attr} = ${attr}
done
echo ""
echo "#Optional"
for attr in ${get_optional_attributes}
do
echo self.${attr} = ${attr}
done
echo ""
for attr in ${get_mandatory_attributes}
do
echo "@property"
echo "def ${attr}(self):"
echo " return self._${attr}"
echo ""
echo "@${attr}.setter"
echo "def ${attr}(self, ${attr%"${attr#?}"}):"
echo " if type(${attr%"${attr#?}"}) is not str:"
echo " raise Exception(\"${attr} should be string. Currently it's %s\" % type(${attr%"${attr#?}"}))"
echo " self._${attr} = ${attr%"${attr#?}"}"
echo "\n"
done
for attr in ${get_optional_attributes}
do
echo "@property"
echo "def ${attr}(self):"
echo " return self._${attr}"
echo ""
echo "@${attr}.setter"
echo "def ${attr}(self, ${attr%"${attr#?}"}):"
echo " if ${attr%"${attr#?}"} is not None:"
echo " if type(${attr%"${attr#?}"}) is not str:"
echo " raise Exception(\"${attr} should be string. Currently it's %s\" % type(${attr%"${attr#?}"}))"
echo " self._${attr} = ${attr%"${attr#?}"}"
echo "\n"
done
# For optional dictionaries
for attr in ${get_optional_attributes}
do
echo "if self.${attr} is not None:"
echo " @DICTION@['${attr}'] = self.${attr}"
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment