0

As the title suggests, I want to import a specific set of variables from a module (I cannot import *, and I don't want to write a long list of variables in the import line of the code).

A better way to explain this - how can I sequence a module that I create in a way that will allow me to import specific blocks of code, for example:

Module:

'''not to import'''
var1 = 'var1'

'''variables to import'''
var2 = 'var2'   

'''not to import'''
var3 = 'var3'

File:

from Module import (second block of code)
print(var2)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 2
    from Module import var2 ? – Swetank Poddar Jan 02 '20 at 17:28
  • Modules can define a variable named `__all__` as described in the [documentation](https://docs.python.org/3/tutorial/modules.html#importing-from-a-package) to designate what variables should exported. – martineau Jan 02 '20 at 17:30
  • There is no interface for importing a named subset of names from a module. You either import everything (modulo the value of `__all__`, and excluding `_`-prefixed names) via `*` or nothing. – chepner Jan 02 '20 at 17:30
  • 1
    You've identified your design problem quite well: you have distinct groups of things you want to import. Thus, they belong in separate modules. – Prune Jan 02 '20 at 17:30
  • You could cluster each group into a `dict`, import only the `dict`s you want, and then un-bundle them with a tuple assignment. Again, this seems to defeat the purpose of a `module`. – Prune Jan 02 '20 at 17:31
  • You could use global variables (although this brings with it a new set of problems) as in https://stackoverflow.com/questions/13034496/using-global-variables-between-files. – DerekG Jan 02 '20 at 17:32
  • When importing variables from file, whole script is executed. Thus, code inside your Module file will nonetheless be executed. If you want to import specific portion of code, one way would be to put it into different file and do import *. – H S Jan 02 '20 at 17:32
  • Off-topic: Note that [PEP 8](https://www.python.org/dev/peps/pep-0008/#package-and-module-names) suggests that module names be all lowercase. – martineau Jan 02 '20 at 17:36
  • Splitting the module into multiple modules doesn't help; that would only allow `from foo import *` where otherwise `*` would include more names than desired, and the OP has already said that `... import *` is not an option. – chepner Jan 02 '20 at 18:39

1 Answers1

0

One way you might consider doing this which would avoid global variables would be to collect all the variables you want to import into a class as class attributes. Something like:

/Module.py

a = 1
b = 2

class foo(object):
    x = 10
    y = 20

c = 3
d = 4

Then you could import x and y (and not the other variables) like:

from Module import foo

Then you could access x and y like:

foo.x and foo.y

Swazy
  • 378
  • 3
  • 10