Kurt Peek
Kurt Peek

Reputation: 57471

Syntax of importing multiple classes from a module

I'm reading some code which contains the following import statement:

from threading import local as thread_local, Event, Thread

At first this syntax puzzled me, but I think it is equivalent to:

from threading import local as thread_local
from threading import Event
from threading import Thread

Can anyone confirm whether this is the case?

Upvotes: 5

Views: 8957

Answers (3)

Jannis Ioannou
Jannis Ioannou

Reputation: 2201

Yes the two syntaxes are equivalent and also equivalent with:

from threading import (
   local as thread_local, 
   Event, 
   Thread
)

Answer based on the title:

Syntax of importing multiple classes from a module

from PyQt5.QtWidgets import (
  QWidget, 
  QLCDNumber,
  QSlider,
  QVBoxLayout, 
  QApplication)

Upvotes: 0

vlad-ardelean
vlad-ardelean

Reputation: 7622

Yes, it is.

Check out all the ways that one can import a module in python: https://docs.python.org/2/reference/simple_stmts.html#the-import-statement

Upvotes: 0

Bakuriu
Bakuriu

Reputation: 101959

You can check this on the official documentation. Here's the documentation for the import syntax:

import_stmt     ::=  "import" module ["as" name] ( "," module ["as" name] )*
                     | "from" relative_module "import" identifier ["as" name]
                     ( "," identifier ["as" name] )*
                     | "from" relative_module "import" "(" identifier ["as" name]
                     ( "," identifier ["as" name] )* [","] ")"
                     | "from" module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+
name            ::=  identifier

Note how you always have the import module ["as" name] and identifier ["as" name], including in the list definition:

( "," identifier ["as" name] )* 

This means a comma , followed by an identifier, optionally assigned with as to a name and the )* means "this group can be repeated zero or more times, which includes the example you provided.

This is also explained on the same page a bit later on:

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;
  2. for each of the identifiers specified in the import clauses:
    1. check if the imported module has an attribute by that name
    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    3. if the attribute is not found, ImportError is raised.
    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

Upvotes: 3

Related Questions