Jaigus
Jaigus

Reputation: 1502

How do I write global variables correctly in python?

I am using sqlalchemy for connection pooling, and I want to make an engine object available to the other modules. I created a module for utilities that other modules need, and it looks like this:

from sqlalchemy import [...]

_engine = create_engine(url)
_meta = MetaData()
_meta.bind = _engine

def get_meta():
       return _meta

def get_engine():
       return _engine

I tried doing this before without the leading underscore, and it didn't work. I was under the impression that the leading underscore was only a conventional style for private variables in python, but apparently it can effect the way code is interpreted? Anyway, I'm just trying to have one particular live engine object (which controls access to the database connection pool) available to other modules and would like to know the best practice for doing so, thank you.

Upvotes: 0

Views: 1038

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409472

From PEP008:

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

So yes the interpreter handles identifiers with leading underscores differently than identifiers without.

Upvotes: 4

Related Questions