Function files in python

Adding functions from other files to a Python class

When I execute main.py it successfully prints the method test from index.py but what I am trying to do is figure out a way where I can just create a file in the lib folder where that while has only one function in the format

class User(object): def newFunction(self): return abc 

and this function should automatically be available for me in main.py I am sure that this is not a hard thing to do but I honestly don’t know what I want (what to search for to solve this) which is preventing me from researching the solution.

3 Answers 3

You can use a metaclass to customize class creation and add functions defined elsewhere:

import types import os import os.path import imp class PluginMeta(type): def __new__(cls, name, bases, dct): modules = [imp.load_source(filename, os.path.join(dct['plugindir'], filename)) for filename in os.listdir(dct['plugindir']) if filename.endswith('.py')] for module in modules: for name in dir(module): function = getattr(module, name) if isinstance(function, types.FunctionType): dct[function.__name__] = function return type.__new__(cls, name, bases, dct) class User(metaclass=PluginMeta): plugindir = "path/to/the/plugindir" def foo(self): print "foo" user = User() print dir(user) 

Then in the plugin files, just create functions not classes:

def newFunction(self, abc): self.abc = abc return self.abc 

And the metaclass will find them, turn them into methods, and attach them to your class.

Читайте также:  Нижние панель на css

Hello, It’s giving me this error dct[function.__name__] = types.MethodType(function) TypeError: Error when calling the metaclass bases instancemethod expected at least 2 arguments, got 1

Thanks a lot for that. The code works in terms of adding functions for the directory but I am having troubles accesing them. In this case, I cant seem to call self.foo() in any of the files. The error I get is PluginMeta has no attribute foo . Shouldnt that be User() ?

@Kartik I’m not sure what you mean. The only place you can use self is inside an instance method — either inside an instance method on User , or inside one of the plugin functions that PluginMeta is turning into instance methods for you. You can’t call self.foo() anywhere else, and there shouldn’t be any other code in the plugin files.

@Kartik OK, gotcha. My mistake. It was the same line again — the call to MethodType is totally wrong; I was confused. I fixed the code above, but just chage that line to dct[function.__name__] = function and you should be fine.

Classes are objects, and methods are nothing more than attributes on class-objects.

So if you want to add a method to an existing class, outside the original class block, all that is is the problem of adding an attribute to an object, which I would hope you know how to do:

class User(object): pass def newFunction(self): return 'foo' User.newFunction = newFunction 

agf’s metaclass answer is basically a nifty automatic way of doing this, although it works by adding extra definitions to the class block before the class is created, rather than adding extra attributes to the class object afterwards.

That should be basically all you need to develop a framework in which things defined in one module are automatically added to a class defined elsewhere. But you still need to make a number of design decisions, such as:

  1. If your externally-defined functions need auxiliary definitions, how do you determine what’s supposed to get added to the class and what was just a dependency?
  2. If you have more than one class you’re extending this way, how do you determine what goes in which class?
  3. At what point(s) in your program does the auto-extension happen?
  4. Do you want to say in your class «this class has extensions defined elsewhere», or say in your extensions «this is an extension to a class defined elsewhere», or neither and somewhere bind extensions to classes externally from both?
  5. Do you need to be able to have multiple versions of the «same» class with different extensions active at the same time?

A metaclass such as proposed by agf can be a very good way of implementing this sort of framework, because it lets you put all the complex code in one place while still «tagging» every class that doesn’t work the way classes normally work. It does fix the answers to some of the questions I posed above, though.

Источник

Importing Function From a File in Python

The process of importing a function from a file in Python is similar to importing modules. You have to create two files. Next, insert the definition of the function in one file and call the function from another.

Create a file with a function

Name the new file myfile.py and insert a function.

Create the second file, in the same directory, let’s call it main.py, import the file and make a function call.

This code will generate the following message.

my_function works. Message: Hello World!

Another way to import

Let’s import a file and call a function a bit differently. Instead of using import myfile, we use from myfile import *.

Now, you can call a function, without using the file name at the beginning of it.

This way, the program will import all functions inside the file. In our case, there is only one function.

Import file from another location

Python 3.3+

If the file where you want to call a function is in a different location than the file you want to import, you have to use the SourceFileLoader class.

I have my second file called myfile2.py at this location: D:/myfile2.py.

The modified main.py file looks like this:

The class SourceFileLoader takes a path and loads a module using the load_module function. This module is assigned to the mymodule variable.

After you run the code, you will get this message.

my_function2 works. Message: Hello World!

Python 3.5+

You can also import a file using the util module.

Источник

SOLVED: Calling a function from another file in Python

Different methods for calling a function from another file in Python

When we wish to call a function from another file in Python, we have different scenarios to achieve our goal.

  • Calling a function from another file
  • Calling a function containing arguments from another python file
  • Calling a function present in a file with a different directory
  • Importing all functions from another Python file
  • Calling a function without using the import function

Example-1: Calling a function from another file

In this scenario, we are calling a function from another file. Let us take a compute.py file having a function interest to compute the simple interest of given principal and duration. We will then write a demo.py file that has saving function, which when called makes call to interest function to compute simple interest.
compute.py

# Function to compute simple interest at fixed rate of 5% def interest(): p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from compute import interest def saving(): print("Interest accrued is",interest()) saving() 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued is 100.0 

Example-2: Calling Function containing arguments from another python file

In this scenario, we are calling a function from another file but with the arguments. Let us firstly write two python files compute.py and demo.py. We will write a function interest to compute simple interest when we pass amount and number of years. The rate is fixed as 5%. Hence, the function will compute simple interest and return the amount to the calling function.
compute.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from compute import interest # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued for the principal 1000 for 2 years at the rate of 5% is 100.0 

Example-3: Calling function present in a file with a different directory

In this scenario, we are calling a function from another file in different directory. Let us save the file compute.py inside the folder bank. Whereas, demo.py is saved outside the folder bank. Hence, we are accessing the file from the module bank stored in the different directory. In this case, only the import statement requires the modification. The way function is called remains same.

bank/compute.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si 
from bank.compute import interest # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) 
Enter the principal amount 1000 Enter the number of years 2 Computing simple interest at rate of 5% Interest accrued for the principal 1000 for 2 years at the rate of 5% is 100.0 

Example-4: Importing all functions from another Python file

In this scenario, Let us take the compute.py file but with one more function added to compute compound interest. Here, we will import all the functions present in compute.py file. The compute.py contains two functions to compute simple interest and compound interest. We will then make a call to a function demo.py file.

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 return si # Function to compute Compound interest at fixed rate of 5% def compoundinterest(p,n): print("Computing Compound interest at rate of 5%") r=5 ci=p*pow(1+r/100,n)-p return ci 
from compute import * # Get input from the user p=int(input("Enter the principal amount")) n=int(input("Enter the number of years")) # Calling a function of compute.py file with p and n as an arguments print("Simple Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",interest(p,n)) print("Compound Interest accrued for the principal",p, "for",n, "years at the rate of 5% is",compoundinterest(p,n)) 
Enter the principal amount 1000 Enter the number of years 5 Computing simple interest at rate of 5% Simple Interest accrued for the principal 1000 for 5 years at the rate of 5% is 250.0 Computing Compound interest at rate of 5% Compound Interest accrued for the principal 1000 for 5 years at the rate of 5% is 276.2815625000003 

Example-5: Call a function without using the import statement

In this scenario, we will not use import statement, rather use importlib and use the function from the file compute.py . Let us assume, our project structure is something like as shown below.
computeproject->computelib->compute.py
computeproject->demo.py

# Function to compute simple interest at fixed rate of 5% def interest(p,n): print("Computing simple interest at rate of 5%") r=5 si=(p*r*n)/100 print("Simple Interest accured for the principal",p, "for",n, "years at the rate of 5% is",si) 
import importlib from inspect import isfunction def call_func(full_module_name, func_name, *argv): module = importlib.import_module(full_module_name) for attribute_name in dir(module): attribute = getattr(module, attribute_name) if isfunction(attribute) and attribute_name == func_name: attribute(*argv) call_func('compute', 'interest', 1000,5) 
Computing simple interest at rate of 5% Interest accured for the principal 1000 for 5 years at the rate of 5% is 250.0

Summary

The knowledge of Calling a function from another file in Python is very useful while working on real and practical world applications. It helps in re-usability and data abstraction. In many situations, we will need to call a function that is used in many other files of a project and is lying in some common functionality file. In this tutorial, we covered the different scenario to call a function lying in another file and directory with an example. All in all, this tutorial, covers everything that you need to know in order to understand calling a function from another file in Python.

Источник

Оцените статью