If you do your import like this, importing the function from the module:
from random import choices
Then your code needs to just refer to that function, since you haven't imported the module itself, so Python won't be aware of the module's name in your code:
choices(string.ascii_uppercase + string.digits, k = 10)
But if you instead import the whole module:
import random
Then your code needs to refer to both the module and the function, because the only way Python knows about the function is via the imported module:
random.choices(string.ascii_uppercase + string.digits, k = 10)
If you get this error:
AttributeError: 'module' object has no attribute 'choices'
Then that could mean you might also be using an old Python version which simply doesn't have choices
, as it was added in Python 3.6.
If that's not the case, then you possibly have a file named random.py
that's accidentally getting imported instead. See this question for more details if that's the case.
But without knowing more details about your python version and local files, it's impossible to say exactly why you in particular are getting that particular error.
Another issue in your above code is this line - it's overwriting your import string
statement, and setting string
to an actual string instead (your string was 'foobar'
but any string would've caused the issue):
string = 'foobar'
When you refer to the string
module right after, since you've overwritten it with the string 'foobar'
, trying to use the module at all (like string.ascii_uppercase
for example) will result in this kind of error:
AttributeError: 'str' object has no attribute 'ascii_uppercase'