code_extraction.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. import inspect
  2. import re
  3. from typing import Callable
  4. import isort
  5. UNCOMMENT_PATTERN = re.compile(r'^(\s*)# ?')
  6. def _uncomment(text: str) -> str:
  7. return UNCOMMENT_PATTERN.sub(r'\1', text) # NOTE: non-executed lines should be shown in the code examples
  8. def get_full_code(f: Callable) -> str:
  9. """Get the full code of a function as a string."""
  10. code = inspect.getsource(f).split('# END OF DEMO', 1)[0].strip().splitlines()
  11. code = [line for line in code if not line.endswith('# HIDE')]
  12. while not code[0].strip().startswith(('def', 'async def')):
  13. del code[0]
  14. del code[0]
  15. if code[0].strip().startswith('"""'):
  16. while code[0].strip() != '"""':
  17. del code[0]
  18. del code[0]
  19. indentation = len(code[0]) - len(code[0].lstrip())
  20. code = [line[indentation:] for line in code]
  21. code = ['from nicegui import ui'] + [_uncomment(line) for line in code]
  22. code = ['' if line == '#' else line for line in code]
  23. if not code[-1].startswith('ui.run('):
  24. code.append('')
  25. code.append('ui.run()')
  26. full_code = isort.code('\n'.join(code), no_sections=True, lines_after_imports=1)
  27. return full_code