Python - libraries without the import "*"

1

How do I create a library without having to import like this: from x import * or from x import y ? Only by importing import x .

Who can answer me, please use the script below as a library example.

def imprimir():
    print('Olá!')

NOTE: I want to give import nome_da_biblioteca and not have to use from nome_da_biblioteca import imprimir or from nome_da_biblioteca import * .

    
asked by anonymous 07.09.2018 / 04:33

2 answers

2

When you import the other module with import nome_da_biblioteca it is executed and its namespace is added to the current module in an object of type module with the same name as the module.

So, just use attribute access to retrieve names defined in the imported module:

import nome_da_biblioteca
nome_da_biblioteca.imprimir()

p = nome_da_biblioteca.imprimir
p()
    
07.09.2018 / 07:57
1

You can import of a file in Python using the following statements.

# foo.py

def foo():
    print("Sou foo")


# bar.py

import foo

def bar():
    print("Executando foo")
    foo.foo()

Since it is defined in the same directory I can simply make a import <nome_do_arquivo> now think of files defined in different directories, for example, we have a project defined as follows:

project/
    functions/
        __init__.py
        foo.py
    bar.py

If we wanted to import the file foo being in bar we would do it like this:

# foo.py

import functions.foo 

def bar():
    print("Executando foo")
    functions.foo.foo()

This is just an abbreviated explanation of what it is possible to do to import files into Python if you want to go even deeper, I suggest that you study: #

    

07.09.2018 / 05:10