Python - object has no attribute 'randint' - python

I want to import the random module to use randint and get a random number from 1 to 10. I have this so far:
import random
number = random.randint(1,10)
print number
I've also tried importing randint specifically, but that doesn't work either. With the code above, I get object has no attribute 'randint.'
I've come across plenty of people getting this error. The solution has always been to find the file you've named random.py and change its name because the script is loading that instead of the real module. I understand that, but I can't find that file; I've searched high and low, and the only file I can find named random.py is the real module in the Python library list.

I think you're probably using a statement too specific at the top of your file such as:
from random import random
Instead of the correct, (but more broad) statement:
import random

From what you're saying, you can import random, but it's not the random module.
If random.__file__ works, then it's another module, and you get the path. Remove this path from your python file, or rename the file.
If it does not work (as your comment suggests), you need to investigate further. Use type(random), help(random), etc... to find out what it is and you should be able to get more color. See if you are importing some modules before in your workflow, in which random is defined.

I have run into this basic issue multiple times. You would think I would learn by now.
You may have a file in that directory or in the path of your own making that is called "random.py"
When you go to import random from your code it steps on itself.

Add this (#!/usr/bin/python)to your top of the file save and run again.
#!/usr/bin/python
It will automatically add this two line below to above #!/usr/bin/python, (FYI I am using Sublimetext3)
(# -*- coding: utf-8 -*-)
from __future__ import unicode_literals

Related

Python file does not recognize imported functions from other Python files

I'm trying to make my code more organized by creating separate files for various functions. I'm testing out printing scenes of dialogue with a text scrolling code, and instead of keeping every line of dialogue in one file, I have moved it to a scene0.py file in the folder scenes. In that file, I define the function playscene0.
In a different folder called scenetext, I have a file called textstuff.py which contains the defined functions print_italics (which prints italics text), texttype (which makes each character type out individually like some video games do), and textscroll (which reads lists of dialog and formats it, plus timings with time.sleep).
That aforementioned scene0.py file uses from scenetext.textstuff import * to import the above functions, plus additional variables that go along with them (unique to that file). VSCode seems to initially recognize that all the functions being used in the playscene0 function have been successfully imported.
In my importtest file:
from scenes.scene0 import playscene0
playscene0()
This gives me:
NameError: name 'print_italics' is not defined
Though it very much is defined in the file it is derived from.
I've already looked into circular imports and how they cause problems, but that doesn't seem to be the cause here. I've tried importing both time and everything from scenetext.textstuff in the importtest file directly, but the problem persists.
Any suggestions are welcome, thank you
EDIT: After adding from scenetext.textstuff import print_italics to the importtest file, it gives me a different error upon running:
ImportError: cannot import name 'print_italics' from 'scenetext.textstuff' (/Users/[me]/vscode/VOYAGE/scenetext/textstuff.py)
Not sure what causes this.
You need to add an import to the importtest file - from scenetext.textstuff import print_italics, so that the function becomes "visible".
You should import the textstuff functions BEFORE you import the playscene function that uses them
from scenetect.textstuff import print_italics
from scenes.scene0 import playscene0
playscene0()

Taking an input from python file to another

I made a file that turns to other files and run their scripts consecutively. Most of these files have a common parameter which is an input. When I import it, it (of course) requests for input. I wish to avoid re-input of something.
Example:
MainFile.py:
import Base_params
import Liner
Base_params.py:
no_of_slices=int(input('Enter no. of Slices'))
sub_slice=int(input('enter sub slice'))
Liner.py:
from PIL import Image
import shutil
from Base_params import no_of_slices, sub_slice
The short answer is that Python handles this for you already exactly the way you want. To understand why, let me give you a little background on the import system.
When a module is imported for the first time, an empty module object is created. Then its code is executed and any names you bind are placed in its dictionary, which is also the global namespace for the module. In your case that would mean running the code of Base_params.py and creating the names no_of_slices and sub_slice based on the user input.
When the same module is imported subsequently, its code is not run (which is your concern). Instead, the object reference from sys.modules is returned. An import statement always checks whether a module is already loaded before attempting to run it again.
The reason that creating the empty module object (and placing it in sys.modules before running the module code is very important is that most modules have recursive imports. Marking the module as already imported ensures that any infinite loops are broken before they happen.
In your case, it is perfectly fine to define a module of constants that asks for user input. The first module that does import Base_params will trigger an execution of the input statements. All further occurrences of import Base_params will just bind sys.modules['Base_params'] to whatever the name Base_params in your namespace. There will not be a second query for no_of_slices and sub_slice.
The links to the official documentation I provided throughout will explain anything I missed.

Why is this python code running twice [duplicate]

This question already has an answer here:
Why Python print my output two times when I import the same file in which I am printing?
(1 answer)
Closed 2 years ago.
Here is the code
import random
print("Hello", end="")
print("twice")
and a screenshot of the code
When I execute this code it for some reason is running twice. The problem seems to be from the import random statement, because if I either remove that statement or import some other module it works fine.
What could be the reason for this, should I reinstall Python on my system.
There's nothing wrong with python.
The reason is simple:
Your module is importing itself (because it is also named random) - this has to do with the lookup mechanics of python. python will try to import from your root folder first, before modules from pythonpath are imported.
From the docs:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
The directory containing the input script (or the current directory
when no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
The installation-dependent default.
Since your file (module) is called random.py, import random will import this very file.
Now, what does "import" mean?
The statement import something will cause Python to lookup the name something, starting with the current directory.
Therefore, import random will result in an import of this very file, since its name will shadow the build-in random.
Besides, if the name to import is already in the namespace, then the import statement is ignored.
Once the module to import has been located, its code is executed.
As a result, the flow of your script is as follow:
Lookup the random.py name
Add random to the namespace
Execute the code contained in random.py
The random name already exists in the namespace, so the import random statement is ignored
Print the text
Print the text
The reason for this is you've named the script random.py and inside it you import random.
random will not import the built-in random module but, rather, the random module you've created. This leads to the script executing the same statements twice (and also leads to other ugly errors if you tried and import something from random, like from random import randrange.)
Renaming the script leads to normal behavior.
Because your scripts is called random.py, so when you import random you are executing your script as well. Mind to name correctly your scripts.
your python script is named random.py so when you import random it import itself , in python when you import module it will run it.
therefor you get print twice.
rename your script or remove the import

Linking Python Files Assistance

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.

Python "import random" Error

As you may know from my previous posts, I'm learning Python. And this time I have a small error which I think is with this build of Python itself. When using the following:
import random
number = random.randint(1,10000)
Python gives me this error:
File "C\Users\name\Documents\Python\random.py", line 5, in (module)
print random.random()
TypeError: 'module' object is not callable
Every time I try to run it. Me no understand. Any help would be much appreciated!
EDIT: The two lines of code I'm trying to run:
import random
print random.randint(1,100)
That's it. And it gives me the same error.
By naming your script random.py, you've created a naming conflict with the random standard library module.
When you try to run your script, the directory containing the script will be added to the start of the module import path. So when your script does import random, you're effectively running a second copy of the script as the random module.
When the random module runs import random, it means that random.random will also be a reference to your module. So when you attempt to call the random.random() standard library function, you're actually attempting to call the module object resulting in the error you got.
If you rename your script to something else, the problem should go away.
Even I faced the same problem. I have renamed my python file from random.py to shuffle.py. This didn't work out. Then I changed the version then it worked. This may help a bit.
Python version : 3.6.7
replace
import random;
to
import random2;
I am using pycharm and I had to take the additional step to import the methods from random. In my case:
import random
from random import choice
The simple answer: Change your filename from "random.py" to something else as it is conflicting with random library.

Categories