Converts `docment` docstrings to Numpy styled
The goal of this module is to take code that looks like the following:
def addition(
a:int, # The first number to add
b:int=2, # The second number to add
) -> int: # The sum of a and b
"Adds two numbers together"
return a+b
And convert it to be the following:
def addition(a,b) -> int:
"""Adds two numbers together
Parameters
---------
a : int
The first number to add
b : int
The second number to add
Returns
-------
int
The sum of a and b
"""
return a + b
Below we have an example string repsentation of the above docments style:
source = '''def addition(
a:(int, float), # The first number to add
# The second number to add
b:int = 2,
) -> (int,float): # The sum of a and b
"Adds two numbers together"
return a+b'''
test_eq(get_annotations(source), (['(int, float)', 'int'], '(int, float)'))
test_eq(_get_leading(' Hello my name is Zach'), (2, ' '))
source = """@delegates()
def addition(
a:(int, float), # The first number to add
# The second number to add
b:int = 2,
) -> (int,float): # The sum of a and b
"Adds two numbers together"
def _inner(): return a+b
return _inner()"""
print(source)
print(reformat_function(source))
source = '''class Arithmetic:
"A class that can perform basic arithmetic on ops"
_o = 2
_b = 5
_c = 3
class A:
def __init__(
self,
o:int # An integer
):
self.o = o
def __init__(
self,
a:int, # The first number to use
b:(int, float), # The second number to use
):
self.a = a
self.b = b
@delegates()
def add(
self
) -> (int,float): # Sum of a and b
"Adds self.a and self.b"
return self.a + self.b'''
print(reformat_class(source))
multiple_funcs = '''from fastai.vision.all import *
import numpy as np
class Arithmetic:
"A class that can perform basic arithmetic on ops"
_o = 2
_b = 5
_c = 3
class A:
def __init__(
self,
o:int # An integer
):
self.o = o
def __init__(
self,
a:int, # The first number to use
b:(int, float), # The second number to use
):
self.a = a
self.b = b
@delegates()
def add(
self
) -> (int,float): # Sum of a and b
"Adds self.a and self.b"
return self.a + self.b
def foo(
a:int, # First
b:int, # Second
) -> (int, float): # Sum of a and b
"Adds"
return a+b
def baz(
a:int, # First
b:int, # Second
) -> (int, float): # Difference of a and b
"Subtracts"
return a-b
myConst = 22
def bar(
a:int, # First
b:int, # Second
) -> (int, float): # Product of a and b
"Multiplies"
return a*b'''
Cleaning and Transforming Files
Given the above's usage of AST trees to rebuild your code, it automatically looks very similar to something that would come out of a code formatter, such as Black or Flake8. However, we still need to convert individual files, not just handling certain capabilities.
This is what the below functionality does