random.choices can't be imported? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
this may be an easy one so sorry for the post but I can't seem to get random.choices() to import
my code:
import random
scans = 100
foobar = []
for i in range(scans):
string = 'https://'
string.join(random.choices(string.ascii_lowercase + string.digits, k = url_len))
string.join(random.choice(domains_list))
foobar.append(string)
del string
I am getting:
AttributeError: 'module' object has no attribute 'choices'
as an output in the mac-os terminal.
I have tried:
restarting editor
using from random import choices instead(alongside) of import random
again sorry if this seems like a spam post but I have been googling for a while and have not found a single answer.
Thanks to all! :D

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'

Related

NLTK function from string variable isn't callable [duplicate]

This question already has answers here:
import module from string variable
(7 answers)
How can I import a module dynamically given its name as string?
(10 answers)
Closed 5 years ago.
I have a list of related function names which I want to iterate thru, calling the function held in the variable. But no matter how I try it, I get: "TypeError: 'TweetTokenizer' object is not callable"
Following the solution in Calling a function of a module from a string with the function's name in Python (of which it is suggested this question is a duplicate), finds the functions in the nltk module and assigns them. But my resulting "tok_alg" function is still failing as not callable. Any advice on why this is happening would be appreciated.
#!/usr/bin/env python
import nltk
import os
testTxt="I'll have a Bloomin' Onion."
Tokenizers = [ 'Tweet', 'MWE', 'TreebankWord' ]
for tokenizer in Tokenizers:
tokz = tokenizer + 'Tokenizer'
tok_alg = getattr(nltk, tokz)()
result = tok_alg(testTxt)
print(result)
Listing the functions does work, viz
for tokenizer in [ TweetTokenizer(), MWETokenizer() ]:
result = tokenizer.tokenize(testTxt)
But the suggested conversion of str variables via getattr() is not working for NLTK. While this is elegant and practical, I need the string variables for other purposes. Surely there is some way to vivify these into a function call. What am I missing?

Python 2.7 function disappearing from module after import

I'm running a python script that imports a function, and then imports a class from a module with the same name as the function. For example:
from antioch import parrot
from antioch.parrot import Spam
If I print help(antioch) after the first import statement, it shows parrot() listed under the FUNCTIONS, however if I print help(antioch) after the second import statement the FUNCTIONS list no longer includes the parrot() function.
This causes a problem later in my code when trying to call the function as I get a 'module object us not callable' error.
I realise that I could probably avoid this issue by renaming the parrot module to a different name to the function but this would involve editing quite a lot of code and seems like a workaround which shouldn't be necessary.
Is there a better way around this problem?

Python __import__ is only giving me top level module [duplicate]

This question already has answers here:
How can I import a module dynamically given its name as string?
(10 answers)
Closed 9 years ago.
I'm doing
module = __import__("client.elements.gui.button", globals(), locals(), [], 0)
But it's only returning client.
What is my problem?
That's what __import__ does.
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name.
You're not really supposed to use __import__; if you want to import a module dynamically, use importlib.import_module.
Accepted answer is correct, but if you read on in the docs you'll find that this can be gotten around with an admittedly unsettling "hack" by using __import__ like so:
module = __import__('client.elements.gui.button', fromlist=[''])
It doesn't really matter what you pass in for fromlist so long as it's a non-empty list. This signals to the default __import__ implementation that you want to do a from x.y.z import foo style import, and it will return the the module you're after.
As stated you should use importlib instead, but this is still a workaround if you need to support Python versions < 2.7.
It only obtains the top level, but you can also work around this like so:
module_name = 'some.module.import.class'
module = __import__(module_name)
for n in module_name.split('.')[1:]:
module = getattr(module, n)
# module is now equal to what would normally
# have been retrieved where you to properly import the file

In Python, is it a good practice to import all attributes with a wildcard? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
and why?
Sometimes I need import all the attributes of a module so I use wildcard importing, but one of my Vim scripts(using flake8 as its syntax checker) always gives me an warning and tell me unable to detect undefined names.
Is there any other disadvantages of using wildcard importing?
It's generally not a good idea to use from module import *. Wildcard importing leads to namespace pollution; you imported more names than you need and if you accidentally refer to an imported name you may not get the NameError you wanted.
Also, if a future version of the library added additional names, you could end up masking other names, leading to stranger bugs still:
from foo import bar
from spam import *
If you upgrade spam and it now includes a spam.bar it'll replace the foo.bar import in the line above.
Using the wildcard import can cause subtle bugs:
foo.py
import sys
os = sys # just for the fun of it... :-D
python console
>>> import os
>>> from foo import *
>>> os.path.join('p1', 'p2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
This is especially important when updating library versions. They might or might not add new variables and break your code in horrible ways.
If you really want to use the * import always place it first so that other imports and definitions take precedence.
Good answers so far, but always nice to refer to the PyDocs:
Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practise in production code.
The answer by Martijn correctly addresses the issue of namespace polution, but I don't think any of the answers here have yet correctly addressed what I consider to be the biggest problem ... It's not explicit.
Consider a hypothetical module:
#foo.py
from bar import *
from baz import *
from qux import *
def breakfast(x):
with corn_beef_hash(x) as yummy:
for egg in yummy:
yield ham(egg.scrambled)
Now a few months later, you can't seem to remember what corn_beef_hash actually does so you go to look at the documentation -- except that you can't remember whether corn_beef_hash was part of bar or baz or qux. This makes it harder to track down. Also, if you know where the function was originally defined, that gives you some hints about what it's supposed to be doing which can make the code easier to read.
Yes there are, if you import everything using the wildcard you take everything from that package and turn it into an instance in your script, a better way of doing this is to simply import the package:
ex.
import package
package.x
this way you won't run into naming issues.

Python import trouble

I am having some trouble importing a class from a particular module. The class is in the module my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7
This code works
import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7
which means to access my class I have to do
my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7.MyClass
But this does not
from my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 import MyClass
Neither does this
import my_module1.my_module2.my_module3.my_module4.my_module5.my_module6.my_module7 as my_name
Both Give this error saying
AttributeError: 'module' object has no attribute my_module7'
This has me completely stumped and I have been working on it for a couple of weeks now. Any suggestions?
EDIT - I cant change the structure unfortunately as it is imposed by the system I am using
Looks like a circular import.
Gordon McMillan says:
Circular imports are fine where both modules use the “import ” form of import. They fail when the 2nd module wants to grab a name out of the first (“from module import name”) and the import is at the top level. That’s because names in the 1st are not yet available, because the first module is busy importing the 2nd.
I think you may want to consider an alternate design in the first place (redesigning your module breakdown so it's a flatter setup), but as that isn't your question try:
import my_module1.my_module2.my_modu...<etc>
my_name = my_module1.my_module2.my_modu...<etc>
my_name.MyClass
A module is a first class object in python, so you can alias them with variables.

Categories

Resources