Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to reference files within same module

Tags:

python

I'm using this code in one of my apps in Google App Engine. I encountered problems with the way that individual files are referenced. For example, in __init.py__ the files decorators.py, errors.py, etc are imported as follows:

import reddit.decorators
import reddit.errors
import reddit.helpers
import reddit.objects

Since the files are all within the same module, shouldn't they be imported like this instead:

import decorators
import errors
import helpers
import objects

The absolute reference works only if the reddit package is on the system path, which seems not to be the case in Google App Engine, for some reason.

Is this a problem with the source, or do I need to examine my application configuration within Google App Engine more closely?

like image 890
mpenkov Avatar asked Apr 09 '26 04:04

mpenkov


1 Answers

If you want to use a package, you will have to install the whole directory somewhere where Python can find it, i.e., to a directory that is in sys.path. You should never attempt to use the package contents as standalone modules, since this is not how the package is designed for.

Since the working directory of your main script (.) is in sys.path, you should be able to use the reddit package simply by putting the whole package directory within the same directory as your main script. If you cannot import reddit in Google App Engine, you will have to check your setup there. Unfortunately, I do not know how GAE works or what you are allowed to install there, but I guess it should work, since they allow you to put arbitrary Python modules and packages to your webspace, don't they?

Concerning your original question, you are refering to the wrong section of the manual. For intra-package references, you should either use absolute imports:

import reddit.decorators as decorators

or relative ones:

from . import decorators

If the absolute import syntax works depends on your Python version. This is ambiguous:

import decorators

Do you mean a global module (/decorators.py)? Or a module within the package (/reddit/decorators.py)? Python 2.x will look for a relative import first, then try an absolute import if the relative one fails. Starting with version 2.6, using absolute-style imports is deprecated and should not be used any more. Since 3.0, the statement above will only be interpreted as absolute import and not look for a relative one. Explicit absolute imports will work as expected in both versions.

like image 83
Ferdinand Beyer Avatar answered Apr 10 '26 17:04

Ferdinand Beyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!