fastai / nbdev

Create delightful software with Jupyter Notebooks
https://nbdev.fast.ai/
Apache License 2.0
4.8k stars 484 forks source link

How to document a module and or constants? #1367

Open dsm-72 opened 9 months ago

dsm-72 commented 9 months ago

Let's say I have a notebook 00_cons.ipynb Which contains some constants (maybe some compiled regex expressions, or maybe just some default values)

Example Notebook 00_cons.ipynb

Constants

constants for my package

#| default_exp cons
#| hide
from nbdev.showdoc import *

Named Literals

#| export
ASTERICK = '*'
# default values, string-ly typed options, etc
# ...

Meta-Data Keys

#| export
OBS = 'obs'
VAR = 'var'

Regex Expressions

some precompiled regex expressions

#| export
import re
#| export
WORDS_TO_SNAKE_WITH_UPPERCASE = re.compile(
    r'[A-Z]?[a-z]+'                     # A possible uppercase followed by lowercase letters
    r'|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)' # Two or more consecutive uppercase letters
    r'|\d+'                             # One or more digits
    r'|[A-Z]{2,}'                       # Two or more consecutive uppercase letters
    r'|[A-Z]$'                          # Uppercase letter at end of string
)
#| hide
import nbdev; nbdev.nbdev_export()

Problem Statement

Above doesn't really generate any documentation Now we could add an 00__init__.ipynb file with a #| default_exp cons.__init__ to try and get around this.

#| hide
from types import ModuleType
def is_dunder(s: str) -> bool: 
    return s.startswith('__') and s.endswith('__')

def drop_dunders(m: ModuleType) -> list: 
    return list(filter(lambda s: not is_dunder(s), dir(m)))

def cons_dict(m: ModuleType) -> dict:
    return dict(zip(m.__all__, list(map(lambda a: getattr(m, a), m.__all__))))

from mypkg import cons
show_doc(cons)
show_doc(drop_dunders(cons))
show_doc(cons_dict(cons))

None of these work well.

CONST: str = 'A_CONSTANT''''
This is my constant

Parameters
----------
Here is a note
'''
show_doc(CONST)

Will yield

A_CONSTANT
This is my constant

Parameters
Here is a note

A_CONSTANT This is my constant

See #1313 . As show_doc doesn't work with Notes, etc

deven367 commented 9 months ago

@dsm-72 I think the only other option in this case would be to make these as class variables.