2

I am interested how I can import function from another python script, which extension should be not .py (for example .pyf). In other words I want somehow to replace:

from Math import Calculate

to

from 'Math.pyf' import Calculate

How to do that?

chanfort
  • 125
  • 1
  • 1
  • 9
  • It should be possible but will likely involve writing a custom importer. – Simeon Visser Jun 26 '14 at 23:15
  • so, what would be this custom importer? – chanfort Jun 26 '14 at 23:15
  • 1
    You should have a look at `importlib` which allows you to customize the import behaviour: https://docs.python.org/3/library/importlib.html . It does involve upgrading to Python 3 though. – Simeon Visser Jun 26 '14 at 23:17
  • My code is using python 2.7 and I can't use python 3, as it is on remote computer and I would need to rewrite many thousands of lines of my code. There must be easier solution... – chanfort Jun 26 '14 at 23:35
  • 2
    Out of curiosity, why do you want the file you are importing to have a non-standard extension? – murgatroid99 Jun 26 '14 at 23:41
  • because in working directory I have a list of .py files, which are used to execute through bash loop. If there will be this function file named with .py extension, it will give errors when it would be executed from bash. – chanfort Jun 26 '14 at 23:48
  • 1
    `Math = eval(open("Math.pyf").read()) ` ... thats pretty sketchy though ... why not just convert them to pyc files then you can import them normally? – Joran Beasley Jun 26 '14 at 23:59
  • It complains like that:Traceback (most recent call last): File "tffvsRhoBin.py", line 9, in plott = eval(open("plotter.pyf").read()) File "", line 1 def plotter(): ^ SyntaxError: invalid syntax – chanfort Jun 27 '14 at 00:14

0 Answers0