Python - libraries without import "*"

Asked

Viewed 106 times

1

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

Who will 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 *.

  • How so library?

  • A library in Python that I would create, only with the function imprimir().

  • You want to add the print function to the namespace but you don’t want to have to import it?

  • 1

    And why you need this?

  • I don’t want to write from biblio import *, want to write only import biblio

  • You can as long as the file is in the same directory.

  • You say I can do import biblio only if it is in the same folder, otherwise: from biblio import imprimir, this?

  • @Henrique Exatamente.

  • Thanks, and why it appears that this post is unanswered?

  • I will add an answer.

  • Ah, all right. = D

  • Don’t forget to set the answer as correct if it has cleared your doubts.

Show 7 more comments

2 answers

2


When importing the other module with import nome_da_biblioteca it runs and its namespace is added to the current module in a module type object with the same name as the module.

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

import nome_da_biblioteca
nome_da_biblioteca.imprimir()

p = nome_da_biblioteca.imprimir
p()
  • Thanks had not seen the mistake.

  • And yet you helped me, Thiago.

1

You can do the import of an archive in Python using the following declarations.

# foo.py

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


# bar.py

import foo

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

As long as it is set in the same directory I can simply make a import <nome_do_arquivo> now let’s 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’d do it this way:

# foo.py

import functions.foo 

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

This is just an abridged explanation of what it is possible to do to import files into Python if you want to go deeper I suggest you study further: Modules and Packages.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.