Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.6, import local vs 3rd party package with same name

I have done research but I am not able to find a clear solution... How to import 3rd party package if I have a package with the same name?

Example:

Project tree looks like this:

├── Pipfile
├── Pipfile.lock
├── analytics
│   ├── __init__.py
│   └── client.py
└── main.py

Content of analytics/client.py is simple:

def identify():
    print("local analytics")

analytics/init.py is one-liner:

from .client import  identify

main.py

import analytics


analytics.identify();

If I run python main.py it will write local analytics to the output. It's ok.

However, If I install 3rd party package with name analytics, e.g.

pipenv install analytics-python (https://segment.com/docs/sources/server/python/)

and run python main.py, it will write local analytics to the output again.

How to run code from 3rd party package?

like image 292
Klik Kliković Avatar asked Sep 17 '25 04:09

Klik Kliković


1 Answers

The point here is that you are running __init__.py as a script. When you run a script, Python adds the directory containing the script to the front of sys.path, and this globally affects all subsequent imports.

So in order to work with third-party module either you have to rename your local analytics directory or remove the __init__.py file so python do not lists it in sys.path.

like image 165
Saleem Ali Avatar answered Sep 19 '25 13:09

Saleem Ali