How to include external Python code to use in other files? - python

If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?
So if I have:
[Math.py]
def Calculate ( num )
How do I call it like this:
[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )

You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

Just write the "include" command :
import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
#Deleet :
#bfieck remark is correct, for python 2 and 3 compatibility, you need either :
Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))

If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.

I've found the python inspect module to be very useful
For example with teststuff.py
import inspect
def dostuff():
return __name__
DOSTUFF_SOURCE = inspect.getsource(dostuff)
if __name__ == "__main__":
dostuff()
And from the another script or the python console
import teststuff
exec(DOSTUFF_SOURCE)
dostuff()
And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

It's easy and simple:
you can just do this:
def run_file(path):
return exec(open(path).read());
run_file("myfile.py");

I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5.
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
I prefer Alternative #2 and have been using it in my website development.

Related

Header files in python

How do I create a header file in python ?
I know the steps to do it in C++ but I don't know how to do it in python.
You can do something like this:
create a new python file (e.g.: pseudo_header) here you can add function, variables etc.
Example - in pseudo_header:
name = "Bob"
in your main.py do this:
import pseudo_header
print(pseudo_header.name) << "Bob"
pseudo_header.name = "John"
print(pseudo_header.name) << "John"
Python is not having header files like c++. Instead we import libraries here.
For example take below small piece of code.
import datetime
print datetime.datetime.now()
Output
2019-11-15 12:33:33.177000
Here we are importing library datetime. datetime.datetime.now() will give you the current date.
You can also import only a specific object instead of whole module. Like below.
from datetime import datetime
print datetime.now()
There is no need to define anything before code in python as we did in c++.
You just know about the syntax of the python it will be enough for beginner programming.
But if you want to use some extra libraries then you will need some importing.
Example
print("Hello World")
output
>> Hello World
Similarly you can define variables, do some conditional programming or define some loops etc.
Example
a = 5
if a != 5:
print("I am angry")
if a == 5:
print("I am happy")
output
>> I am happy
See there is no need to do any importing.
But if you want to use some libraries like. DateTime
import datetime
print datetime.datetime.now()
This library deals with date and time and anythings belongs to them.
That is python :)
What I usually do is create a separate library file with all function definitions and import this in the main script.
Let's say my library is called foo.py, which contains
import numpy as np
def side(area):
'''
Function to get length of the side of a square of a given area.
'''
assert (area > 0), 'Invalid input!'
return np.sqrt(area)
Then, in my main script, I just import the library and use the functions.
import numpy as np
from foo import *
area = 100
print (side(area)) # returns 10
May not be the best way but works for me.

Python - Import module which has a different name to file?

Essentially, I have two .py files which lie in the same directory. Namely, foo_v02 and bar_v01.
In bar_v01, I want to import a class from foo_v02. However, for the sake of convenience, I want to use the statement from foo import myClass (ignoring the version number). However, as my file isn't called foo, of course python throws an error as there's no file called foo.py.
My Question: Is there a way I can just use from foo import myClass without having to rename my foo_v02.py file?
Note: I already have code which works but it uses from foo_v02 import myClass, so I'm not experiencing a problem as such. Also, I'm asking this question as my foo_xx.py file will undergo frequent editing so there will be multiple versions (so I don't want to have to edit the import statement with every new version). Also, there's only ever going to be one foo_xx.py in the directory as all the previous versions are moved to a different directory once they're outdated.
EDIT:
I've posted an answer for now, but if anyone has a better way, please feel free to post it!
I think the below code maybe works:
import glob
foo = __import__(glob.glob('foo_*.py')[0][:-3])
myClass = foo.myClass
Since the original answer got deleted...
import glob
a = glob.glob('*.py') ## Returns all of the `python` files
b = a[0]
exec('from {} import myClass'.format(b[:-3]))
I'm using exec() (instead of __import__) as I actually want to run the import statement. Also, the import isn't discarded afterwards.

Python : 'import module' vs 'import module as'

Is there any differences among the following two statements?
import os
import os as os
If so, which one is more preferred?
It is just used for simplification,like say
import random
print random.randint(1,100)
is same as:
import random as r
print r.randint(1,100)
So you can use r instead of random everytime.
The below syntax will help you in understanding the usage of using "as" keyword while importing modules
import NAMES as RENAME from MODULE searching HOW
Using this helps developer to make use of user specific name for imported modules.
Example:
import random
print random.randint(1,100)
Now I would like to introduce user specific module name for random module thus
I can rewrite the above code as
import random as myrand
print myrand.randint(1,100)
Now coming to your question; Which one is preferred?
The answer is your choice; There will be no performance impact on using "as" as part of importing modules.
Is there any differences among the following two statements?
No.
If so, which one is more preferred?
The first one (import os), because the second one does the exact same thing but is longer and repeats itself for no reason.
If you want to use name f for imported module foo, use
import foo as f
# other examples
import numpy as np
import pandas as pd
In your case, use import os
The import .... as syntax was designed to limit errors.
This syntax allows us to give a name of our choice to the package or module we are importing—theoretically this could lead to name clashes, but in practice the as syntax is used to avoid them.
Renaming is particularly useful when experimenting with different implementations of a module.
Example: if we had two modules ModA and ModB that had the same API we could write import ModA as MyMod in a program, and later on switch to using import MoB as MyMod.
In answering your question, there is no preferred syntax. It is all up to you to decide.

Is there a way to get importer's variable in importee?

Say that I have two python file
# importer.py
parameter = 4
import importee
and
# importee.py
print parameter
Can I or how can I in importee.py access importer.py's parameter?
I'm using an ugly work around, borrow (and pollute) the sys
# importer.py
import sys
sys.parameter = 4
import importee
and
# importee.py
print sys.parameter
Too ugly.
Looking for better solution.
The recommended way to achieve what I think you want to achieve is to declare function in importee, and call it, e.g.:
# importer.py
import importee
importee.call_me(4)
and:
# importee.py
def call_me(parameter):
print(parameter)
It is preferable to avoid performing any operations in global scope. And especially print()ing anything but I suppose your minimal example doesn't match your real use case :).
By the way, the ugly work around you have mentioned is practically equivalent to using a separate configuration module. For example:
# importer.py
import config
config.param = 4
import importee
+
# importee.py
import config
print(config.param)
+
# config.py
param = 7 # some default
It's still nowhere close to pretty but at least avoids mangling with system modules.

Is there an accepted way in Python to import a module from within a function?

I have written a script for XBMC which optionally downloads a dll and then imports a module that depends on that dll if the download was successful.
However, placing the import inside a function generates a Python syntax warning.
Simplified example:
1 def importIfPresent():
2 if chkFunction() is True:
3 from myOptionModule import *
Line 3 generates the warning, but doesn't stop the script. I can't place this code at the start outside of a function because I need to generate dialog boxes to prompt the download and then hash the file once it is downloaded to check success. I also call this same code at startup in order to check if the user has already downloaded the dll.
Is there a different/better way to do this without generating the syntax warning? Or should I just ignore the warning and leave it as is?
Thank you! Using the useful responses below, I now have:
import importlib
myOptionalModule = None
def importIfPresent():
if chkFunction is True:
try:
myOptionalModule = importlib.import_module('modulex')
except ImportError:
myOptionalModule = None
...
importIfPresent()
...
def laterFunction():
if myOptionalModule != None:
myParam = 'something expected'
myClass = getattr(myOptionalModule, 'importClassName')
myFunction = getattr(myClass, 'functionName')
result = myFunction(myClass(), myParam)
else:
callAlternativeMethod()
I am posting this back mainly to share with other beginners like myself the way I learned through the discussion to use the functionality of a module imported this way instead of the standard import statement. I'm sure that there are more elegant ways of doing this that the experts will share as well...
You're not getting the warning for doing an import inside a function, you're getting the warning for using from <module> import * inside a function. Doing a In Python3, this actually becomes a SyntaxError, not a SyntaxWarning. See this answer for why wildcard imports like this in general, and expecially inside functions are discouraged.
Also, this code isn't doing what you think it does. When you do an import inside a function, the import only takes affect inside the function. You're not importing that module into the global namespace of the file, which I believe is what you're really trying to do.
As suggested in another answer importlib can help you here:
try:
import myOptionModule as opt
except ImportError:
opt = None
def importIfPresent():
global opt
if chkFunction() is True:
opt = importlib.import_module("myOptionModule")
I beleive you need to use the importlib library to facilitate this.
The code would be at the top of the mod:
import importlib
then replace "from myOptionModule import *" with "module = importlib.import_module(myOptionModule)". You can then import the defs/classes you want or import them all by using getattr(module,NAME(S)TOIMPORT).
See if that works.
Check out chapter 30 and 31 of Learning Python by Lutz for more info.

Categories

Resources