Random in python 2.5 not working? - python

I am trying to use the import random statement in python, but it doesn't appear to have any methods in it to use.
Am I missing something?

You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file.
To tell for sure what's going on, do this:
>>> import random
>>> print random.__file__
That will show you exactly which file is being imported.

This is happening because you have a random.py file in the python search path, most likely the current directory.
Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py.
This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax.
Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.

I think you need to give some more information. It's not really possible to answer why it's not working based on the information in the question. The basic documentation for random is at:
https://docs.python.org/library/random.html
You might check there.

Python 2.5.2 (r252:60911, Jun 16 2008, 18:27:58)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed()
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> random.randint(0,3)
3
>>> random.randint(0,3)
1
>>>

If the script you are trying to run is itself called random.py, then you would have a naming conflict. Choose a different name for your script.

Can you post an example of what you're trying to do? It's not clear from your question what the actual problem is.
Here's an example of how to use the random module:
import random
print random.randint(0,10)

Seems to work fine for me. Check out the methods in the official python documentation for random:
>>> import random
>>> random.random()
0.69130806168332215
>>> random.uniform(1, 10)
8.8384170917436293
>>> random.randint(1, 10)
4

Works for me:
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> brothers = ['larry', 'curly', 'moe']
>>> random.choice(brothers)
'moe'
>>> random.choice(brothers)
'curly'

Related

importing a class from a module starting with number

I need to import a single class (not the whole file) from a python file starting with number.
There was a topic on importing a whole module and it works, but can't find my way around this one.
(In python, how to import filename starts with a number)
Normally it would be:
from uni_class import Student
though the file is called 123_uni_class.
Tried different variations of
importlib.import_module("123_uni_class")
and
uni_class=__import__("123_uni_class")
Error:
from 123_uni_class import Student
^
SyntaxError: invalid decimal literal
importlib.import_module("123_uni_class") returns the module after importing it, you must give it a valid name in order to reuse it:
import importlib
my_uni_class = importlib.import_module("123_uni_class")
Then you can access your module under the name 'my_uni_class'.
This would be equivalent to import 123_uni_class as my_uni_class if 123_uni_class were valid in this context.
It works for me:
Python 3.6.8 (default, Feb 14 2019, 22:09:48)
[GCC 7.4.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import importlib
>>> importlib.import_module('123_a')
<module '123_a' from '/path/to/123_a.py'>
>>> __import__('123_a')
<module '123_a' from '/path/to/123_a.py'>
You would not see an actual syntax error containing the literal text "from 123_uni_class import ..." unless you actually have some source code containing that line.
If you must, you can also bypass the import system entirely by reading the contents of the file and exec()-ing them, possibly into a namespace you provide. For example:
mod = {}
with open('123_uni_class.py') as fobj:
exec(fobj.read(), mod)
Student = mod['Student']
This general technique is used, for example, to read config files written in Python and things like that. I would discourage it though for normal usage and suggest you just use a valid module name.

Do I have to reload a module in python to capture changes?

I am running python 3.6.4 (anaconda, spyder).
Do I need to reload a user-defined module in order to capture the changes?
For example, suppose I wrote the simple function and save it in test.py file:
def plus5(x):
return x + 5
Then in the IPython console I type
import test as t
and then I change the user-defined function to:
def plus5(x):
return x + 500
Then when I type in IPython console
t.plus5(0)
it returns 500 without re-importing or reloading the module first.
If I change the function name from plus5 to something else then I have to re-import the module to see the change. But when I change the function statements then it automatically captures the changes without re-importing the module
From the Python documentation:
Note: For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload()
e.g. import importlib; importlib.reload(modulename).
This is a feature in the IPython interpreter name autoreload. It has the magic command %autoreload which allows for activating or deactivating this feature. It seems to be on by default, but I was not able to find something proving that.
As Megalng explained, this is a built in feature of IPython interpreter and in default Python interpreter you have to use importlib to reload the module. Here is default python interpreter execution,
Python 3.6.2 (default, Sep 5 2017, 17:37:49)
[GCC 4.6.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import test as t
>>> t.plus5(0)
5
>>>
>>>
>>> #Changed function body to return x + 500
...
>>> t.plus5(0)
5
>>> import test as t
>>> t.plus5(0)
5
>>> #It had no affect, even importing again doesn't work.
...
>>> import importlib; importlib.reload(t)
<module 'test' from '~/test.py'>
>>>
>>> t.plus5(0)
500
>>> #Now it works !
...
>>>
As you can see, even after changing function body to return x + 500, it still generated a result of 5 for t.plus5(0), even importing test module again did not help. It only started working when importlib was used to reload test module.

Python interpreter not working with imported modules?

Ok. So I have a bunch of functions I wrote out in my text editor under functions.py
When I import functions.py into my python interpreter, it tells me that everything I have saved under my functions.py file is not defined.
for example, I have a variable in functions.py called color.
color = "Red"
When I go to print out color in my interpreter, it says that "color is not defined."
Why is it that my interpreter is not remembering my functions or my variables, even though I was able to import the file?
Did you do it like this?:
> cat functions.py
colors = 'red'
> python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from functions import *
>>> colors
'red'
>>>
First, lunch the interpreter in the same folder of your script then you have to way to call color
1
import functions
print functions.color
2
from functions import color
print color
for both you get printed color value
I found the problem. The following code would have worked if 'color' was not inside a class.
import functions
print functions.color
But because the variable color was inside a class named 'colors' I had to also define 'colors' for the interpreter to pick it up.
import functions
print functions.colors.color
Red

Python 2.7 print() error

I have a strange error using sep, file, (etc.) arguments of python's print() function.
I tried to google it out, dag around stackoverflow, and read python's documentation but I came up with nothing.
I have attached a simple snippet, I would deeply appreciate any help.
# python
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("blah"*10, sep=" | ")
File "<stdin>", line 1
print("blah"*10, sep=" | ")
^
SyntaxError: invalid syntax
Try:
from __future__ import print_function
first
In the 2.x series, print is a statement, while in 3.x it's a function. If you want in 2.6+ to have print as a function, you use from __future__ import print_function as the first import statement.
Expect code to break though
The print function is specific to Python 3.
You have two solutions here:
Write
from __future__ import print_function
so you can use it as specified by cdarke.
Or you use print as a simple statement as it should be with older versions of Python (print "Hello World").

How do I pickle an object?

Here is the code I have:
import pickle
alist = ['here', 'there']
c = open('config.pck', 'w')
pickle.dump(alist, c)
and this is the error I receive:
Traceback (most recent call last):
File "C:\pickle.py", line 1, in ?
import pickle
File "C:\pickle.py", line 6, in ?
pickle.dump(alist, c)
AttributeError: 'module' object has no attribute 'dump'
whats going on? I am using python 2.4 on windows xp
Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.
The code you have works fine for me.
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>
>>> alist = ['here', 'there']
>>> c = open('config.pck', 'w')
>>>
>>> pickle.dump(alist, c)
>>>
The issue is that your filename "pickle.py" is making the import pickle statement try to import from your own file instead of the main library. Rename your code file.
Your script is called pickle and therefore shadows the module picke from the standard library. It imports itself and tries to call its dump function (and of course it doesn't have one).
Note that you're "lucky" that you don't get kicked into an infinite import loop (because importing the same module twice just creates another reference to the same module object in memory).

Categories