1

Looking at this Difference between list(numpy_array) and numpy_array.tolist() got me interested in this question. While I don't think that calling list on a numpy array is necessarily a problem, it is often not what I would prefer compared to using the np.ndarray.tolist method.

Just using something like grep for list would return far too many results in some projects. But for some input x it is difficult for me to think of any generally-applicable regex for it.

So instead I am wondering if there is some other way to search the code for calling a list on a numpy array. My best guess is to use the ast library, but I am not familiar with it.

Ideally I would like some kind of function.

import ast


def is_list_on_arr(code):
    '''Indicate if list called on numpy array.'''
    ...

if __name__ == "__main__":
    code = """
    import numpy as np
    arr = np.array([1, 2, 3])
    lst = list(arr)
    """
    is_list_on_arr(code)

How can I check if a code base contains such a pattern?

2
  • 1
    Unless your IDE has a check for this, I don't think it will be easy to do. Figuring out data flow and the types of parameters is complex. Commented Apr 26, 2023 at 18:03
  • 1
    Unless you were in the habit of using list like this, you probably won't find many cases. More likely you might have hidden instances, such as list comprehension, [i for i in an_array] or the equivalent for loop. Commented Apr 26, 2023 at 21:14

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.