Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declaration in python to have a readable and clean code?

Is it possible to declare functions in python and define them later or in a separate file?

I have some code like:

class tata:
   def method1(self):
      def func1():
         #  This local function will be only used in method1, so there is no use to
         # define it outside.
         #  Some code for func1.
      # Some code for method1.

The problem is that the code becomes messy and difficult to read. So I wonder if it's possible for instance to declare func1 inside method1 and define it later?

like image 494
banx Avatar asked Oct 15 '10 22:10

banx


People also ask

How do you use the Clear function in Python?

You can simply “cls” to clear the screen in windows.


3 Answers

Sure, no problem:

foo.py:

def func1():
    pass

script.py:

import foo
class tata:
   def method1(self):
      func1=foo.func1
like image 166
unutbu Avatar answered Nov 01 '22 23:11

unutbu


I think what you want is to import the function within method1, e.g.

def method1(...):
    from module_where_func1_is_defined import func1
    # do stuff
    something = func1(stuff, more_stuff)
    # do more stuff

Python modules are basically just files; as long as the file module_where_func1_is_defined.py is in the same directory as your script, method1 will be able to import it.

If you want to be able to customize the way method1 works, and also make it even more clear that it uses func1, you can pass func1 to method1 as a default parameter:

import other_module

# various codes

def method1(other_args, func=other_module.func1)
    # do stuff
    something = func(stuff, more_stuff)
    # do more stuff
like image 21
intuited Avatar answered Nov 02 '22 00:11

intuited


If func1() needs to handle anything contained in the scope of method1() you're best leaving func1()'s definition there. You'll have to have func1() receive any pertinent data as parameters if it's not defined within the scope of method1()

like image 2
Ishpeck Avatar answered Nov 01 '22 22:11

Ishpeck