2

Can I write a method/function in a __init__.py file? as demonstrated below

Example:

In __init__.py file

import subprocess
import config


def ssh_exe(cmd):
    try:
        ssh_cmd = "ssh root@{0} {1}".format(config.ip, cmd)
        out = subprocess.check_output(ssh_cmd)
        return out
    except Exception as e:
        return str(e)
CDspace
  • 2,639
  • 18
  • 30
  • 36
HE-MAN
  • 33
  • 5

1 Answers1

3

sure, they are normal files. Only difference is that they define that the folder is a package.

From python official basic tutorial:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Note that you usually don't put your code in __init__.py but instead define it in the packages' modules and import only the names you want to expose in the package namespace.

Here's an example on how to access then, suppose you have this directory structure:

Development/
   main.py
   setup.py
   myprogram/
       __init__.py
       other.py

The myprogram folder is considered a package because of __init__.py so in main.py you can do:

import myprogram
myprogram.something() # defined in `__init__.py`
import myprogram.other # the submodule other.py inside the package
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • Thanks for the reply. But how to access the method/function in another python file? – HE-MAN Jul 18 '18 at 16:21
  • Thanks @nosklo. I got it. – HE-MAN Jul 18 '18 at 16:31
  • It's not the only difference. `__init__.py` is automatically executed in certain circumstances. There's a fair bit to read on this https://stackoverflow.com/questions/5831148/why-would-i-put-code-in-init-py-files https://stackoverflow.com/questions/70159126/is-it-bad-practise-to-not-use-init-py-files-in-a-python-project https://stackoverflow.com/questions/448271/what-is-init-py-for – NeilG May 24 '23 at 06:30