Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #16824 > unrolled thread

Re: sending a variable to an imported module

Started byArnaud Delobelle <arnodel@gmail.com>
First post2011-12-08 11:55 +0000
Last post2011-12-08 11:55 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: sending a variable to an imported module Arnaud Delobelle <arnodel@gmail.com> - 2011-12-08 11:55 +0000

#16824 — Re: sending a variable to an imported module

FromArnaud Delobelle <arnodel@gmail.com>
Date2011-12-08 11:55 +0000
SubjectRe: sending a variable to an imported module
Message-ID<mailman.3409.1323345323.27778.python-list@python.org>
On 8 December 2011 11:28, Bastien Semene <bsemene@cyanide-studio.com> wrote:
> Hi list,
>
> I'm trying to pass a variable to an imported module without singletons.
> I've seen in the doc, and tested that I can't use global to do it :
>
> === module.py ===
> def testf():
>  print test
>
>
> === main.py ===
> global test
> test = 1
>
> imported_module = __import__(module, globals(), locals(), [], -1)
>
> importmodule.testf()
>
> === output ===
> NameError: global name 'test' is not defined
>
>
>
> While I was reading many (many) threads about singleton I read people
> claiming that singletons can always be avoided (I can't remeber the most
> relevant thread on stackoverflow).
> I don't want to start a new debate about singletons, I think Internet has
> enough debates yet.
>
> But in my case I'd like to access this variable anywhere and at anytime
> without having to pass it as a parameter everywhere (this variable is a
> configuration manager object).
> How can I achieve that without singletons ?
> I'm beginner in Python, that's why I'm maybe missing something obvious.

Put it in its own module and import that module in the places where it
is needed.  E.g. in your example:

== settings.py ==
test = 1

== module.py ==
import settings
def testf():
    print settings.testf

== main.py ==
import module
module.testf()

In every module that you need 'test', import settings and you will be
able to access test.  This is why singletons are often not needed in
Python (just like most other design patterns).

-- 
Arnaud

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web