from cjm_psl_utils.core import get_source_code
cjm-psl-utils
Some utility functions using the Python Standard Library.
This file will become your README and also the index of your documentation.
Install
pip install cjm_psl_utils
How to use
get_source_code
=True) get_source_code(get_source_code, markdown
def get_source_code(obj:object, # The object whose source code you want to retrieve.
=False, # Return the source code formatted as markdown
markdown=False): # Remove docstrings and comments
remove_documentation"""
Returns the source code of an object, with an optional markdown formatting.
"""
# Get the source code of the object
= inspect.getsource(obj)
source
# If the remove_documentation flag is set to True, remove docstrings and comments
if remove_documentation:
= False
in_docstring = source.split('\n')
lines = ''
source # Remove docstrings
for line in lines:
if line.strip().startswith(('\'\'\'', '\"\"\"')):
= not in_docstring
in_docstring elif not in_docstring:
+= line + '\n'
source # Remove comments
= '\n'.join([line for line in source.split('\n')
source if not line.strip().startswith(('#'))])
= source.replace('\n\n', '\n')
source
if markdown:
# Format the source code as markdown code block
= f"```python\n{source}\n```"
source
# Check if the code is running in Jupyter Notebook
try:
get_ipythonfrom IPython.display import Markdown
# Format the source code as an IPython Markdown object
= Markdown(source)
source except NameError:
# If not in Jupyter Notebook, do nothing
pass
# Return the formatted source code
return source
file_extract
from cjm_psl_utils.core import file_extract
from pathlib import Path
= "../images/images.zip"
fname = Path("./images") dest
print(dest.exists())
file_extract(fname, dest)print(dest.exists())
print(list(os.walk(dest))[0][2])
False
True
['cat.jpg']