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.
In my project, I am trying to share a global variable across modules as described in the Python documentation: https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules
I seemed to find, however, that the global variable is instantiated twice and I am not sure why. I want the variable to be a singleton.
I was able to reproduce the issue with this minimal example:
# main.py
class TheClass:
def __init__(self):
print("init TheClass")
def do_work(self):
import worker
worker.do_work()
the_class:TheClass = TheClass()
if __name__ == '__main__':
the_class.do_work()
# worker.py
from main import the_class
def do_work():
print("doing work...")
Output of python main.py:
init TheClass
init TheClass
doing work...
'init TheClass' is logged twice which implies that the class was instantiated twice.
I was unable to reproduce this behaviour in the interactive Python shell:
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import main
init TheClass
>>> main.the_class.do_work()
doing work...
>>>
How do I fix this undesired behaviour?
This happens because you are having a circular import and because of something special that happens with the codefile that you are actually starting.
If you start a file (as the argument to python) it will become the __main__ module independent of its filename. If at a later point in time the same file is imported, it is not recognized as already imported and is reimported under its real name, main in your case. This is why the code is run twice. A third import will not rerun the code.
You can fix it by preventing circular imports (don't put stuff to import into the starter), or by putting the code that should not run twice into the name checking if you already have.
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'