How to Import python package from another directory?

You can add the parent directory to PYTHONPATH, in order to achieve that, you can use OS depending path in the “module search path” which is listed in sys.path. So you can easily add the parent directory like following: import sys sys.path.insert(0, ‘..’) from instance import config Note that the previous code uses a relative … Read more

How is the __name__ variable in a Python module defined?

It is set to the absolute name of the module as imported. If you imported it as foo.bar, then __name__ is set to ‘foo.bar’. The name is determined in the import.c module, but because that module handles various different types of imports (including zip imports, bytecode-only imports and extension modules) there are several code paths … Read more

Import a module with parameter in python

there are various approaches to do so, here is just a silly and simple one: main.py “””A silly example – main supplies a parameter “”” import sys,os print os.path.basename(__file__)+”:Push it by: –myModuleParam “+str(123) sys.argv.append(‘–myModuleParam’) sys.argv.append(123) import module print os.path.basename(__file__)+”:Pushed my param:”+str(module.displayMyParam) module.py “””A silly example – module consumes parameter “”” import sys,os displayMyParam = ‘NotYetInitialized’ … Read more

How to move all modules to new version of Python (from 3.6 to 3.7)

Even if the old python version has been removed, it is possible to use the pip of the current python version with the –path option to list all the modules installed in the previous version. For example, migrating all my user installed python modules from 3.7 to 3.8 pip freeze –path ~/.local/lib/python3.7/site-packages > requirements.txt pip … Read more

Python calling a module that uses argparser

The first argument to parse_args is a list of arguments. By default it’s None which means use sys.argv. So you can arrange your script like this: import argparse as ap def main(raw_args=None): parser = ap.ArgumentParser( description=’Gathers parameters.’) parser.add_argument(‘-f’, metavar=”–file”, type=ap.FileType(‘r’), action=’store’, dest=”file”, required=True, help=’Path to json parameter file’) parser.add_argument(‘-t’, metavar=”–type”, type=str, action=’store’, dest=”type”, required=True, help=’Type … Read more

How do I extend a python module? Adding new functionality to the `python-twitter` package

A few ways. The easy way: Don’t extend the module, extend the classes. exttwitter.py import twitter class Api(twitter.Api): pass # override/add any functions here. Downside : Every class in twitter must be in exttwitter.py, even if it’s just a stub (as above) A harder (possibly un-pythonic) way: Import * from python-twitter into a module that … Read more