Does python optimize modules when they are imported multiple times?

Python modules could be considered as singletons… no matter how many times you import them they get initialized only once, so it’s better to do: import MyLib import ReallyBigLib Relevant documentation on the import statement: https://docs.python.org/2/reference/simple_stmts.html#the-import-statement Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages …

Read more

Reading a file using a relative path in a Python project

Relative paths are relative to current working directory. If you do not want your path to be relative, it must be absolute. But there is an often used trick to build an absolute path from current script: use its __file__ special attribute: from pathlib import Path path = Path(__file__).parent / “../data/test.csv” with path.open() as f: …

Read more

Import a Python module into a Jinja template?

Within the template, no, you cannot import python code. The way to do this is to register the function as a jinja2 custom filter, like this: In your python file: from dates.format import timesince environment = jinja2.Environment(whatever) environment.filters[‘timesince’] = timesince # render template here In your template: {% macro time(mytime) %} <a title=”{{ mytime }}”>{{ …

Read more

How does python find a module file if the import statement only contains the filename?

http://docs.python.org/3/tutorial/modules.html#the-module-search-path 6.1.2. The Module Search Path When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations: The directory containing the …

Read more

How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?

“I’d like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so.” Isn’t that what a README file is for? Here’s your alternative. A “wrapper”: a little blob of Python that checks the environment before running your target aop. File: …

Read more