Create an additional package without saving the global package

I am working on a Python project where I need to communicate with the Jira API. I want to use the "official" Jira Python client available here .

The package introduces a global namespace jira

, which means you must

from jira import JIRA

      

to use the API.

How to create a subpackage

company.project.datasources.jira

      

without shadowing the global package jira

?


Let me add a few steps to reproduce my problem and show what I mean:

This is my directory layout:

.
├── company
│   ├── __init__.py
│   └── project
│       ├── datasources
│       │   ├── __init__.py
│       │   └── jira.py
│       └── __init__.py
└── test.py

      

company / project / data sources / jira.py

# This should be the global class. I don't know how to import it
from jira import JIRA as BaseJira

class JIRA(BaseJira):
    # Add something fancy here
    pass

      

test.py

from company.project.datasources.jira import JIRA

custom_jira = JIRA()

      

When I try:

python test.py

      

I am getting the following error:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    from company.project.datasources.jira import JIRA
  File "/tmp/test/company/project/datasources/jira.py", line 2, in <module>
    from jira import JIRA as BaseJira
ImportError: cannot import name JIRA

      

__init__.py

All files are currently empty. I tried a lot with them but it didn't work for me. These files are probably the key to my problem?

+3


source to share


1 answer


You are using Python 2 which has some problems with how it allows imports. It thinks it jira

refers to a module jira

relative to the current module (in which case they refer to the same thing, but this will also happen if you also tried to do this import from another module next to jira.py

).

You need to enable Python 3 import behavior. Add the following import before anything else in jira.py

(or anything else at the same level as the hidden package):

from __future__ import absolute_import

      



See PEP 328 for more information . The theses describe a common problem:

Imports can be ambiguous in the face of packages; in a package it is not clear whether it refers import foo

to a module within a package or some module outside a package. (More precisely, a local module or package might obscure another hanging directly sys.path

.)

All imports are expected to be absolute by default (search only sys.path

) with special syntax (leading points) for accessing batch-relative imports.

+4


source







All Articles