Jump to content

Package variables

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
My goal is to create a package variable which other files can then use.
Here's what I have now:
file:/tests/__init__.py
#!/usr/bin/python
# -*- coding: utf-8 -*'

import tests
import factories.testFactory

def setUpPackage():
    tests.cls = factories.testFactory.getClass("black")
The simple way would be to just insert the declaration below imports but then I get some problems with the type of the variable since the getClass-function is a factory and returns a class.
This code actually works but it "looks" wrong to me ; first import the package in which you are(tests) and then refer to yourself(tests.cls).
Is this the right way to do it ?
Is there another more dynamic way in which the code still works if it's moved to another directory ?
How about if I change the class name ?

Thanks in advance ..

ps. the setUpPackage is the function name that nose recognizes ..

#2
manux

manux

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 234 posts
Afaik the correct way of using a package "within itself" is effectively to import the said package and use it as a "local" package.

Here are a few tips from PEP 8:

Quote

Global Variable Names

(Let's hope that these variables are meant for use inside one module
only.) The conventions are about the same as those for functions.

Modules that are designed for use via "from M import *" should use the
__all__ mechanism to prevent exporting globals, or use the older
convention of prefixing such globals with an underscore (which you might
want to do to indicate these globals are "module non-public").

You also might want to read PEP 328, depending on what version of Python you use.

Personally I don't really like this syntax either, so I just import my package's modules as relative imports.
i.e. if I have a module abc.py, __init__.py will not import tests.abc, just import abc.
It works too ;)

#3
denarced

denarced

    Programmer

  • Members
  • PipPipPipPip
  • 182 posts
So what I'm doing is actually "correct" ..
Ok then ..
Thanks!

#4
billyy2288

billyy2288

    Newbie

  • Members
  • Pip
  • 3 posts
Thanks you for the post.