Python 3.6中TypeError: 'range'对象不可调用问题求助
TypeError: 'range' object is not callable in Your NMF Collaborative Filtering Code Hey there! Let's break down why you're hitting this error when running sdrange = range(2,50,2) in your Python 3.6 code, and how to fix it quickly.
The Root Cause
This error almost always happens when you've accidentally overwritten Python's built-in range() function with a range object earlier in your code. For example, if you had a line like:
# This is the problematic line! range = range(1, 10)
After this, range is no longer the callable function you know—it's now a concrete range object. So when you try to call range(2,50,2) later, Python throws the TypeError because you can't "call" an object like a function.
How to Verify
To confirm this is the issue, add this line right before your problematic sdrange = range(2,50,2) statement:
print(type(range))
- If the output is
<class 'range'>, you've definitely overwritten the built-in function. - If it's
<class 'builtin_function_or_method'>, then the issue is somewhere else (but this is rare for this specific error).
Steps to Fix
- Rename conflicting variables: Scan your entire code for any line where you assigned something to a variable named
range. Change that variable name to something unique—likenmf_range,my_range, oritem_range—anything that doesn't clash with Python's built-in names. - Test with the built-in explicitly (temporarily): If you need a quick test to confirm the fix works, you can call the original built-in function directly using the
builtinsmodule:
This skips the overwrittenimport builtins sdrange = builtins.range(2,50,2)rangevariable and uses the native function. - Build better naming habits: Going forward, avoid using Python's built-in function/class names (like
list,dict,str,range,sum) as variable names. This will prevent these kinds of frustrating bugs entirely.
Since you're working on an NMF collaborative filtering implementation, it's likely you used range to define something like the number of latent factors or a range of hyperparameters—just give that variable a more descriptive, non-conflicting name and you'll be good to go.
内容的提问来源于stack exchange,提问作者ESLearner

