astroid icon indicating copy to clipboard operation
astroid copied to clipboard

Behavior of infer when function name clashes with brain

Open usagitoneko97 opened this issue 6 years ago • 1 comments

Sorry if this is a dumb question. I have the following code:

import astroid
node = astroid.extract_node(
            """
        def sample(a, b=None):
            return a
        sample([1, 2, 5, 6], 2) #@
        """
        )
inferred = next(node.infer())
elems = sorted(elem.value for elem in inferred.elts)

After inferring the return value to the sample call, the elems returned a list that contained 2 values, whereas it should be [1, 2, 5, 6] in this case. I understand that probably random brain has something to do with it, but why this behavior is the default even though random module was never imported?

usagitoneko97 avatar Feb 22 '19 06:02 usagitoneko97

Thanks for opening an issue @usagitoneko97 Yes, you are definitely right, the random brain uses a simple check to "figure" out if sample comes from random module or not, but it's so simple that it only matches the name of the function with sample. Unfortunately we can't infer what node represents in a transform predicate function, as those transforms might be called before the inference engine is fully set up. An alternative would be to not match function names any longer, but attribute access, which means we'll be applying the transform to random.sample, but not to from random import sample; sample(). This might not be a big of a deal if we change that approach.

PCManticore avatar Feb 27 '19 08:02 PCManticore