473,568 Members | 2,905 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

relative import broken?

Are relative imports broken in 2.5?
Directory ``temp`` contains::

__init__.py
test1.py
test2.py

File contents:
__init__.py and test2.py are empty
test1.py contains a single line::

from . import test2

Python 2.5.1 under Win2000, cmd line execution,
produces as output::

Traceback (most recent call last):
File "F:\temp\test1. py", line 1, in <module>
from . import test2
ValueError: Attempted relative import in non-package

Why?

Thanks,
Alan Isaac
Apr 28 '07 #1
12 2715
Alan Isaac <ai****@america n.eduwrote:
Are relative imports broken in 2.5?
Directory ``temp`` contains::

__init__.py
test1.py
test2.py

File contents:
__init__.py and test2.py are empty
test1.py contains a single line::

from . import test2

Python 2.5.1 under Win2000, cmd line execution,
produces as output::

Traceback (most recent call last):
File "F:\temp\test1. py", line 1, in <module>
from . import test2
ValueError: Attempted relative import in non-package

Why?
If you're running test1.py as your main module, then it's not part of a
package, so the relative import should indeed fail as you mention.
OTOH, something like:

$ python -c'from temp import test1'

from the parent directory of temp should work fine. Since you don't
give us the exact command line you're trying to execute, it's impossible
to guess exactly what you're doing.
Alex
Apr 28 '07 #2
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
If you're running test1.py as your main module, then it's not part of a
package, so the relative import should indeed fail as you mention.
So if I understand you,
in a package, any module that I wish
to make available for execution as a script
(in the usual way, with a main function)
cannot have any relative imports.
Is this right? What is the reason for
this restriction? (And where is it
documented?)

Thank you,
Alan Isaac
Apr 29 '07 #3
Alan Isaac <ai****@america n.eduwrote:
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
If you're running test1.py as your main module, then it's not part of a
package, so the relative import should indeed fail as you mention.

So if I understand you,
in a package, any module that I wish
to make available for execution as a script
(in the usual way, with a main function)
cannot have any relative imports.
Is this right? What is the reason for
this restriction? (And where is it
documented?)
The most up-to-date documentation for import and from statements is at
<http://docs.python.org/dev/ref/import.htmlbut it's still somewhat
incomplete -- it gives the grammar for relative imports, but does not
explain its semantics, nor, for that matter, any of the semantics of
pakages. The discussions about relative imports in particular are
recorded as PEP 328, while an old essay about the semantics of packages
is recorded at a link give on the docs page I mentioned.

Very simply, PEP 328 explains:
"""
Relative Imports and __name__

Relative imports use a module's __name__ attribute to determine that
module's position in the package hierarchy. If the module's name does
not contain any package information (e.g. it is set to '__main__') then
relative imports are resolved as if the module were a top level module,
regardless of where the module is actually located on the file system.
"""
and points to four discussion threads on python-dev which, after much
give and take, led to Guido picking these semantics.

To me, it makes sense: if a module is top-level, and thus not part of a
package (and __main__ in particular is always in that state), then
saying "import from the current package" has no well defined meaning,
because there IS no "current package". Using __name__ rather than
__file__, in turn, makes a lot of sense, because a package's _logical_
structure is defined by its __path__, and need not coincide with any
_physical_ arrangement of directories.

If you have a better and sharper idea about how relative imports should
work in toplevel modules (those whose __name__ indicates they have NOT
been imported as part of a package, including __main__), feel free to
make a case for it on python-dev (python-list is fine for preliminary
discussions and brainstorming, but nothing will happen about any idea
until and unless it's taken to python-dev, survives the scathing barrage
of objections that strongly characterizes that mailing list, and finally
manages to convince Guido:-).
Alex
Apr 30 '07 #4
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** **@mac.com...
To me, it makes sense: if a module is top-level, and thus not part of a
package (and __main__ in particular is always in that state), then
saying "import from the current package" has no well defined meaning,
because there IS no "current package".
Thanks for the explanations.
I do not have an opinion because I have not really thought this through.

One of the things I was hoping for, however, was for a less hackish way
for scripts bundled with a package to access the package modules.

That is, suppose I have directory ``mypackage`` with subdirectory
``scripts``.
What is the pretty way for the scripts to access ``mypackage`` without
assuming ``mypackage`` is in ``sys.path``?

Thanks,
Alan Isaac
Apr 30 '07 #5
Alan Isaac <ai****@america n.eduwrote:
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** **@mac.com...
To me, it makes sense: if a module is top-level, and thus not part of a
package (and __main__ in particular is always in that state), then
saying "import from the current package" has no well defined meaning,
because there IS no "current package".

Thanks for the explanations.
I do not have an opinion because I have not really thought this through.

One of the things I was hoping for, however, was for a less hackish way
for scripts bundled with a package to access the package modules.

That is, suppose I have directory ``mypackage`` with subdirectory
``scripts``.
What is the pretty way for the scripts to access ``mypackage`` without
assuming ``mypackage`` is in ``sys.path``?
I don't know of any "pretty" way -- I'd do it by path manipulation
(finding mypackage from os.path.abspath (__file__) and inserting its
_parent_ directory in sys.path).
Alex
May 1 '07 #6
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
I don't know of any "pretty" way -- I'd do it by path manipulation
(finding mypackage from os.path.abspath (__file__) and inserting its
_parent_ directory in sys.path).

Yes, that seems to be the standard solution.
I find it ugly. Anyway, I suppose my question remains:
why are we constrained from solving this with
a relative import? (And I suppose your answer will be:
well then, relative to *what*? I am having trouble
seeing why that answer cannot be given a clear riposte.)

Thanks,
Alan
May 1 '07 #7
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
I don't know of any "pretty" way -- I'd do it by path manipulation
(finding mypackage from os.path.abspath (__file__) and inserting its
_parent_ directory in sys.path).
"Alan Isaac" <ai****@america n.eduwrote in message
news:7nNZh.4420 $st3.1414@trndd c06...
Yes, that seems to be the standard solution.
I find it ugly.
Just to confirm that I am right to find it ugly:
does this not clearly introduce the possibility of name clashes?
Or am I overlooking some trick?

Alan Isaac
May 2 '07 #8
Alan Isaac <ai****@america n.eduwrote:
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
I don't know of any "pretty" way -- I'd do it by path manipulation
(finding mypackage from os.path.abspath (__file__) and inserting its
_parent_ directory in sys.path).


Yes, that seems to be the standard solution.
I find it ugly. Anyway, I suppose my question remains:
why are we constrained from solving this with
a relative import? (And I suppose your answer will be:
well then, relative to *what*? I am having trouble
seeing why that answer cannot be given a clear riposte.)
So what do you think the answer should be?

Alex
May 2 '07 #9
Alan Isaac <ai****@america n.eduwrote:
"Alex Martelli" <al***@mac.comw rote in message
news:1h******** *************** ***@mac.com...
I don't know of any "pretty" way -- I'd do it by path manipulation
(finding mypackage from os.path.abspath (__file__) and inserting its
_parent_ directory in sys.path).

"Alan Isaac" <ai****@america n.eduwrote in message
news:7nNZh.4420 $st3.1414@trndd c06...
Yes, that seems to be the standard solution.
I find it ugly.

Just to confirm that I am right to find it ugly:
does this not clearly introduce the possibility of name clashes?
Or am I overlooking some trick?
If you use sys.path.insert (0, ...), not sys.path.append , I'm not sure
what "name clashes" you're thinking of -- as long as you avoid naming
your modules the same as ones in the standard library (which is a good
practice I heartily recommend), of course, what scenario do you fear?

You can have more control about _where_ stuff can get imported from by
directly calling the __import__ builtin, but that's not often needed.
Alex
May 2 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1578
by: Rutger Claes | last post by:
In the directory /var/www/dynamo/xsl is the basic xsl file for xhtml documents /var/www/dynamo/xsl/xhtml.xsl. In this file there is an import statement: <xsl:import href="xhtml/basic.xhtml.xsl" />. This import statement should load /var/www/dynamo/xsl/xhtml/basic.xhtml.xsl as far as I know. The current document is...
0
1445
by: Anders J. Munch | last post by:
Now 2.5 is out, and we have a syntax for explicit relative imports (PEP 328, http://www.python.org/dev/peps/pep-0328/, in case anyone wasn't paying attention). The long-term plan is that the classical import syntax becomes absolute import only, so that all imports are explicitly one or the other. You can only use relative import from...
1
5680
by: Alexey Borzenkov | last post by:
After reading PEP-0328 I wanted to give relative imports a try: # somepkg/__init__.py <empty> # somepkg/test1.py from __future__ import absolute_import from . import test2 if __name__ == "__main__":
0
1331
by: Alan Isaac | last post by:
What is the recommended packaging of demo scripts or test scripts for a package that has modules that use relative imports? Example: Suppose I have the package structure: package/ __init__.py subpackage1/
0
1382
by: Kay Schluehr | last post by:
Since their introduction in Python 2.5 I only reviewed the new "relative import" notation briefly by reading the "What's new in Python 2.5" article. Now I wanted checkout if I get comfortable with them. Opening the tutorial I found following notice ( 6.4.2 ): "Note that both explicit and implicit relative imports are based on the name of...
10
194
by: test | last post by:
basic noob question here. i am trying to reference a package, i have the structure: mypack/ __init__.py test.py subdir1/ __init__.py mod1.py
4
1821
by: DG | last post by:
Alright, I have searched and searched and read many conversations on the topic of relative and absolute imports and am still not getting the whole thing through my skull. Highlights of what I've read: http://mail.python.org/pipermail/python-list/2007-January/422973.html...
0
1201
by: Stef Mientki | last post by:
hello, I'm running Python 2.5 and want my programs to run at least under Windows and Linux (preferable also Mac). So I guess I should always use relative paths. From most modules I can call a global function, that should import a dictionary from path deeper than the module itself. The import is done in the global function. In that...
0
1479
by: Gabriel Genellina | last post by:
En Sat, 18 Oct 2008 05:52:04 -0300, Stef Mientki <stef.mientki@gmail.com> escribió: Why don't you let the caller tell you its own location, using __file__? The above code is too much magic for me. Yes.
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
1
7665
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5501
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3651
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3631
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.