Skip to content

Commit

Permalink
Merge commit 'f92c9e7df9d50efa451ae4cd62da8b229db8d1b3' into thread-sig
Browse files Browse the repository at this point in the history
  • Loading branch information
Carreau committed Oct 2, 2023
2 parents 9e29ac4 + f92c9e7 commit 8516262
Showing 1 changed file with 39 additions and 4 deletions.
43 changes: 39 additions & 4 deletions papyri/signature.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import inspect

from dataclasses import dataclass
from typing import List, Any, Dict, Union
from typing import List, Any, Dict, Union, Optional
from .common_ast import Node
from .errors import TextSignatureParsingFailed

from .common_ast import register

import json

@register(4031)
class Empty(Node):
Expand Down Expand Up @@ -100,12 +101,17 @@ def to_node(self) -> SignatureNode:

parameters = []
for param in self.parameters.values():
if param.annotation is inspect._empty:
annotation = _empty
elif isinstance(param.annotation, str):
annotation = param.annotation
else:
# TODO: Keep the original annotation object somewhere
annotation = inspect.formatannotation(param.annotation)
parameters.append(
ParameterNode(
name=param.name,
annotation=_empty
if param.annotation is inspect._empty
else str(param.annotation),
annotation=annotation,
kind=param.kind.name,
default=_empty
if param.default is inspect._empty
Expand Down Expand Up @@ -138,6 +144,15 @@ def param_default(self, param):
def annotations(self) -> bool:
return self.target_item.__annotations__

@property
def return_annotation(self) -> Optional[str]:
return_annotation = self._sig.return_annotation
return (
None
if return_annotation is inspect._empty
else inspect.formatannotation(return_annotation)
)

@property
def is_public(self) -> bool:
return not self.target_item.__name__.startswith("_")
Expand Down Expand Up @@ -170,5 +185,25 @@ def keyword_only_parameter_count(self):
else:
return None

def to_dict(self) -> dict:
"""
Output self as JSON (Python dict), using the same format as Griffe
"""
json_data = self.to_node().to_dict()

# Use human-readable names for parameter kinds
for param in json_data["parameters"]:
param["kind"] = getattr(inspect._ParameterKind, param["kind"]).description

json_data["returns"] = self.return_annotation

return json_data

def to_json(self) -> bytes:
"""
Output self as JSON, using the same format as Griffe
"""
return json.dumps(self.to_dict(), indent=2, sort_keys=True).encode()

def __str__(self):
return str(self._sig)

0 comments on commit 8516262

Please sign in to comment.