Skip to content

Instantly share code, notes, and snippets.

@William-Lake
Last active December 27, 2018 14:45
Show Gist options
  • Save William-Lake/277a43f7d725ff638d09caa9b944841b to your computer and use it in GitHub Desktop.
Save William-Lake/277a43f7d725ff638d09caa9b944841b to your computer and use it in GitHub Desktop.
*SIMPLE* Python Class Wizard

Create Python Class File

A very basic wizard for creating a python class file.

Getting Started

NOTE: These instructions were written for Linux.

  1. Download the required files.

  2. Make the script executable

  3. Save it somewhere you can execute it from.

    a. If on Windows, follow this

    b. If on Linux, copy the script, 'method_template', and 'class_template' to /usr/bin

Usage

  1. Open a terminal and run the script, ensuring you provide the path to where you want the class file to be generated: create_python_class_file.py /path/for/generated/class
  2. Use the wizard to provide the required data to create one or more classes.

Examples

Most Basic Example

class BasicExample(object):

    def __init__(self):

        pass

Class with init Params

class BasicExampleWithInit(object):

    def __init__(self,first_param, second_param):

        pass

Class with Methods

class BasicExampleWithMethod(object):

    def __init__(self):

        pass

    def first_method(self):

        pass

    def second_method(self):

        pass

Class with Methods with Params

class BasicExampleWithMethodParams(object):

    def __init__(self):

        pass

    def example_method(self,first_method, second_method):

        pass
class !CLASS_NAME!(!BASE_CLASS!):
def __init__(self!INIT_PARAMS!):
pass
#!/usr/bin/env python3
import argparse
import re
import os
from os import name
def clear_screen():
'''Clears the console. OS Independent.'''
if name == 'nt': os.system('cls')
else: os.system('clear')
def gather_input(prompt,break_on_empty_input=False):
'''Gathers input from the user.
Arguments:
prompt {str} -- The prompt to provide the user.
Keyword Arguments:
break_on_empty_input {bool} -- If True, the process ends when no input is provided. (default: {False})
Returns:
str -- The user's input response to the prompt.
'''
user_response = ''
while True:
clear_screen()
user_response = input(prompt)
if (
len(user_response.strip()) > 0 or
(
len(user_response.strip()) == 0 and
break_on_empty_input)): break
return user_response
def gather_inputs(prompt):
'''Gathers multiple user inputs with the same prompt.
Arguments:
prompt {str} -- The prompt to provide the user.
Returns:
list -- The user's input responses to the prompt.
'''
user_responses = []
while True:
user_response = gather_input(prompt,break_on_empty_input=True)
if len(user_response) == 0: break
else: user_responses.append(user_response)
return user_responses
def gather_methods():
'''Gathers all the method data, if the user wants to provide any.
Returns:
str -- The methods as one string.
'''
methods = []
method_template_file_name = os.path.realpath(__file__).replace('create_python_class_file.py','method_template')
method_template = open(method_template_file_name).read()
if gather_input('Are there any methods to add? (Y/N)').strip().upper()[0] == 'Y':
while True:
method_name = gather_input('Method Name?')
method_params = (
''
if gather_input('Are there any method params? (Y/N)').strip().upper()[0] != 'Y'
else ',' + ', '.join(gather_inputs('?')))
method = re.sub(r'!METHOD_NAME!',method_name,method_template)
method = re.sub(r'!METHOD_PARAMS!',method_params,method)
methods.append(method)
if gather_input('Add another method? (Y/N)').strip().upper()[0] != 'Y': break
return ''.join(methods)
def create_class_file(target_path,class_name,base_class_name,init_params,methods):
'''Creates the class file using the provided data.
Arguments:
target_path {str} -- The path to write the class file.
class_name {str} -- The class' name in snake_case.
base_class_name {str} -- The base class name the class is extending.
init_params {str} -- The params to include in the class' __init__ method.
methods {str} -- The class' methods as a string.
'''
file_name = f'{class_name}.py'
class_name = class_name.replace('_',' ').title().replace(' ','')
class_template_file_name = os.path.realpath(__file__).replace('create_python_class_file.py','class_template')
class_template = open(class_template_file_name).read()
class_data = re.sub(r'!CLASS_NAME!',class_name,class_template)
class_data = re.sub(r'!BASE_CLASS!',base_class_name,class_data)
class_data = re.sub(r'!INIT_PARAMS!',init_params,class_data)
with open(os.path.join(target_path,file_name),'w+') as out_file:
out_file.write(class_data)
out_file.write(methods)
def setup_argparse():
'''Sets up the argparser for this script.
Returns:
ArgParser -- The argparser to use for this script.
'''
parser = argparse.ArgumentParser(description='Create a new python class file.')
parser.add_argument('target_path',type=str,help='The target path to write the class file to.')
return parser
if __name__ == "__main__":
'''Main Method'''
parser = setup_argparse()
args = parser.parse_args()
target_path = args.target_path
while True:
class_name = gather_input('Class Name? (In snake_case, E.g. class_name NOT ClassName)')
base_class_name = gather_input('Base Class Name? (In TitleCase, E.g. ClassName NOT class_name. If unsure, enter "object")')
init_params = (
''
if gather_input('Are there any __init__ params? (Y/N)').strip().upper()[0] != 'Y'
else ',' + ', '.join(gather_inputs('?')))
methods = gather_methods()
create_class_file(target_path,class_name,base_class_name,init_params,methods)
if gather_input('Create another class file?').strip().upper()[0] != 'Y': break
def !METHOD_NAME!(self!METHOD_PARAMS!):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment