Usama
Usama

Reputation: 480

Pass arg while importing

How can I pass an argument to a Python module while importing it?

For instance, while running a script from command line, I can do this:

python script.py [arg1] [arg2]  

I want to do the same while I am importing a module in python

I have two modules, one.py and two.py

one.py:

name='TestTab'
import two [arg(which i want to be name variable)] 
tweet = Tweet()

two.py:

import sqlalchemy
name= [received arg]
class Tweet():
    __tabname__ = name
    id = Column(String(255))

Basically, I want to create a new table every time I import two.py, and I want the name of the new table to be passed while importing.

Upvotes: 3

Views: 123

Answers (2)

Huy Le
Huy Le

Reputation: 667

Not really pythonic but a possible simplest way is to expose your variable out

one.py

import two
two.name = "test"
tweet = two.Tweet()

two.py

import sqlalchemy
name = None
class Tweet():
    __tabname__ = name
    id = Column(String(255))

Upvotes: 1

TessellatingHeckler
TessellatingHeckler

Reputation: 28983

That's not a feature of Python, and you're not using classes well by using class-level variables and no constructor. The way to approach this is to pass the parameter to the constructor of Tweet, and store the data as instance variables.

one.py

name='TestTab'
from two import Tweet
tweet = Tweet(whatever_name)

two.py

import sqlalchemy

class Tweet(object):
    def __init__(self, name):
        self.tabname = name
        self.id = Column(String(255))

Upvotes: 2

Related Questions