I am making a PyCharm plugin that will generate code examples based on a Python class. The user will be able to select a class and the plugin will generate code examples that utilise the attributes and methods of the class.
Basic Class
class Rectangle:
# Hardcoded values
width = 5
length = 10
def calculate_area(self):
return self.width*self.length
Basic Example
r = Rectangle()
r.calculate_area()
The problem arises when the class contains methods that take parameters. For example, if the class contains a method that takes a string parameter, then I want the generated examples to pass either an empty or a random string to the method. Is there a good way to analyse the potential type of the parameters (when not strongly defined) to generate code examples?
Potential Solutions
So far I have come up with 2 applicable solutions (passing None parameters when calling the method is not applicable):
- A potential solution would be to keep track of the parameters and analyse the operations that they use/are used in to determine their type. In the code below num will most likely be an integer, as determined by the method body:
def calculate_even(num):
return num % 2 == 0
- I know that you can execute a string containing Python code and check if it compiles correctly (source). A possible solution (one that I would love to avoid) is to generate code examples, passing different types as method parameters and determining which ones work after executing said code examples.
I can see huge downsides with both solutions, as the first one will require the handling of lots of operations for the different types and will still most likely be inaccurate, and the second one becomes incredibly slow for methods that take multiple parameters. I am really hoping that there's a more elegant solution that I have missed.
source https://stackoverflow.com/questions/75440251/can-you-efficiently-analyse-the-type-of-method-parameters-in-python
Comments
Post a Comment