5090

Why is calling `import random; random.random()` throwing a TypeError?

Question:

I'm new to Python. I wrote a small script to generate ten random float values, but it keeps failing. Here's the script:

import random for i in range(10): x = random.random() print x

and here's the error message:

TypeError: 'module' object is not callable'.

I can't see what the problem is. I'm pretty sure random exists!

My version is Python 2.7.6.

Answer1:

If you save the following code into random.py:

import random print(__name__) print(random) print(random.random)

and run it then it prints something like:

random <module 'random' from '/.../python/import/name-shadowing/random.py'> <module 'random' from '/.../python/import/name-shadowing/random.py'> __main__ <module 'random' from '/.../python/import/name-shadowing/random.py'> <module 'random' from '/.../python/import/name-shadowing/random.py'>

i.e., both random and random.random refers to the same module -- your local random.py that shadows random module from the standard library.

Perhaps it works as follows:

<ol><li>python -mrandom finds random.py in the current directory, imports it as random and and starts to run it as __main__.</li> <li>It sees import random and imports the cached module.</li> <li>print(random) prints the representation of the module object to stdout.</li> <li>print(random.random) looks up random name in random module. It finds it (the name refers to the module itself. And it prints it.</li> </ol>

The solution is to avoid shadowing the names. Avoid shadowing the standard names for readability. And avoid shadowing 3rd-party names if you might use them in your code.

If the current directory is not in sys.path then it imports stdlib module:

import sys sys.path.pop(0) # assume the script directory is the first in the Python path import random print(__name__) print(random) print(random.random) <h3>Output</h3> __main__ <module 'random' from '/usr/lib/python3.4/random.py'> <built-in method random of Random object at 0x1aaf7f8>

Note: it is only for illustration. Avoid modifying sys.path in your scripts.

Recommend

  • what is “this instanceof fNOP ? this” doing?
  • Using ExecutorService to repeatedly perform a number of similar tasks in parallel
  • Can we Create Smart Device Project in VIsual Studio 2015 Professional
  • Java Generic Type Inference Strange Behavior?
  • mfc - MessageBox with rich text
  • is this code truly private? (python)
  • Pandas groupby to to_csv
  • Cannot find “Grammar.txt” in python-sphinx
  • Python 3.2.2, error(scripts to exe)
  • C# - Most efficient way to iterate through multiple arrays/list
  • C#: Import/Export Settings into/from a File
  • netsh acl setting (need alternative method - registry settings?)
  • pip in virtualenv gets ConnectTimeoutError
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • pillow imaging ImportError
  • gspread or such: help me get cell coordinates (not value)
  • How can I set a binding to a Combox in a UserControl?
  • Django simple Captcha “No module named fields” error
  • How to add git credentials to the build so it would be able to be used within a shell code?
  • Remove final comma from string in vb.net
  • Groovy: Unexpected token “:”
  • AJAX Html Editor Extender upload image appearing blank
  • How to know when stdin is empty if it contains EOF?
  • How to create a file in java without a extension
  • recyclerView does not call the onBindViewHolder when scroll in the view
  • MySQL WHERE-condition in procedure ignored
  • Join two tables and save into third-sql
  • Deserializing XML into class C#
  • In LanguageTool, how do you create a dictionary and use it for spell checking?
  • How to model a transition system with SPIN
  • ORA-29908: missing primary invocation for ancillary operator
  • How to include full .NET prerequisite for Wix Burn installer
  • python regex in pyparsing
  • Acquiring multiple attributes from .xml file in c#
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • costura.fody for a dll that references another dll
  • Converting MP3 duration time
  • java string with new operator and a literal
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize