How to import functions from other projects in Python?

Ideally both projects will be an installable python package, replete with __init__.py and setup.py. They could then be installed with python setup.py install or similar. If that is not possible, don’t use execfile()! Manipulate the PYTHONPATH to add Foo so that import Project1.file1 works. For example, from Project2/fileX.py: from os import path import sys sys.path.append(path.abspath(‘../Foo’)) … Read more

ES6 – declare a prototype method on a class with an import statement

You can still attach a method on a class‘ prototype; after-all, classes are just syntactic sugar over a “functional object”, which is the old way of using a function to construct objects. Since you want to use ES6, I’ll use an ES6 import. Minimal effort, using the prototype: import getColor from ‘path/to/module’; class Car { … Read more

How to reference python package when filename contains a period

Actually, you can import a module with an invalid name. But you’ll need to use imp for that, e.g. assuming file is named models.admin.py, you could do import imp with open(‘models.admin.py’, ‘rb’) as fp: models_admin = imp.load_module( ‘models_admin’, fp, ‘models.admin.py’, (‘.py’, ‘rb’, imp.PY_SOURCE) ) But read the docs on imp.find_module and imp.load_module before you start … Read more

using variable in import command

Use importlib module if you want to import modules based on a string: >>> import importlib >>> os = importlib.import_module(‘os’) >>> os <module ‘os’ from ‘/usr/lib/python2.7/os.pyc’> When you do something like this: >>> k = ‘os’ >>> import k then Python still looks for file named k.py, k.pyc etc not os.py as you intended.