Page 1 of 1

What does "from . import *" mean.

Posted: Sun Feb 10, 2019 6:39 pm
by Grumpy Mike
The title says it all. I found this in some code that talks to a Bluetooth device but I have failed to find what it means.
I get the "import *" bit, I understand this to mean import all of the module, but what does the period mean? What is being used to import everything from?

Re: What does "from . import *" mean.

Posted: Sun Feb 10, 2019 7:47 pm
by gordon77
A Google shows it's relative, see guido's decision in this link...

https://www.python.org/dev/peps/pep-0328/

Re: What does "from . import *" mean.

Posted: Sun Feb 10, 2019 7:49 pm
by hippy
The "from ." means relative to where what contains that was imported from.

https://realpython.com/absolute-vs-rela ... on-imports

Re: What does "from . import *" mean.

Posted: Sun Feb 10, 2019 8:46 pm
by scruss
If you specify a name (say foo)

Code: Select all

from foo import *
Python will go off looking in $PYTHONPATH for foo.py, and import all of its methods when it is found.
If you specific a path, such as . for the current working directory, Python will read all of the *.py files in that directory and import their methods.

It's a little confusing.

Re: What does "from . import *" mean.

Posted: Sun Feb 10, 2019 9:56 pm
by Idahowalker
Take the threading class it has several subclasses; such as thread, Queue, and a few others.

If the threading class was imported all the subclasses are loaded but you may only want to use one of the subclasses, can shave off a bit of ram, or you want to use your own name to reference a sub class.

Something along the lines of just importing the thread class, say import threading as t, and you want to use the Queue you'd write t.Queue.blah. If you named the Queue class you can then import t as threading and q as t.Queue so then you'd only have to reference any calls to the methods and properties of the Queue class as q.blahblahblah instead of t.Queue.blahblahblah.

Re: What does "from . import *" mean.

Posted: Mon Feb 11, 2019 3:49 am
by Grumpy Mike
Thanks guys,
The email notification dosn't seem to be working so sorry for the delay.
Yes it does seem a bit confusing, I did read one post where it was advised never to use it.

Just to clear up a point ( pun intended ) is the current directory set automatically to the place where IDLE3 is running the file from or do I have to set it using cd from the terminal window? It is just that the example code that comes with a libiary I am looking at uses this form of import and simply dosn't work.

Thanks again

Re: What does "from . import *" mean.

Posted: Wed Feb 20, 2019 11:50 am
by Grumpy Mike
with the code:-

Code: Select all

from pylgbst.peripherals import ColorDistanceSensor
from . import *
I get the error message

Code: Select all

from . import *
SystemError: Parent module '' not loaded, cannot perform relative import
This is example code from the libiary so it is supposed to work. Any ideas?