python calling a def() inside of def()

Question:

I’m making a package for my python assistant and have found a problem.

Im importing the following program into the main script.

import os

def load() :
    def tts(name) :
        os.system("""PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(' """ + name + " ');"

how do i call the function into my program

ive tried :

import loadfile
loadfile.load().tts("petar")

and it didn’t work

Asked By: elite gamer88

||

Answers:

When you run loadfile.load().tts("petar"), it is equivalent to:

v = loadfile.load()
v.tts("petar")

Your method loadfile.load() does not return any value, so v is assigned None. Then you try to call tts() against None, which is an error.

Why are you trying to do this? Maybe you want to create a class?

Answered By: Poshi

You are never supposed to expose a sub-function outside of its scope, in this case, the tts method outside load. It’s actually imposible to access tts without exposing its reference outside of your load() method. I suggest you to rather use a class like this:

In loadfile.py:

import os

class LoadFile(object):
    def tts(self, name):
        os.system("""PowerShell -Command "Add-Type –AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak(' """ + name + " ');")

def load():
    return LoadFile()

On main code:

import loadfile
loadfile.load().tts("petar")

Answered By: Damodar Dahal

you can follow this code to call def within def

def num1(x):
   def num2(y):
      return x * y
   return num2
res = num1(10)

print(res(5))

Reference URL

Answered By: Willie Cheng

You also can use the decorator "@classmethod" to create some funcion inside your class that doesn’t need create an instance of your class.

In your "my_package.py" file you can do some like this:

class Loaders():

   @classmethod
   def load(self, parameter):
      return self.tts(parameter)

   def tts(self):
      os.system("""PowerShell...""")
      ...
      return self

In python files that will call this "my_package.py" you can code:

       filename        classname
          |                |
          V                V
from my_package import Loaders

# to use your method tts you can Instantiate your class and after call the method:
x = Loaders()
x.tts('petar')

# or you can call directly some classmethod
x = Loaders.load('petar')

If you need change the steps when initializing your class, … you can edit the instantiation method init


class Loaders():

   def __init__(self, some_param):
      ...do something...

      return self

...
# so when you when you call 
x = Loaders()

# " ... do something ..." will do and the class object (self) will return.

Answered By: Wesley Silva
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.