Skip to content

Instantly share code, notes, and snippets.

@MineRobber9000
Created April 16, 2017 23:42
Show Gist options
  • Save MineRobber9000/fb50546182cb4bf6d82e4258e8ffb3ad to your computer and use it in GitHub Desktop.
Save MineRobber9000/fb50546182cb4bf6d82e4258e8ffb3ad to your computer and use it in GitHub Desktop.
A python module for making python modules.

PyMod

PyMod is a library I wrote in the course of writing a Brainfuck to Python compiler. It allows programmatic generation of python programs/modules. Methods of the Program class are:

Program.addImport

Adds an import to the module. Takes arguments where moduleName is the name of a module or feature, and futureImport is a boolean stating if the first argument is a module or feature. (defaults to False)

Program.addLine

Adds a line to the program. Takes argument line which is the line to add.

Program.fullcode

Outputs the full python code of the program. Takes 1 optional argument headers which are comments/a docstring in a list to go at the top of the file before any imports.

import pymod
# A basic Hello World with a date printout as well. Will be generated as test.py.
hwt = pymod.Program()
# Import print function (future import)
hwt.addImport("print_function",True)
# Import time library (regular import)
hwt.addImport("time")
# Add 2 lines of code.
hwt.addLine("print('Hello World!')")
hwt.addLine("print('Today is '+time.strftime('%B %d, %Y.'))")
# Export code to file
with open("test.py","w") as f:
f.write(hwt.fullcode());
# Uncomment next line if you want the code to be ran
# import test
# Python module to make other modules
class Program:
"""A python program"""
def __init__(self):
self.future_imports = []
self.imports = []
self.lines = []
def addImport(self,moduleName,futureImport=False):
if futureImport:
self.future_imports.append(moduleName)
return
self.imports.append(moduleName)
def addLine(self,line):
self.lines.append(line)
def fullcode(self,header=None):
if header:
ret = header
else:
ret = ["# code generated by PyMod - Python Modules made programmatically.","# PyMod by MineRobber9000, licensed under MIT License"]
if self.future_imports != []:
ret.append("from __future__ import "+",".join(self.future_imports))
importStatement = "import "+",".join(self.imports)
ret.append(importStatement)
ret.append("")
for line in self.lines:
ret.append(line)
return "\n".join(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment