Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use python file/function across multiple local projects

Tags:

python

I have multiple python projects and each of them has a utility file, all of them with the same functions.

How can I set up some sort of local python library which I can import to all my local projects? I know rodeo has some functionality that you can use to designate some functions/files to be available across multiple python projects. Is there a way to do that outside of rodeo?

I do not want to create a library that is available through pip (since that would mean exposing it to everyone)

like image 451
user308827 Avatar asked May 16 '16 03:05

user308827


People also ask

How do you call a function from another directory in python?

First make utils_dir as python package: simply add init.py in the directory. b). Then, add path of parent folder of utils_dir to PYTHONPATH environment variable. You can add this line into your .

How do I run a project from another project in python?

You take the code you want to use in both projects, and you put it into a module, which you extract into a third separate project. That project you make into a package, which you can work on separately. You then release version of it, and reuse them in your other projects.

Can python functions be external files?

User-defined functions can be called from other files. A function can be called and run in a different file than the file where the function is defined.


2 Answers

You can create a local python library by creating a python package. It is as easy as putting a file named: __init__.py, into your utils lib.

You can read here more about the concept of creating a python packages

And here about how to write a good __init__.py

To finish, I just need to mention the PYTHONPATH, and an almost similar question about importing from a parent directory

Hope it was helpful for you.

like image 125
Kings85 Avatar answered Nov 16 '22 10:11

Kings85


If you're using PyCharm, you can add directory with local utils to project as "content root":

File -> Settings -> Project -> Project Structure -> Add content root

After that your utils would be available in project even if they're placed somewhere else.

If you're not using PyCharm you would need somehow add your external files to project's path. For example, dynamically.

like image 3
Mikhail Gerasimov Avatar answered Nov 16 '22 11:11

Mikhail Gerasimov