Test.py:
def test():
print("Hello World")
test()
When I run this using the interpreter (ctrl+shift+p > Python: Select Interpreter > target interpreter), it works.
If I then try to run the repl (ctrl+shift+p > Python: Start REPL), I see the repl started in the terminal:
PS C:\Development\personal\python\GettingStarted> & c:/Development/personal/python/GettingStarted/.venv/Scripts/python.exe
Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
However, if I try to execute the defined method in the repl, I get an undefined error:
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
Correct way #1 to import and use:
>>> import test
Hello World
>>> test.test()
Hello World
Correct way #2 to import and use:
>>> from test import test
Hello World
>>> test()
Hello World
If you get an ImportError for both ways above, then you are running the Python REPL from the wrong directory.
It's a bit confusing that the filename and function name are the same.
Also it's a bit unusual that there is a call to test() at the end of the file (causing the function to be called at import time). Typically it's wrapped like if __name__ == '__main__': test() to avoid the call at import time, but make the call when run as a script from the command-line.
Import test doesn't work, because Python keywords are lowercase and case sensitive.
from test import Test doesn't work, because Python identifiers (e.g. function names) are case sensitive.
import Test may work on Windows (but not on macOS, Linux and many other operating systems), because filenames on Windows are case insensitive.
import test.py doesn't work, because it's not allowed to have the .py extension as part of the import module name.
import test from test doesn't work, because from ... must come before import ....
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.
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.
This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
Closed 5 years ago.
I use to think both are equal until I tried this:
$python
Python 2.7.13 (default, Dec 17 2016, 23:03:43)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> root=Tk()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Tk' is not defined
>>> from Tkinter import *
>>> root=Tk()
So what's the core difference between these 2 kinds of import that import everything from a module?
Thanks.
when you import x , it binds the name x to x object , It doesn't give you the direct access to any object that is your module, If you want access any object you need to specify like this
x.myfunction()
On the other side when you import using from x import * , It brings all the functionalities into your module, so instead of x.myfunction() you can access it directly
myfunction ()
for example lets suppose we have module example.py
def myfunction ():
print "foo"
Now we have the main script main.py , which make use of this module .
if you use simple import then you need to call myfunction() like this
import example
example.myfucntion()
if you use from, you dont need to use module name to refer function , you can call directly like this
from example import myfunction
myfunction()
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'