Calling __init__.py from another file - python

I am trying to understand how __init__py works. But I have the following question.
I have the following directory:
myfoldername/
example/
__init__.py
sayhello.py
saybye.py
main.py
Inside the __init__py file I import the sayhello.py and saybye.py files
from example.sayhello import *
from example.saybye import *
Inside the sayhello.py I have two functions:
def hello():
print('hello')
def hello_person(x):
print('hello ' + x)
Why can I not call the both functions in the sayhello.py when I import the module into a separate script main.py?
import example as ex
ex.hello() //prints 'hello'
ex.hello_person('John') //prints module 'example' has no attribute 'hello_person'

Though that shouldn't have happened. but if the issue is still there you can make use of The Zen of Python. Which says
Explicit is better than implicit.
Hence,
from example.sayhello import hello, hello_person

Related

How do you import a module that imports another module in a subfolder?

So this is my folder structure:
root
module_a
hello.py
submodule_a
hi.py
module_b
howdy.py
hello.py calls a method in hi.py. howdy.py calls a method in hello.py
This is the content of each file:
hi.py
def myhi(hi):
print("myhi " + hi)
hello.py
from submodule_a.hi import myhi
def myhello(hello):
myhi("myhello " + hello)
howdy.py
from module_a.hello import myhello
def myhowdy(howdy):
myhello("myhowdy " + howdy)
So the first issue is that howdy.py cannot find module_a, so I did sys.path.append(".") inside howdy.py.
But now the new problem is that, from howdy.py, it cannot find submodule_a from hello.py.
How do you solve this issue? Is it possible to solve it without editing hello.py at all?
I've tried messing with __init__.py but I couldn't find anything that could solve the second problem.
create a __init__.py file in module_a and module_b and submodule_a then import the functions you want to use in another directory like these:
module_a/__init__.py
from hello import myhello
from submodule_a import myhi
module_a/submodule_a/__init__.py
from hi import myhi
module_b/__init__.py
from howdy import myhowdy

Import variables from a config File

I have a script that have multiple files and a config file with all the variables store in one Python file.
Folder structure:
Config file:
If I try to run the main file which calls the head function imported, an error pops up saying that the config cannot be imported.
Imports:
Your Functions folder has a __init__.py file. If your app executes from Main.py (ie if Main.py satisfies __name__ == "__main__") therefore wherever you are in your app you could import the config like this:
from Functions.Config import *
Edit:
However,from module import * is not recommended with local import. You could give an alias to the import and call name.variable instead of calling name directly.
Example:
def head():
# import packages
import Function.Config as conf
print(conf.more_200)
head()
>>> 50
Your syntax are wrong.
It is supposed to be from Config import * and not import .Config import *

Unable to import a function from outside the current working directory

I am currently having difficulties import some functions which are located in a python file which is in the parent directory of the working directory of the main flask application script. Here's how the structure looks like
project_folder
- public
--app.py
-scripts.py
here's a replica code for app.py:
def some_function():
from scripts import func_one, func_two
func_one()
func_two()
print('done')
if __name__ == "__main__":
some_function()
scripts.py contain the function as such:
def func_one():
print('function one successfully imported')
def func_two():
print('function two successfully imported')
What is the pythonic way of importing those functions in my app.py?
Precede it with a dot so that it searches the current directory (project_folder) instead of your python path:
from .scripts import func_one, func_two
The details of relative imports are described in PEP 328
Edit: I assumed you were working with a package. Consider adding an __init__.py file.
Anyways, you can import anything in python by altering the system path:
import sys
sys.path.append("/path/to/directory")
from x import y
1.
import importlib.util
def loadbasic():
spec = importlib.util.spec_from_file_location("basic", os.path.join(os.path.split(__file__)[0], 'basic.py'))
basic = importlib.util.module_from_spec(spec)
spec.loader.exec_module(basic)
return basic #returns a module
Or create an empty file __init__.py in the directory.
And
do not pollute your path with appends.

Python importing multiple scripts

I've been working on a python script that will require multiple libraries to be imported.
At the moment my directory structure is
program/
main.py
libs/
__init__.py
dbconnect.py
library01.py
library02.py
library03.py
My dbconnect.py which has the following contents
import psycopg2
class dbconnect:
def __init__(self):
self.var_parameters = "host='localhost' dbname='devdb' user='temp' password='temp'"
def pgsql(self):
try:
var_pgsqlConn = psycopg2.connect(self.var_parameters)
except:
print("connection failed")
return var_pgsqlConn
I am able to import and use this in my main.py using
from libs.dbconnect import dbconnect
class_dbconnect = dbconnect()
var_pgsqlConn = class_dbconnect.pgsql()
This works as expected however I am trying to import all of the library scripts each which have similar contents to bellow
def library01():
print("empty for now but this is library 01")
I have added to my __init__.py script
__all__ = ["library01", "library02"]
Then in my main.py I tried to import and use them as bellow
from libs import *
library01()
I am getting the following error
TypeError: 'module' object is not callable
I'll suppose content in your library0x.py are different (the functions/class have different names)
The best way is to import all your subfiles content in the __init__.py
# __init__.py
from .dbconnect import *
from .library01 import *
from .library02 import *
from .library03 import *
Then you can use the following :
from libs import library01, library02
If you want to restrict for some reasons importation with the wildcard (*) in your library0x.py files, you can define a __all__ variable containing all the names of the function you will import with the wildcard :
# library01.py
__all__ = ["library01"]
def a_local_function():
print "Local !"
def library01():
print "My library function"
Then, by doing from .library01 import *, only the function library01 will be import.
EDIT: Maybe i missunderstand the question : here are some ways to import the function library01 in the file library01.py :
# Example 1:
from libs.library01 import library01
library01()
# Example 2:
import libs.library01
libs.library01.library01()
# Example 3:
import libs.library01 as library01
library01.library01()
In your case library01 is a module which contains a function named library01. You import the library01 module and try to call it as a function. That's the problem. You should call the function like this:
library01.library01()

Python : Cannot find any functions within my own module?

I have created my own module with filename mymodule.py. The file contains:
def testmod():
print "test module success"
I have placed this file within /Library/Python/2.7/site-packages/mymodule/mymodule.py
I have also added a __init__.py file, these have compiled to generate
__init__.pyc and mymodule.pyc
Then in the python console I import it
import mymodule
which works fine
when I try to use mymodule.testmod() I get the following error:
AttributeError: 'module' object has no attribute 'testmod'
So yeah it seems like it has no functions?
You have a package mymodule, containing a module mymodule. The function is part of the module, not the package.
Import the module:
import mymodule.mymodule
and reference the function on that:
mymodule.mymodule.testmod()
You can use from ... import and import ... as to influence what gets imported exactly:
from mymodule import mymodule
mymodule.testmod()
or
from mymodule import mymodule as nestedmodule
nestedmodule.testmod
or
from mymodule.mymodule import testmod
testmod()
etc.

Categories