Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docmnets fails on class constructors #343

Closed
muellerzr opened this issue Aug 8, 2021 · 2 comments
Closed

docmnets fails on class constructors #343

muellerzr opened this issue Aug 8, 2021 · 2 comments

Comments

@muellerzr
Copy link
Contributor

If we pass in a class for the docments function, it completely fails. I would expect it to look at the __init__ for all the relevant information it would need (as it's the class constructor). Basic breaking example:

class Add:
    "A basic addition class"
    def __init__(
        self,
        a:int = 0, # The first number to be added
        b:(int, float) = 1.5, # The second number to be added
    ):
        self.a = a
        self.b = b
    
    def add(
        self,
    ) -> Union[int, float]:
        "Adds `self.a` and `self.b`"
        return self.a + self.b
docments(Add)

Stack trace:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-101-f7728d42a6d5> in <module>()
----> 1 docments(Add)

/mnt/d/lib/python3.7/site-packages/fastcore/docments.py in docments(s, full, returns)
     55 def docments(s, full=False, returns=True):
     56     "`dict` of parameter names to 'docment-style' comments in function or string `s`"
---> 57     comments = {o.start[0]:_clean_comment(o.string) for o in _tokens(s) if o.type==COMMENT}
     58     parms = _param_locs(s, returns=returns)
     59     docs = {arg:_get_comment(line, arg, comments, parms) for line,arg in parms.items()}

/mnt/d/lib/python3.7/site-packages/fastcore/docments.py in _tokens(s)
     22     "Tokenize Python code in string or function object `s`"
     23     if isfunction(s): s = getsource(s)
---> 24     return tokenize(BytesIO(s.encode('utf-8')).readline)
     25 
     26 _clean_re = re.compile('^\s*#(.*)\s*$')

AttributeError: type object 'Add' has no attribute 'encode'
@muellerzr
Copy link
Contributor Author

A potential fix is changing the first line of docments to see if it's a class, and if so call the __init__

    if isclass(s): s = s.__init__ # Constructor for a class
    comments = {o.start[0]:_clean_comment(o.string) for o in _tokens(s) if o.type==COMMENT}
    ...

@muellerzr
Copy link
Contributor Author

Fixed with #347

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant